首页 > 解决方案 > 您是否需要 Composer for async PHP 和像 ReactPHP 或 Swoole 这样的 HTTP 服务器?

问题描述

据我了解 Composer 用于通过 PHP 提供的 SPL 函数自动加载类,或者至少注册在类不存在时调用的方法。然后,这必须在每次请求使用 Laravel 或 CakePHP 进行传统设置时发生……

我的问题是,Composer 如何在 Swoole HTTP Server 环境中工作,您可以自由地预先加载所有内容?在这种情况下甚至需要 Composer 吗?

一个 Swoole HTTP PHP 服务器的基本术语如下所示:

<?php

// Load all your classes and files here?

$http = new swoole_http_server("127.0.0.1", 9501);

$http->on("start", function ($server) {
    echo "Swoole http server is started at http://127.0.0.1:9501\n";
});

$http->on("request", function ($request, $response) {
    $response->header("Content-Type", "text/plain");
    $response->end("Hello World\n");
});

$http->start();

所以我可以事先加载所有内容,而不必担心必须调用任何自动加载脚本?

然后所有类都将在全局范围内,因此所有内容都已预加载并准备好在->on("request")函数回调中使用。

标签: phpreactphpswoole

解决方案


您可以composer通过 Swoole 在 CLI 上下文中使用其自动加载功能。

PHP 的执行没有变化,所以自动加载器可以正常工作,只需包含vendor/autoload.phpat 相关脚本。

<?php

// Autoloader is now up, you can use new Your/Class;
require_once('vendor/autoload.php'); 

$http = new swoole_http_server("127.0.0.1", 9501);

$http->on("start", function ($server) {
    echo "Swoole http server is started at http://127.0.0.1:9501\n";
});

$http->on("request", function ($request, $response) {
    $response->header("Content-Type", "text/plain");
    $response->end("Hello World\n");
});

$http->start();

免责声明:我将 swoole 与 Laravel、Lumen 和自定义解决方案(CLI 和 fastcgi)/web 一起使用,它运行良好,并且在这种情况下使用 PHP 的方式没有改变。


推荐阅读