如何制作自定义服务命令?

时间:2019-09-26 16:47:52

标签: laravel laravel-6

我实际上是在过去的项目中做到这一点,并且正在运行,但是现在它的新版本是 6.0 ,而我以前使用的是 5.8 。< / p>

所以我尝试了,我只是创建了一个命令:

php artisan make:command CustomServeCommand

然后将这些代码放入 CustomServeCommand 类中:

protected function getOptions()
{
    return [
        ['host', null, InputOption::VALUE_OPTIONAL, 'The host address to serve the application on.', '127.0.1.1'],//default 127.0.0.1
        ['port', null, InputOption::VALUE_OPTIONAL, 'The port to serve the application on.', 80],
    ];
}

当我php artisan serve无效时。

实际上,以上代码在 5.8 版本中正常工作,返回了以下行:

Laravel development server started: <http://127.0.1.1:80>


我现在的问题是如何在6.0版中制作自定义服务命令:

我要提供127.0.0.1:8000而不是127.0.1.1:80

有人知道如何实现这一目标吗?


已编辑

  

注意:这只是为了减少帖子,我无意在图像中发布代码。

还有 5.8 enter image description here

这是 6.0 enter image description here

中生成的代码

2 个答案:

答案 0 :(得分:1)

因为在5.8版本中,您扩展了,所以作曲者在之前加载了现有的命令,而在6.0中则不是 >

像这样扩展现有的serve命令

这就是您所需要的(删除其余生成的代码)

在6.0.0中测试

<?php

namespace App\Console\Commands;

use Illuminate\Foundation\Console\ServeCommand;
use Symfony\Component\Console\Input\InputOption;

class CustomServeCommand extends ServeCommand
{
    protected function getOptions()
    {
        return [
            ['host', null, InputOption::VALUE_OPTIONAL, 'The host address to serve the application on.', '127.0.1.1'], //default 127.0.0.1
            ['port', null, InputOption::VALUE_OPTIONAL, 'The port to serve the application on.', 80],
        ];
    }
}

并且Console\Kernel

中注册命令

您的端口选择有些奇怪,因此您必须做几件事

停止已经使用该端口的服务(假设Linux)

sudo service nginx stop 
# or
sudo service apache2 stop 

以root特权执行命令

sudo php artisan serve

结果

~/Sites/laravel (master ✗) ✹ ★ ᐅ  sudo php artisan serve
Laravel development server started: <http://127.0.1.1:80>
[Thu Sep 26 18:04:02 2019] Failed to listen on 127.0.1.1:80 (reason: Address already in use)
~/Sites/laravel (master ✗) ✹ ★ ᐅ  sudo service nginx stop
~/Sites/laravel (master ✗) ✹ ★ ᐅ  sudo php artisan serve 
Laravel development server started: <http://127.0.1.1:80>
^C
~/Sites/laravel (master ✗) ✹ ★ ᐅ  php artisan serve
Laravel development server started: <http://127.0.1.1:80>
[Thu Sep 26 18:04:23 2019] Failed to listen on 127.0.1.1:80 (reason: Permission denied)
~/Sites/laravel (master ✗) ✹ ★ ᐅ  sudo php artisan serve
Laravel development server started: <http://127.0.1.1:80>
[Thu Sep 26 18:10:28 2019] 127.0.0.1:58714 [200]: /robots.txt
[Thu Sep 26 18:10:29 2019] 127.0.0.1:58716 [200]: /favicon.ico

PS:我个人不建议这样做,端口80是标准的HTTP端口,不应由内置服务器使用

请注意,尽管有http://127.0.1.1访问权限,服务器仍会将请求代理到其他本地IP和端口

此外,我建议您试一下Laravel Valet(适用于Mac和Linux),因为它更容易在没有任何命令的情况下访问project.test

但是,我希望这会有所帮助

答案 1 :(得分:0)

为什么不将其作为参数传递?

对于端口8000:

php artisan serve --port=8080

如果要在端口80上运行它,则可能需要将其与sudo一起使用:

sudo php artisan serve --port=80