statix / server
PHP内置服务器的面向对象包装
Requires
- php: >=8
- symfony/process: ^6.0
- vlucas/phpdotenv: ^5.4
Requires (Dev)
- guzzlehttp/guzzle: ^7.4
- illuminate/http: ^9.21
- laravel/pint: ^1.0
- pestphp/pest: ^1.21
- spatie/invade: ^1.1
README
Statix Server是一个PHP包,它提供了一个简单的配置和启动本地PHP服务器的方法,以满足您的Web开发需求。
要求
- PHP 8最低要求
安装
您可以通过composer安装此包
composer require statix/server
在Packagist上查看:https://packagist.org.cn/packages/statix/server
基本用法
要开始使用,请引入供应商自动加载脚本,并创建一个Server
类的实例。在设置任何配置选项后,调用start
方法来启动服务器。
use Statix\Server\Server; require_once './vendor/autoload.php'; Server::new()->start(); // or (new Server)->start();
配置
您可以使用服务器配置几个选项,例如主机、端口、根目录等。请参阅以下部分,以详细了解每个配置方法的详细说明。
通过构造函数或Server::new()传递配置
您可以通过构造函数传递大多数配置选项。例如,以下代码中我们设置了host
、port
和root
选项。
use Statix\Server\Server; Server::new([ 'host' => 'localhost', 'port' => 8000, 'root' => __DIR__ . '/content' ]); // or new Server([ 'host' => 'localhost', 'port' => 8000, 'root' => __DIR__ . '/content' ]);
可以通过构造函数传递的完整配置项列表如下。
$optionsSettableViaContructor = [ 'host' => 'string', // default: localhost 'port' => 'string|int', // default: 8000 'root' => 'string', // default: getcwd() 'router' => 'string', // path to your routing script 'php' => 'string', // path to the desired PHP binary to use for the server process 'withEnvVars' => [ 'APP_DYNAMIC_ENV' => 'server' ], 'withoutEnvVars' => [ 'APP_KEY' ] ];
通过命名方法设置配置
您还可以通过以下方式调用命名方法来设置配置选项,如下所示。
use Statix\Server\Server; Server::new() ->php('path') ->host('localhost') ->port('8080') ->root('./content') ->router('./router.php') ->withEnvVars([ 'APP_DYNAMIC_ENV' => 'server' ])->withoutEnvVars([ 'APP_KEY', ])->withEnvFile('path/to/.env');
捕获服务器进程的输出
如果您想显示服务器进程接收和处理请求时的输出,您可以调用output
方法,并传递一个回调函数,该函数将被调用并传递进程的任何输出。
Server::new() ->output(function($output) { echo $output; })->start();
在后台运行进程
您可能会发现将服务器进程在后台运行很有用,您可以通过调用runInBackground()
来实现。只要父脚本正在运行,进程就会运行。
Server::new()->runInBackground();
检查进程是否正在运行
您可以通过调用isRunning
方法来检查服务器是否正在运行。
$server = Server::new()->withEnvVars([ 'APP_NAME' => 'statix/server', ]); $server->isRunning(); // false $server->runInBackground(); $server->isRunning(); // true
停止服务器
您可以通过在服务器类的实例上调用stop命令来停止运行服务器的进程。如果服务器当前没有运行,此方法将返回null
,否则它将返回一个数组,其中首先包含进程的退出代码,其次包含进程的退出文本。请注意,此命令只能在服务器在后台运行时调用。
$server = Server::new()->runInBackground(); // do work $server->stop();
重新启动服务器
您可以通过在服务器类的实例上调用restart
方法来重新启动服务器。您可能需要重新启动服务器的原因之一是检测到您的.env
文件已更改,您可以通过重新启动服务器并确保环境变量已加载来确保这一点。
$server = Server::new()->runInBackground(); // do work $server->restart(); // do more work $server->stop();
贡献
安装
- 克隆仓库
git clone https://github.com/statix-php/server.git
- 安装PHP依赖项
composer install
测试
我们使用Pest PHP进行测试套件,请在推送更改之前确保没有破坏性的更改,请运行以下命令。此外,强烈鼓励为新的功能编写测试,更改将在没有测试的情况下考虑,但这将增加接受/合并的时间。
./vendor/bin/pest
样式
我们使用Laravel Pint来自动标准化代码样式,请在推送更改之前,使用以下命令运行pint
。
./vendor/bin/pint