以创建控制器为例
1、先通过 think 命令创建一个make文件,效果如下图:
php think make:command make/MyController
2、修改上面创建的文件【MyController.php】
<?php
declare (strict_types = 1);
namespace app\command\make;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
class MyController extends Command
{
protected function configure()
{
// 指令配置
$this->setName('mycontroller')
->setDescription('the mycontroller command');
}
protected function execute(Input $input, Output $output)
{
// 指令输出
$output->writeln('mycontroller');
}
}
/***************************************** 上面是原来的内容,下面是修改后的内容 *****************************************/
<?php
declare (strict_types = 1);
namespace app\command;
use think\console\command\Make;
/**
* 自定义控制器模板
* Class MyController
* @package app\command
*/
class MyController extends Make
{
protected $type = "MyController";
protected function configure()
{
parent::configure();
$this->setName('make:myController')
->setDescription('Create a new self controller class');
}
public function getStub(): string
{
$stubPath = __DIR__ . DIRECTORY_SEPARATOR . 'stubs' . DIRECTORY_SEPARATOR;
return $stubPath . 'controller.stub';
}
protected function getClassName(string $name): string
{
return parent::getClassName($name) . ($this->app->config->get('route.controller_suffix') ? 'Controller' : '');
}
protected function getNamespace(string $app): string
{
return parent::getNamespace($app);
}
}
3、在 app/command/make 目录下创建名为【stubs】的目录,且在【stubs】下创建一个名为【controller.stub】的文件,效果如下图:
4、找到项目中原有的【controller.stub】文件,具体位置在【vendor/topthink/framework/src/think/console/command/make/stubs/controller.stub】。复制原有文件中的内容到新建的【controller.stub】中。
注意:【controller.stub】模板中的变量只有下图中的四个。
5、在【config/console.php】中加入第一步中创建的命令,效果如下图:
6、现在可以通过 think 的命令查看我们所创建的自定义命令,结果如下图:
php think
7、使用自定义的think命令创建一个名为【Test】控制器类,效果如下图:
//admin/controller/Test 这是文件的路径+文件名,根据自己项目调整
php think make:myController admin/controller/Test