建立自定義指令行
第一步,配置command.php檔案,目錄在application/command.php
<?php
return [
'app\home\command\Test',
];
第二步,建立指令類檔案,建立application/home/command/Test.php
<?php
namespace app\home\command;
use think\console\Command;
use think\console\Input;
use think\console\Output;
class Test extends Command
{
protected function configure()
{
$this->setName('test')->setDescription('Here is the remark ');
}
protected function execute(Input $input, Output $output)
{
$output->writeln("TestCommand:");
}
}
了解:configure()方法裡面設定自定義的指令行指令,setName()方法是指令;setDescription()方法是該指令的描述。
execute()方法執行指令操作($this->其他的操作),指令操作在伺服器上一般不可見,故需要存入日志檔案,且無論該指令執行成功或失敗。
注意:可使用trace()助手函數記錄日志,第二個參數為錯誤級别。
try{
Log::init([
// 日志記錄方式,内置 file socket 支援擴充
'type' => 'File',
// 日志儲存目錄
'path' => ROOT_PATH.'/runtime/card_success/',
// 日志記錄級别
'level' => ['error'],
]);
// 執行代碼
echo 'success';
trace("success",'error');
} catch(Exception $e){
Log::init([
// 日志記錄方式,内置 file socket 支援擴充
'type' => 'File',
// 日志儲存目錄
'path' => ROOT_PATH.'/runtime/card_error/',
// 日志記錄級别
'level' => ['error'],
]);
trace("執行錯誤:(".date("Y-m-d H:i:s").")".$e->getMessage(),'error');
}
伺服器上定時指令行執行(以寶塔為例)
cd 根目錄
php think test