自定义组件重写框架 artisan 快速创建 Controller 和 Model
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 协议》,转载必须注明作者和本文链接