I often find myself wishing for more structure on models in a Laravel application.
By default, the models are in the App
namespace , which can get very difficult to understand if you're working on a large application. So I App\Models
decided to organize my models within namespaces.
update user model
To do this, the first thing you need to do is move the User
models into the app/Models
directory and update the namespace accordingly.
This requires you to update all files that reference the App\User
class .
The first is config/auth.php
:
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class, // 修改这里
],
],
The second is the config/services.php
file :
'stripe' => [
'model' => App\Models\User::class, // 修改这里
'key' => env('STRIPE_KEY'),
'secret' => env('STRIPE_SECRET'),
],
Finally, modify the database/factories/UserFactory.php
file :
$factory->define(App\Models\User::class, function (Faker $faker) {
...
});
generative model
Now we have changed the namespace of the User
model , but how to generate a new model. As we know they will be placed under the App
namespace .
To fix this, we can extend the default ModelMakeCommand
:
<?php
namespace App\Console\Commands;
use Illuminate\Foundation\Console\ModelMakeCommand as Command;
class ModelMakeCommand extends Command
{
/**
* Get the default namespace for the class.
*
* @param string $rootNamespace
* @return string
*/
protected function getDefaultNamespace($rootNamespace)
{
return "{$rootNamespace}\Models";
}
}
and overwrite the existing bindings AppServiceProvider
in :
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Console\Commands\ModelMakeCommand;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
$this->app->extend('command.model.make', function ($command, $app) {
return new ModelMakeCommand($app['files']);
});
}
}
The above is what needs to be modified. Now we can go ahead and generate models like we did in our terminal: php artisan make:model Order
, they will be in App\Models
the namespace.
Hope you can use it!
For more PHP knowledge, go to PHPCasts