ThinkPHP 5 命令行执行控制器方法!

 平时在开发的时候为了方便定时任务执行某些方法,我们可以通过tp的自定义命令行来实现

首先创建一个 application/common/command/Action.php 

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/12/23
 * Time: 12:35
 */

namespace app\common\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;

class Action extends Command
{
    protected function configure()
    {
        $this->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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值