0
点赞
收藏
分享

微信扫一扫

Laravel 如何使用 PHP 内置的服务器启动服务

大漠雪关山月 2022-04-02 阅读 108

在Laravel项目中,如果你在本地安装了 PHP, 并且你想使用 PHP 内置的服务器来为你的应用程序提供服务,则可以使用 Artisan 命令 serve 。该命令会在 ​​http://localhost:8000​​ 上启动开发服务器

一、如何启动PHP内置服务器?

php artisan serve


Laravel 如何使用 PHP 内置的服务器启动服务_php​​  


你也可以指定host和port进行启动,主要使用--host和--port参数

1.1 指定端口号

php artisan serve --port 8001


Laravel 如何使用 PHP 内置的服务器启动服务_服务器_02​​  


1.2 指定host,可以使用ip,也可以使用域名的形式

php artisan serve --host 127.0.0.2 --port 8001


Laravel 如何使用 PHP 内置的服务器启动服务_php_03​​  


二、php artisan serve命令如何运行的?

有人比较好奇为什么执行这个命令就可以运行服务了呢?

其实从 PHP 5.4 版本开始,PHP 就已经内置(built in)了一个 web server,并且,Laravel 的 artisan 命令也支持这个内置web server,这让快速启动服务变得更高效了。当然,如果要部署到生产服务器上的话,还是要安装 apache 或 nginx 之类的 web server 的。

接下来我们来分析下laravel的命令:​​php artisan serve​

2.1 源文件ServeCommand.php

注意:此次laravel项目是基于6.20.26版本

源文件是src/Illuminate/Foundation/Console/ServeCommand.php

<?php

namespace Illuminate\Foundation\Console;

use Illuminate\Console\Command;
use Illuminate\Support\Env;
use Illuminate\Support\ProcessUtils;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Process\PhpExecutableFinder;

class ServeCommand extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'serve';

/**
* The console command description.
*
* @var string
*/
protected $description = 'Serve the application on the PHP development server';

/**
* The current port offset.
*
* @var int
*/
protected $portOffset = 0;

/**
* Execute the console command.
*
* @return int
*
* @throws \Exception
*/
public function handle()
{
chdir(public_path());

$this->line("<info>Laravel development server started:</info> http://{$this->host()}:{$this->port()}");

passthru($this->serverCommand(), $status);

if ($status && $this->canTryAnotherPort()) {
$this->portOffset += 1;

return $this->handle();
}

return $status;
}

/**
* Get the full server command.
*
* @return string
*/
protected function serverCommand()
{
return sprintf('%s -S %s:%s %s',
ProcessUtils::escapeArgument((new PhpExecutableFinder)->find(false)),
$this->host(),
$this->port(),
ProcessUtils::escapeArgument(base_path('server.php'))
);
}

/**
* Get the host for the command.
*
* @return string
*/
protected function host()
{
return $this->input->getOption('host');
}

/**
* Get the port for the command.
*
* @return string
*/
protected function port()
{
$port = $this->input->getOption('port') ?: 8000;

return $port + $this->portOffset;
}

/**
* Check if command has reached its max amount of port tries.
*
* @return bool
*/
protected function canTryAnotherPort()
{
return is_null


举报

相关推荐

0 条评论