自定義元件重寫框架 artisan 快速建立 Controller 和 Model

Rxy-development發表於2019-09-25

GeneratorCommand.php

<?php

namespace Impecty\LaravelShop\Extend\Artisan\Make;

use Illuminate\Support\Str;
use Symfony\Component\Console\Input\InputArgument;

trait GeneratorCommand
{
    protected $packagePath = __DIR__.'/../../..';

    //獲取名稱空間
    protected function rootNamespace()
    {
        return 'Impecty\\LaravelShop';
    }

    //設定建立的位置
    protected function getPath($name)
    {
        $name = Str::replaceFirst($this->rootNamespace(), '', $name);

        return $this->packagePath.'/'.str_replace('\\', '/', $name).'.php';
    }

    //獲取寫入的名稱空間
    protected function getPackageInput()
    {
        return str_replace('/', '\\', trim($this->argument('package')));
    }

    //定義控制檯填寫時引數個數  =》  php artisan shop-make:controller {package} {name}
    protected function getArguments()
    {
        return [
            ['package', InputArgument::REQUIRED, 'The package of the class'],
            ['name', InputArgument::REQUIRED, 'The name of the class'],
        ];
    }

    //生成指定的模板引數替換
    protected function replaceNamespace(&$stub, $name)
    {
        $DummyRootNamespace = $this->rootNamespace().'\\'.$this->getPackageInput().'\\';
        $stub = str_replace(
            ['DummyNamespace', 'DummyRootNamespace', 'NamespacedDummyUserModel'],
            [$this->getNamespace($name), $DummyRootNamespace, $this->userProviderModel()],
            $stub
        );

        return $this;
    }

    //獲取建立檔案的預設存放路徑
    protected function getDefaultNamespace($rootNamespace)
    {
        return $rootNamespace.'\\'.$this->getPackageInput().$this->getDefaultNamespace;
    }
}
?>

ControllerMakeCommand.php

<?php

namespace Impecty\LaravelShop\Extend\Artisan\Make;

use Illuminate\Routing\Console\ControllerMakeCommand as Command;

class ControllerMakeCommand extends Command
{
    use GeneratorCommand;

    protected $name = 'shop-make:controller';

    protected $getDefaultNamespace = '\Http\Controllers';
}
?>

ModelMakeCommand.php

<?php

namespace Impecty\LaravelShop\Extend\Artisan\Make;

use Illuminate\Foundation\Console\ModelMakeCommand as Command;

class ModelMakeCommand extends Command
{
    use GeneratorCommand;
    protected $name = 'shop-make:model';

    protected $getDefaultNamespace = '\Models';
}
?>

ArtisanServiceProvider.php 服務容器需要在laravel框架app.php進行載入

<?php
namespace Impecty\LaravelShop\Extend\Artisan;

use Illuminate\Support\ServiceProvider;

class ArtisanServiceProvider extends ServiceProvider
{
    protected $command = [
        Make\ClassMakeCommand::class,
        Make\ModelMakeCommand::class,
        Make\ControllerMakeCommand::class,
    ];

    public function register()
    {
        $this->commands($this->command);
    }

    public function boot()
    {

    }

}
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章