How to better organize your Laravel models

I often find myself wishing for more structure on models in a Laravel application.

By default, the models are in the Appnamespace , which can get very difficult to understand if you're working on a large application. So I App\Modelsdecided to organize my models within namespaces.

update user model

To do this, the first thing you need to do is move the Usermodels into the app/Modelsdirectory and update the namespace accordingly.

This requires you to update all files that reference the App\Userclass .

The first is config/auth.php:

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\Models\User::class, // 修改这里
        ],
    ],

The second is the config/services.phpfile :

    'stripe' => [
        'model' => App\Models\User::class, // 修改这里
        'key' => env('STRIPE_KEY'),
        'secret' => env('STRIPE_SECRET'),
    ],

Finally, modify the database/factories/UserFactory.phpfile :

$factory->define(App\Models\User::class, function (Faker $faker) {
    ...
});

generative model

Now we have changed the namespace of the Usermodel , but how to generate a new model. As we know they will be placed under the Appnamespace .

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 AppServiceProviderin :

<?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\Modelsthe namespace.

Hope you can use it!

For more PHP knowledge, go to PHPCasts

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325992117&siteId=291194637