drewm / slim-commander
运行 CLI 命令作为您的 Slim 框架应用程序一部分的非常简单的结构
v0.1
2018-02-20 11:18 UTC
Requires
- php: >=5.5.0
- slim/slim: ^3.1
This package is auto-updated.
Last update: 2024-08-24 03:52:43 UTC
README
运行 CLI 命令作为您的 Slim 框架应用程序一部分的非常简单的结构。
这不是一个控制台工具。它只是您应用程序的 HTTP 入口点的并行,使您能够执行诸如创建作为 cronjobs 运行的脚本或设置基本队列监听器之类的操作。
用法
以 Slim-Skeleton 的结构为例,您的 public/index.php
执行以下操作
require __DIR__ . '/../vendor/autoload.php'; session_start(); // Instantiate the app $settings = require __DIR__ . '/../src/settings.php'; $app = new \Slim\App($settings); // Set up dependencies require __DIR__ . '/../src/dependencies.php'; // Register middleware require __DIR__ . '/../src/middleware.php'; // Register routes require __DIR__ . '/../src/routes.php'; // Run app $app->run();
您需要创建一个新的 PHP 脚本,类似于这个,用作您命令的入口点。它应该在 public
文件夹之外。例如 src/cli.php
。
require __DIR__ . '/../vendor/autoload.php'; // Instantiate the app $settings = require __DIR__ . '/settings.php'; $app = new \DrewM\SlimCommander\App($settings); // Set up dependencies require __DIR__ . '/dependencies.php'; // Register commands instead of routes require __DIR__ . '/commands.php'; // Run app $app->run($argv);
而不是路由,您可以在例如 src/commands.php
中定义命令。
$app->command('HelloWorld', 'HelloWorld:greet', [ 'name', ]);
参数是
- 命令的名称
- 回调,以与常规 Slim 路由回调相同的方式定义
- 期望的参数名称数组
在上面的例子中,第一个参数将作为 name
传递给回调
您的回调从其构造函数接收容器
class HelloWorld { private $container; public function __construct($container) { $this->container = $container; } public function greet($args) { echo "Hello " . $args['name']; } }
将其添加到您的容器中,就像您通常做的那样
$container['HelloWorld'] = function ($container) { return new \App\Commands\HelloWorld($container); };
然后您可以使用 php src/cli.php HelloWorld Fred
来执行它