Laravel自定义command命令创建service

发布时间:2020-11-17 20:34:48 阅读:1396次

我们知道laravel框架有脚手架,可以帮助我们快速的创建controllermodel

我们该如何自定义命令,来快速的创建自己的service

app/Console/Commands

makeServiceCommand.php

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

app/Console/Commands/stubs

<?php

namespace DummyNamespace;

class DummyClass
{
    public function __construct()
    {

    }
    public function index(){
        echo __method__;
    }
}

执行php artisan make:service TestService即可

我们可以在app/Services中看到TestService.php文件

<?php

namespace App\Services;

class TestService
{
    public function __construct()
    {
        
    }

    public function index(){
        echo __method__;
    }
}

如有问题,可以QQ搜索群1028468525加入群聊,欢迎一起研究技术

支付宝 微信

有疑问联系站长,请联系QQ:QQ咨询

转载请注明:Laravel自定义command命令创建service 出自老鄢博客 | 欢迎分享