下面由laravel教程欄目帶大家介紹如何使用 make:service 命令來快速生成 services,希望對大家有所幫助!
前言
Artisan 是 laravel 附帶的命令行接口。Artisan 以 artisan 腳本的形式存在于應(yīng)用的根目錄,并提供了許多有用的命令,這些命令可以在構(gòu)建應(yīng)用時為你提供幫助。
除 Artisan 提供的命令外,你也可以編寫自己的自定義命令。 命令在多數(shù)情況下位于 app/console/Commands 目錄中; 不過,只要你的命令可以由 composer 加載,你就可以自由選擇自己的存儲位置。
前期工作
在開始之前,我們要準(zhǔn)備相應(yīng)的目錄和文件。
我們可以使用以下命令快速生成 ServiceMakeCommand.php 文件:
php artisan make:command ServiceMakeCommand
執(zhí)行完后會在你的 Console 文件夾下生成 Commands 文件夾和 Commands/ServiceMakeCommand.php 文件。
我們還需要在 Commands 文件夾下添加一些文件夾和文件:
結(jié)構(gòu)如下:
-?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 }} { // }
我們的前期準(zhǔn)備就此結(jié)束,是不是很簡單?哈哈。
快速開始
接下來我們就直接一把梭哈了,注意改動的代碼噢。
我們主要是對著 ServiceMakeCommand.php 文件一把梭哈,所以:
app/Console/Commands/ServiceMakeCommand.php
<?php namespace AppConsoleCommands; use IlluminateConsoleGeneratorCommand; 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'; } }
最后,我們執(zhí)行以下命令快速生成 UserService.php 文件:
php artisan make:service UserService
結(jié)構(gòu)如下:
-?app ????-?Console ????????-?Commands ????????-?stubs ????????-?service.plain.stub ????????-?ServiceMakeCommand.php ????????-?Kernel.php +???-?Services +???????-?UserService.php -?. -?. -?.
讓我們查看 UserService.php 和我們想象中的代碼是否一致:
app/Services/UserService.php
<?php namespace AppServices; class UserService{ // }
恭喜,我們已經(jīng)做到我們想要的結(jié)果了。
總結(jié)
雖然我們做得比較簡陋,但我們只需稍加改進(jìn),就可以讓它變得更完善。