自定义命令使用 symfony/console
包:
安装 symfony/console
composer require symfony/console
编写自定义命令脚本
下图所示的 Commands
目录,即为自定义的命令脚本,仿照的laravel的目录结构:
<?php
namespace console\commands;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputArgument;
class OpenServeCityLbs extends Command
{
protected function configure()
{
$this
->setName('Lbs:OpenServeCityLbs')
->setDescription('已开通服务城市lbs数据源');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
return 1;
}
}
命令列表
上图所示的 Kernel.php
文件:
<?php
namespace console;
class Kernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
public static $commands = [
//
\console\commands\Test::class,
\console\commands\Script\CreateAreaTable::class,
\console\commands\Script\OrderRefund::class,
\console\commands\Lbs\OpenServeCityLbs::class,
];
}
自定义命令入口文件
根目录下创建 artisan
文件作为命令入口文件(仿laravel框架的入口文件位置):
#!/usr/bin/env php
<?php
require __DIR__ . '/vendor/autoload.php';
use Dotenv\Dotenv;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Events\Dispatcher;
use support\constants\Project;
use Symfony\Component\Console\Application;
use console\Kernel;
use Webman\Config;
# 加载配置文件
if (method_exists('Dotenv\Dotenv', 'createUnsafeImmutable')) {
Dotenv::createUnsafeImmutable(base_path())->load();
} else {
Dotenv::createMutable(base_path())->load();
}
Config::reload(config_path(), ['route']);
foreach (config('autoload.files', []) as $file) {
include_once $file;
}
foreach (config('bootstrap', []) as $class_name) {
/** @var \Webman\Bootstrap $class_name */
$class_name::start('');
}
# 数据库初始化
if (!class_exists('\Illuminate\Database\Capsule\Manager')) {
exit('数据库操作缺少库文件:\Illuminate\Database\Capsule\Manager' . PHP_EOL);
}
$capsule = new Capsule;
$configs = config('database');
$default_config = $configs['connections'][$configs['default']];
$capsule->addConnection($default_config);
// 创建链接(多库配置)
foreach ($configs['connections'] as $name => $config) {
$capsule->addConnection($config, $name);
}
// 数据库查询事件
if (class_exists('\Illuminate\Events\Dispatcher')) {
$capsule->setEventDispatcher(new Dispatcher(new \Illuminate\Container\Container));
}
// 设置全局静态可访问
$capsule->setAsGlobal();
# sql语句监听
if (env('APP_DEBUG')) {
Capsule::connection()->listen(function ($query) {
//这里是执行sql后的监听回调方法
$sql = vsprintf(str_replace("?", "'%s'", $query->sql), $query->bindings) . " \t[" . $query->time . ' ms] ';
// 把SQL写入到日志文件中
dp($sql);
});
}
// 启动Eloquent
$capsule->bootEloquent();
# 命令操作
$application = new Application();
# 初始化自定义命令列表
foreach (Kernel::$commands as $command) {
$application->add(new $command);
}
Project::$REQUEST_ID = generate_uuid();
$application->run();
执行自定义命令
php artisan xxx:xxx
具体使用可参考 [symfony/console](http://www.symfonychina.com/doc/current/components/console.html)
使用文档。