平时在开发的时候为了方便定时任务执行某些方法,我们可以通过tp的自定义命令行来实现
首先创建一个 application/common/command/Action.php
setName('action')
->addArgument('route', Argument::OPTIONAL, "your run route path! ")//路由地址必须输入
->addOption('option', 'o', Option::VALUE_REQUIRED, 'set Controller Argument')//参数选填
->setDescription('Command run Controller Action!');
}
protected function execute(Input $input, Output $output)
{
$Argument = $input->getArguments();
if ($Argument['command'] == 'action') {
if ($input->hasOption('option')) {
$result = action($this->route($Argument['route']), $input->getOption('option'));
$output->writeln($result);
} else {
$result = action($this->route($Argument['route']));
$output->writeln($result);
}
}
}
public function route($route = '')
{
if ($route) {
$route = explode('/', $route);
$module = isset($route[0]) ? $route[0] : 'index';
$controller = isset($route[1]) ? $route[1] : 'index';
$action = isset($route[2]) ? $route[2] : 'index';
return $module . '/' . $controller . '/' . $action;
}
return $route;
}
}
然后在 application/command.php 添加
return [
'app\common\command\Action',
];
最后执行 php think
我们创建 application/index/controller/Test.php 并添加如下内容
namespace app\index\controller;
use think\Controller;
/**
* 前台首页控制器
*
* @package app\index\controller
*/
class Test extends Controller
{
public function test($a = '')
{
return 'Test Commant :' . $a;
}
最后我们来测试一下输入如下命令
>php think action index/test/test -o a=1