spajak/flow

简单的PHP应用基础

dev-master 2024-06-15 09:37 UTC

This package is auto-updated.

Last update: 2024-09-15 10:29:11 UTC


README

使用PSR-7 HTTP消息/PSR-17 HTTP工厂的简单PHP HTTP应用基础

原理

  • 基于标准化接口和经过良好测试的组件;
  • 不依赖于任何特定框架;
  • 只需使用PHP的include和匿名函数即可快速创建轻量级和可自定义的应用程序。

用法

$app = new Flow\Application;

注册服务(使用: php-di/php-di

$services = [];
$services['hello'] = function() {
    return new class {
        public function sayHello($name) { return "Hello {$name}!"; }
    };
};
$app->getContainerBuilder()->addDefinitions($services);

注册路由(使用: nikic/fast-route

$app->getRouteCollector()->get('/hello[/{name}]', function($request, $name = 'World') use ($app) {
    $container = $app->getContainer();
    $response = $container->get('http_factory')->createResponse(200);
    $response->getBody()->write(
        $container->get('hello')->sayHello($name)
    );
    return $response;
});

注册控制台命令(使用: symfony/console

$app->getConsole()->register('hello')
    ->setDescription('Say hello')
    ->addArgument('name', null, 'Your name', 'World')
    ->setCode(function($input, $output) use ($app) {
        $service = $app->getContainer()->get('hello');
        $output->writeLn($service->sayHello($input->getArgument('name')));
    });

…或使用工厂进行懒加载命令

use Flow\Command\RequestCommand;
use Flow\Emitter\ConsoleEmitter;

$commands = [];
$commands['request'] = function() use ($app) {
    return new RequestCommand(
        $app->getServerRequestCreator(),
        $app->getBroker(),
        new ConsoleEmitter
    );
}
$app->getCommandLoader()->addFactories($commands);

脚本结束时,只需运行应用程序即可

$app->run();

从终端尝试

$ php examples/application.php hello "Grim Reaper"
$ php examples/application.php request GET /hello

许可证

MIT