laravel如何快速生成 Services

发布时间:2021-12-06 15:37:16 作者:小新
来源:亿速云 阅读:190

小编给大家分享一下laravel如何快速生成 Services,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

前言

Artisan 是 Laravel 附带的命令行接口。Artisan 以 artisan 脚本的形式存在于应用的根目录,并提供了许多有用的命令,这些命令可以在构建应用时为你提供帮助。

除 Artisan 提供的命令外,你也可以编写自己的自定义命令。 命令在多数情况下位于 app/Console/Commands 目录中; 不过,只要你的命令可以由 Composer 加载,你就可以自由选择自己的存储位置。

前期工作

在开始之前,我们要准备相应的目录和文件。

我们可以使用以下命令快速生成 ServiceMakeCommand.php 文件:

php artisan make:command ServiceMakeCommand

执行完后会在你的 Console 文件夹下生成 Commands 文件夹和 Commands/ServiceMakeCommand.php 文件。

我们还需要在 Commands 文件夹下添加一些文件夹和文件:

结构如下:

- app
    - Console
+   - Commands
+       - stubs
+           - service.plain.stub
+       - ServiceMakeCommand.php
        - Kernel.php
- .
- .
- .

service.plain.stub 代码:

app/Console/Commands/stubs/service.plain.stub

<?php

namespace {{ namespace }};

class {{ class }}
{
    //
}

我们的前期准备就此结束,是不是很简单?哈哈。

快速开始

接下来我们就直接一把梭哈了,注意改动的代码噢。

我们主要是对着 ServiceMakeCommand.php 文件一把梭哈,所以:

app/Console/Commands/ServiceMakeCommand.php

<?php

namespace App\Console\Commands;

use Illuminate\Console\GeneratorCommand;

class ServiceMakeCommand extends GeneratorCommand
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'make:service {name}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create a new service class';

    /**
     * The type of class being generated.
     *
     * @var string
     */
    protected $type = 'Service';

    /**
     * Get the stub file for the generator.
     *
     * @return string
     */
    protected function getStub()
    {
        return __DIR__ . '/stubs/service.plain.stub';
    }

    /**
     * Get the default namespace for the class.
     *
     * @param  string  $rootNamespace
     * @return string
     */
    protected function getDefaultNamespace ( $rootnamespace )
    {
        return $rootnamespace . '\Services';
    }
}

最后,我们执行以下命令快速生成 UserService.php 文件:

php artisan make:service UserService

结构如下:

- app
    - Console
        - Commands
        - stubs
        - service.plain.stub
        - ServiceMakeCommand.php
        - Kernel.php
+   - Services
+       - UserService.php
- .
- .
- .

让我们查看 UserService.php 和我们想象中的代码是否一致:

app/Services/UserService.php

<?php

namespace App\Services;
class UserService{
    //
    }

恭喜,我们已经做到我们想要的结果了。

以上是“laravel如何快速生成 Services”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

推荐阅读:
  1. Android | 教你如何快速集成机器学习能力
  2. Laravel根据用户id生成四位数唯一邀请码的方法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

laravel services

上一篇:ASP.NET MVC2项目如何升级到MVC 3 RC

下一篇:怎么解决mysql无法启动1067错误问题

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》