Home > Backend Development > PHP Tutorial > Laravel怎么自定义command命令

Laravel怎么自定义command命令

PHPz
Release: 2020-09-05 11:52:27
Original
2925 people have browsed it

Laravel自定义command命令的方法:首先创建command类;然后在“stubs”文件下创建自定义模板文件;最后通过“php artisan make:service Web/TestService”运行测试即可。

Laravel怎么自定义command命令

Laravel自定义command命令

用过Laravel的都知道,Laravel通过php artisan make:controller可以生成控制器,同样的也可以用命令生成中间介和模型,那怎么自定义生成文件呢?

1.创建command类

<?php
namespace App\Console\Commands;
use Illuminate\Console\GeneratorCommand;
class ServiceMakeCommand extends GeneratorCommand
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = &#39;make:service&#39;;
    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = &#39;Create a new service class&#39;;
    /**
     * The type of class being generated.
     *
     * @var string
     */
    protected $type = &#39;Services&#39;;
    /**
     * Get the stub file for the generator.
     *
     * @return string
     */
    protected function getStub()
    {
        return __DIR__.&#39;/stubs/service.stub&#39;;
    }
    /**
     * Get the default namespace for the class.
     *
     * @param  string  $rootNamespace
     * @return string
     */
    protected function getDefaultNamespace($rootNamespace)
    {
        return $rootNamespace."\Services";
    }
}
Copy after login

2.在Commands/stubs文件下创建自定义模板文件

<?php
namespace DummyNamespace;
class DummyClass 
{
    public function __construct()
    {
    }
}
Copy after login

创建了一个只有构造函数的类,具体模板可以自己定义

运行测试

php artisan make:service Web/TestService
Copy after login

这个时候Services文件下的Web目录下会生成TestService文件,Web目录不存在时会自动创建

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template