Phalcon 是高性能 PHP 框架,其 CLI 應用模塊專為後台任務、定時腳本、命令行工具設計。本文系統梳理結構、引導、任務定義、參數處理與任務鏈調用。
app/ ├── config/ │ └── config.php ├── tasks/ │ └── MainTask.php └── cli.php # 入口文件
cli.php 詳解registerDirs([APPLICATION_PATH . '/tasks']);
$loader->register();
// 4. 載入配置(可選)
if (is_readable(APPLICATION_PATH . '/config/config.php')) {
$config = include APPLICATION_PATH . '/config/config.php';
$di->set('config', $config);
}
// 5. 創建 Console 應用
$console = new ConsoleApp();
$console->setDI($di);
// 6. 解析命令行參數 argv -> arguments 數組
$arguments = [];
foreach ($argv as $k => $arg) {
if ($k == 1) $arguments['task'] = $arg;
elseif ($k == 2) $arguments['action'] = $arg;
elseif ($k >= 3) $arguments['params'][] = $arg;
}
// 7. 定義全局常量(供任務內部使用)
define('CURRENT_TASK', $argv[1] ?? null);
define('CURRENT_ACTION', $argv[2] ?? null);
try {
$console->handle($arguments);
} catch (\Phalcon\Exception $e) {
echo $e->getMessage(); exit(255);
}
MainTask.php運行示例
$ php app/cli.php This is the default task and the default action $ php app/cli.php main test world universe hello world best regards, universe任務鏈調用:在一個 Action 中調用另一 Action
- 在 DI 中共享 Console 實例:
$di->setShared('console', $console);- 任務中注入
$this->console並調用handle():class MainTask extends \Phalcon\CLI\Task { public function mainAction() { echo "\nDefault action\n"; $this->console->handle([ 'task' => 'main', 'action' => 'test' ]); } public function testAction() { echo "\nI will get printed too!\n"; } }更優雅的方式是繼承基類封裝
runTask($task, $action, $params)方法。進階技巧
config.php 返回數組,可配置數據庫、日誌、路徑等;\Phalcon\Exception 統一退出碼 255;array $params,框架自動綁定;PHP_EOL 換行,sprintf 格式化,避免雙引號轉義。registerDirs 掃描 tasks 目錄,導致找不到 Task 類;argv[0] 是腳本路徑,業務參數從 argv[1] 開始;$_GET/$_POST,所有輸入來自 $argv 或配置文件;set_time_limit(0) 並妥善處理信號。掌握上述核心流程,即可用 Phalcon 快速構建健壯、可維護的命令行應用與後台任務系統。