当前位置:网站首页>laravel 创建 service层

laravel 创建 service层

2022-06-24 19:41:00 王道长的编程之路

一、生成及编辑 service文件

php artisan make:command AddService

执行该命令,将会在app\Console目录下生成Commands目录,同时在 app\Console\Commands 目录下生成 AddService.php 文件。

将AddService.php文件内容清空,并用如下替换

<?php

namespace App\Console\Commands;

use Illuminate\Console\GeneratorCommand;

class AddService extends GeneratorCommand
{
    
    /** * 控制台命令名称 * * @var string */
    protected $name = 'make:service';
    /** * 控制台命令描述 * * @var string */
    protected $description = 'Create a new service class';
    /** * 生成类的类型 * * @var string */
    protected $type = 'Services';
    /** * 获取生成器的存根文件 * * @return string */
    protected function getStub()
    {
    
        return __DIR__.'/stubs/service.stub';
    }

    /** * 获取类的默认命名空间 * * @param string $rootNamespace * @return string */

    protected function getDefaultNamespace($rootNamespace)
    {
    
        return $rootNamespace.'\Services';
    }
}

二、创建存根目录及文件

在app\Console\Commands目录下创建Stubs目录,可以直接右键新建文件夹,或使用命令行 mkdir app\Console\Commands\Stubs 在该目录下添加名为 services.stub 的文件,完整路径为app/Console/Commands/Stubs/service.stub

编辑services.stub并添加内容,将如下内容添加到services.stub文件中并保存。

<?php

namespace DummyNamespace;

class DummyClass
{

}

三、注册命令

将以下内容添加到app/Console/Kernel.php文件的 protected $commands = [] 属性数组中,使命令生效。

\App\Console\Commands\AddServices::class

protected $commands = [
  Commands\AddService::class
];

四、测试命令

php artisan make:service MusicService
原网站

版权声明
本文为[王道长的编程之路]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_29677867/article/details/107744890