preface

When developing with Laravel or other frameworks, it is common to create a Model base class that all models inherit from. However, the models created using the Laravel Artisan console instruction do not inherit from the base class I created. In order to avoid manual changes every time, Need to rewrite the source code generation method

Read the source code and analyze it

The service provider is the center of the Laravel application startup. All service providers are registered through the config/app.php configuration file, so we go straight to the config/app.php file to find the service provider on the console

After open the ConsoleSupportServiceProvider. PHP, found that there are three service providers, the target file is Artisan console service provider, ignoring the other two files



readingArtisanServiceProvider.phpAfter the code, I found a way to register the create Model commandregisterModelMakeCommand 



Finally openedModelMakeCommand.phpFile, found the Model generator filestubs/model.stub



Analysis: Only modification is requiredstubs/model.stubInstead of modifying the source code directly, create a new ModelMakeCommand service and rewrite itgetStubMethod to rebind to the service container

Custom model creation command service

Create the Customize directory in the project root directory to store the custom framework classes. Here I use the directory where the source ModelMakeCommand. PHP file is stored. Create Customize/Foundation/Console/ModelMakeCommand. PHP files, and source class inheritance

<?php

namespace App\Customize\Foundation\Console;

class ModelMakeCommand extends \Illuminate\Foundation\Console\ModelMakeCommand
{
    protected function getStub()
    {
        if ($this->option('pivot')) {
            return parent::getStub();
        }
        return __DIR__ . '/stubs/model.stub';
    }
}
Copy the code

Create the stubs/model.stub file in the current file directory

<? php namespace DummyNamespace; use App\Customize\Database\Eloquent\Model; Class DummyClass extends Model {//}Copy the code

Rebind the model to create the command service

Two ways:

  1. Directly in the AppServiceProvider.php Rebind the new ModelMakeCommand service in
  2. Create a new service provider andAppend it to the configuration fileconfig/app.php theproviders In the array

test

Create a model using PHP Artisan Make: Model Test, verify that the model is inherited from the custom Model base class