Phalcon搭建多模块框架二十九是创建多模块命令行应用,但有时候项目很小,可能命令行应用只有几个文件不需要分模块。这个时候单模块就很方便。
在开始之前还是需要用到二十九中的前两步,创建define.php文件。
1、在cli目录下创建cli.php文件
<?php
/**
* @desc 命令行入口文件
* @author: ZhaoYang
* @date: 2018年6月17日 下午5:42:16
*/
use Phalcon\Cli\Console;
// 检查版本,搭建用到php7一些新特性
version_compare(PHP_VERSION, '7.0.0', '>') || exit('Require PHP > 7.0.0 !');
extension_loaded('phalcon') || exit('Please open the Phalcon extension !');
// 引入自定义常量文件
require '../config/define.php';
version_compare(PHP_VERSION, '3.0.0', '>') || exit('Require Phalcon > 3.0.0 !');
// 设置时区
date_default_timezone_set('Asia/Shanghai');
// error_reporting(E_ALL & ~E_NOTICE);
try {
// 引入配置文件
$config = require BASE_PATH . 'config/config_' . NOW_ENV . '.php';
// 引入cli配置文件
$cliConfig = require BASE_PATH . 'cli/config/config_' . NOW_ENV . '.php';
// 引入自动加载配置
require BASE_PATH . 'config/loader.php';
// 通常还可能用到各模块的模型
$registerNamespaces = [];
foreach (MODULE_ALLOW_LIST as $v) {
$registerNamespaces[APP_NAMESPACE . '\\' . ucfirst($v) . '\\Models'] = APP_PATH . $v . '/models' . DS;
}
$loader->registerNamespaces($registerNamespaces, true)->registerDirs($cliConfig['application']['register_dirs'], true)->register();
// 引入注册服务
require BASE_PATH . 'cli/config/services.php';
// 处理请求
$console = new Console($di);
// 设置选项
$console->setArgument($argv);
$arguments = [];
foreach ($argv as $k => $arg) {
if ($k === 1) {
$arguments['task'] = $arg;
} elseif ($k === 2) {
$arguments['action'] = $arg;
} elseif ($k >= 3) {
$arguments['params'][] = $arg;
}
}
// 处理请求
$console->handle($arguments);
} catch (\Throwable $e) {
$previous = $e->getPrevious();
$consoleConfig = $console->config->application;
if ($consoleConfig->debug->state ?? false) {
if (empty($consoleConfig->debug->path)) {
echo 'Exception: ', PHP_EOL, '所在文件:', $e->getFile(), PHP_EOL, '所在行:', $e->getLine(), PHP_EOL, '错误码:', $e->getCode(), PHP_EOL, '错误消息:', $e->getMessage(), PHP_EOL, PHP_EOL;
if (!is_null($previous)) {
echo '前一个Exception: ', PHP_EOL, '所在文件:', $previous->getFile(), PHP_EOL, '所在行:', $previous->getLine(), PHP_EOL, '错误码:', $previous->getCode(), PHP_EOL, '错误消息:', $previous->getMessage(), PHP_EOL, PHP_EOL;
}
exit();
}
$errorFile = $consoleConfig->debug->path;
$errorType = 'debug';
} else {
$errorFile = $consoleConfig->error->path;
$errorType = 'error';
}
$errorMessage = 'Exception: [所在文件:' . $e->getFile() . '] [所在行:' . $e->getLine() . '] [错误码:' . $e->getCode() . '] [错误消息:' . $e->getMessage() . '] '/* . PHP_EOL . '[异常追踪信息:' . $e->getTraceAsString() . ']' */;
if (!is_null($previous)) {
$errorMessage .= ' 前一个Exception: [所在文件:' . $previous->getFile() . '] [所在行:' . $previous->getLine() . '] [错误码:' . $previous->getCode() . '] [错误消息:' . $previous->getMessage() . '] '/* . PHP_EOL . '[异常追踪信息:' . $previous->getTraceAsString() . ']' */;
}
$console->di->get('logger', [
$errorFile
])->$errorType</