用AI赚第一桶💰低成本搭建一套AI赚钱工具,源码可二开。 广告
## 创建命令 命令就是一个命令行程序,`Command` 类似于 HTTP 应用的 `Controller` 控制器,负责业务逻辑,不同的是命令行程序通常是处理复杂的数据处理逻辑,相比简单的 `CRUD` 操作要复杂很多。 | 类 | | --- | | mix\console\Command | >[info] 初始代码中命令行应用的命令在 commands 目录。 ## 一个简单的命令 首先在配置文件中增加命令。 ~~~ // 命令 'commands' => [ 'clear exec' => ['Clear', 'Exec'], ], ~~~ 详解命令规则: - 命令:`clear exec` - 命令类的类名,不包括 Command 后缀:`Clear` - 命令类的方法名,不包括 action 前缀:`Exec` 创建命令类,代码如下: ~~~ <?php namespace apps\console\commands; use mix\console\Command; use mix\console\ExitCode; use mix\facades\Output; /** * Clear 命令 * @author 刘健 <coder.liu@qq.com> */ class ClearCommand extends Command { // 执行任务 public function actionExec() { // 响应 Output::writeln('SUCCESS'); // 返回退出码 return ExitCode::OK; } } ~~~ ## 命名空间与文件位置的关系 控制器定义的命名空间为: ~~~ namespace apps\console\commands; ~~~ 因为根命名空间 `apps` 在 `composer.json` 内定义的路径为 : ~~~ "apps\\": "apps/" ~~~ 所以控制器的完整路径为: ~~~shell apps/console/commands/ClearCommand.php ~~~ ## 命令行执行 执行上面写的命令。 ~~~shell mix-console clear exec ~~~ ## 如何使用命令选项 修改上面的命令类,代码如下: ~~~ <?php namespace apps\console\commands; use mix\console\Command; use mix\console\ExitCode; use mix\facades\Input; use mix\facades\Output; use mix\helpers\ProcessHelper; /** * Clear 命令 * @author 刘健 <coder.liu@qq.com> */ class ClearCommand extends Command { // 是否后台运行 public $daemon = false; // 选项配置 public function options() { return ['daemon']; } // 选项别名配置 public function optionAliases() { return ['d' => 'daemon']; } // 执行任务 public function actionExec() { // 蜕变为守护进程 if ($this->daemon) { ProcessHelper::daemon(); } // 修改进程名称 Process::setName('mix-crontab: ' . Input::getCommandName()); // 响应 Output::writeln('SUCCESS'); // 返回退出码 return ExitCode::OK; } } ~~~ - options 方法定义了一个 daemon 选项,所以命令只会接收 `--daemon` 选项。 - optionAliases 方法给 daemon 选项定义了一个别名,所以 `-d` 等效于 `--daemon` 。 执行上面写的命令,并传入选项: ~~~shell mix-console clear exec -d ~~~