您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關如何在Laravel中使用Artisan命令生成自定義模板,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內容,希望大家根據這篇文章可以有所收獲。
備注:個人平時在寫Repository代碼時會這樣寫,如先寫上ShopRepositoryInterface并定義好接口方法如all()
、create()
、update()
、delete()
、findBy()
等等,然后再寫上接口對應的實現ShopRepository并注入對應的Model即Shop。別的PostRepository、TagRepository也會是這么寫(當然,對于很多重用的Repository方法可以集體拿到AbstractRepository抽象類里供子類繼承,實現代碼復用
)。那能不能直接命令行生成模板文件呢,就不用自己一個個的寫了,就像輸入php artisan make:controller PostController
給我一個Controller模板來。
關于使用Repository模式來封裝下Model邏輯,不讓Controller里塞滿了很多Model邏輯,這樣做是有很多好處的,最主要的就是好測試和代碼架構清晰,也符合SOLID原則。如果使用PHPUnit來做測試就知道了為啥說好測試了。SegmentFault上也有相關的文章描述。作者也打算最近新開一篇文章聊一聊這個,PHPUnit也打算過段時間聊一聊。
個人研究了下Artisan命令行,是可以的。經過開發后,結果是輸入自定義指令php artisan make:repository PostRepository --model=Post(這個option可要可不要)
,就會幫我生成一個PostRepositoryInterface和對應的接口實現PostRepository。
模板文件Stub
由于個人需要生成一個RepositoryInterface和對應接口實現Repository,那就需要兩個模板文件了。在resources/stubs新建兩個模板文件,以下是個人經常需要的兩個模板文件(你可以自定義):
/** * @param array $columns * @return \Illuminate\Database\Eloquent\Collection|static[] */ public function all($columns = array('*')) { return $this->$model_var_name->all($columns); } /** * @param int $perPage * @param array $columns * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator */ public function paginate($perPage = 15, $columns = array('*')) { return $this->$model_var_name->paginate($perPage, $columns); } /** * Create a new $model_var_name * @param array $data * @return \$model_namespace */ public function create(array $data) { return $this->$model_var_name->create($data); } /** * Update a $model_var_name * @param array $data * @param $id * @return \$model_namespace */ public function update($data = [], $id) { return $this->$model_var_name->whereId($id)->update($data); } /** * Store a $model_var_name * @param array $data * @return \$model_namespace */ public function store($data = []) { $this->$model_var_name->id = $data['id']; //... $this->$model_var_name->save(); } /** * Delete a $model_var_name * @param array $data * @param $id * @return \$model_namespace */ public function delete($data = [], $id) { $this->$model_var_name->whereId($id)->delete(); } /** * @param $id * @param array $columns * @return array|\Illuminate\Database\Eloquent\Collection|static[] */ public function find($id, $columns = array('*')) { $$model_name = $this->$model_var_name->whereId($id)->get($columns); return $$model_name; } /** * @param $field * @param $value * @param array $columns * @return \Illuminate\Database\Eloquent\Collection|static[] */ public function findBy($field, $value, $columns = array('*')) { $$model_name = $this->$model_var_name->where($field, '=', $value)->get($columns); return $$model_name; } }
模板文件里包括參數,這些參數將會根據命令行中輸入的參數和選項被相應替換:
復制代碼 代碼如下:
['$repository_namespace', '$model_namespace', '$repository_interface_namespace', '$repository_interface', '$class_name', '$model_name', '$model_var_name']
Artisan命令生成Repository模板文件
生成Artisan命令并注冊
Laravel提供了Artisan命令自定義,輸入指令:
php artisan make:console MakeRepositoryCommand
然后改下簽名和描述:
// app/Console/Commands/MakeRepositoryCommand /** * The name and signature of the console command. * * @var string */ protected $signature = 'make:repository {repository} {--model=}'; /** * The console command description. * * @var string */ protected $description = 'Make a repository and interface';
這里{repository}是必填參數并指明(選填參數加個?
,就和路由參數一樣),將會被$this->argument('repository')方法捕捉到,{--model=}是選項,可填可不填,將會被$this->option('model')方法捕捉到。填上這個命令的描述,最后在Console的Kernel里注冊下命令:
// app/Console/Kernel protected $commands = [ // Commands\Inspire::class, // Commands\RedisSubscribe::class, // Commands\RedisPublish::class, // Commands\MakeTestRepositoryCommand::class, Commands\MakeRepositoryCommand::class, ];
然后輸入php artisan命令后就能看到這個make:repository命令了。
自動化生成RepositoryInterface和Repository文件
在MakeRepositoryCommand.php命令執行文件里寫上模板自動生成邏輯,代碼也不長,有些邏輯也有注釋,可看:
use Config; use Illuminate\Console\Command; use Illuminate\Filesystem\Filesystem; use Illuminate\Support\Composer; class MakeRepositoryCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'make:repository {repository} {--model=}'; /** * The console command description. * * @var string */ protected $description = 'Make a repository and interface'; /** * @var */ protected $repository; /** * @var */ protected $model; /** * Create a new command instance. * * @param Filesystem $filesystem * @param Composer $composer */ public function __construct(Filesystem $filesystem, Composer $composer) { parent::__construct(); $this->files = $filesystem; $this->composer = $composer; } /** * Execute the console command. * * @return mixed */ public function handle() { //獲取repository和model兩個參數值 $argument = $this->argument('repository'); $option = $this->option('model'); //自動生成RepositoryInterface和Repository文件 $this->writeRepositoryAndInterface($argument, $option); //重新生成autoload.php文件 $this->composer->dumpAutoloads(); } private function writeRepositoryAndInterface($repository, $model) { if($this->createRepository($repository, $model)){ //若生成成功,則輸出信息 $this->info('Success to make a '.ucfirst($repository).' Repository and a '.ucfirst($repository).'Interface Interface'); } } private function createRepository($repository, $model) { // getter/setter 賦予成員變量值 $this->setRepository($repository); $this->setModel($model); // 創建文件存放路徑, RepositoryInterface放在app/Repositories,Repository個人一般放在app/Repositories/Eloquent里 $this->createDirectory(); // 生成兩個文件 return $this->createClass(); } private function createDirectory() { $directory = $this->getDirectory(); //檢查路徑是否存在,不存在創建一個,并賦予775權限 if(! $this->files->isDirectory($directory)){ return $this->files->makeDirectory($directory, 0755, true); } } private function getDirectory() { return Config::get('repository.directory_eloquent_path'); } private function createClass() { //渲染模板文件,替換模板文件中變量值 $templates = $this->templateStub(); $class = null; foreach ($templates as $key => $template) { //根據不同路徑,渲染對應的模板文件 $class = $this->files->put($this->getPath($key), $template); } return $class; } private function getPath($class) { // 兩個模板文件,對應的兩個路徑 $path = null; switch($class){ case 'Eloquent': $path = $this->getDirectory().DIRECTORY_SEPARATOR.$this->getRepositoryName().'.php'; break; case 'Interface': $path = $this->getInterfaceDirectory().DIRECTORY_SEPARATOR.$this->getInterfaceName().'.php'; break; } return $path; } private function getInterfaceDirectory() { return Config::get('repository.directory_path'); } private function getRepositoryName() { // 根據輸入的repository變量參數,是否需要加上'Repository' $repositoryName = $this->getRepository(); if((strlen($repositoryName) < strlen('Repository')) || strrpos($repositoryName, 'Repository', -11)){ $repositoryName .= 'Repository'; } return $repositoryName; } private function getInterfaceName() { return $this->getRepositoryName().'Interface'; } /** * @return mixed */ public function getRepository() { return $this->repository; } /** * @param mixed $repository */ public function setRepository($repository) { $this->repository = $repository; } /** * @return mixed */ public function getModel() { return $this->model; } /** * @param mixed $model */ public function setModel($model) { $this->model = $model; } private function templateStub() { // 獲取兩個模板文件 $stubs = $this->getStub(); // 獲取需要替換的模板文件中變量 $templateData = $this->getTemplateData(); $renderStubs = []; foreach ($stubs as $key => $stub) { // 進行模板渲染 $renderStubs[$key] = $this->getRenderStub($templateData, $stub); } return $renderStubs; } private function getStub() { $stubs = [ 'Eloquent' => $this->files->get(resource_path('stubs/Repository').DIRECTORY_SEPARATOR.'Eloquent'.DIRECTORY_SEPARATOR.'repository.stub'), 'Interface' => $this->files->get(resource_path('stubs/Repository').DIRECTORY_SEPARATOR.'repository_interface.stub'), ]; return $stubs; } private function getTemplateData() { $repositoryNamespace = Config::get('repository.repository_namespace'); $modelNamespace = 'App\\'.$this->getModelName(); $repositoryInterfaceNamespace = Config::get('repository.repository_interface_namespace'); $repositoryInterface = $this->getInterfaceName(); $className = $this->getRepositoryName(); $modelName = $this->getModelName(); $templateVar = [ 'repository_namespace' => $repositoryNamespace, 'model_namespace' => $modelNamespace, 'repository_interface_namespace' => $repositoryInterfaceNamespace, 'repository_interface' => $repositoryInterface, 'class_name' => $className, 'model_name' => $modelName, 'model_var_name' => strtolower($modelName), ]; return $templateVar; } private function getRenderStub($templateData, $stub) { foreach ($templateData as $search => $replace) { $stub = str_replace('$'.$search, $replace, $stub); } return $stub; } private function getModelName() { $modelName = $this->getModel(); if(isset($modelName) && !empty($modelName)){ $modelName = ucfirst($modelName); }else{ // 若option選項沒寫,則根據repository來生成Model Name $modelName = $this->getModelFromRepository(); } return $modelName; } private function getModelFromRepository() { $repository = strtolower($this->getRepository()); $repository = str_replace('repository', '', $repository); return ucfirst($repository); } }
這里把一些常量值放在config/repository.php配置文件里了:
<?php return [ 'directory_path' => 'App'.DIRECTORY_SEPARATOR.'Repositories', 'directory_eloquent_path' => 'App'.DIRECTORY_SEPARATOR.'Repositories'.DIRECTORY_SEPARATOR.'Eloquent', 'repository_namespace' => 'App\Repositories\Eloquent', 'repository_interface_namespace' => 'App\Repositories', ];
運行一下看可不可以吧,這里截個圖:
It is working!!!
是可以生成RepositoryInterface和對應的接口實現文件,這里一個是加了--model選項一個沒加的,沒加的話這里第一個指令就默認Model的名稱是Shop。
生成的文件內容不截圖了,看下新生成的ShopRepository.php文件,的確是我想要的模板文件:
<?php /** * Created by PhpStorm. * User: liuxiang */ namespace App\Repositories\Eloquent; use App\Shop; use App\Repositories\ShopRepositoryInterface; class ShopRepository implements ShopRepositoryInterface { /** * @var \App\Shop */ public $shop; public function __construct(Shop $shop) { $this->shop = $shop; } /** * @param array $columns * @return \Illuminate\Database\Eloquent\Collection|static[] */ public function all($columns = array('*')) { return $this->shop->all($columns); } /** * @param int $perPage * @param array $columns * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator */ public function paginate($perPage = 15, $columns = array('*')) { return $this->shop->paginate($perPage, $columns); } /** * Create a new shop * @param array $data * @return \App\Shop */ public function create(array $data) { return $this->shop->create($data); } /** * Update a shop * @param array $data * @param $id * @return \App\Shop */ public function update($data = [], $id) { return $this->shop->whereId($id)->update($data); } /** * Store a shop * @param array $data * @return \App\Shop */ public function store($data = []) { $this->shop->id = $data['id']; //... $this->shop->save(); } /** * Delete a shop * @param array $data * @param $id * @return \App\Shop */ public function delete($data = [], $id) { $this->shop->whereId($id)->delete(); } /** * @param $id * @param array $columns * @return array|\Illuminate\Database\Eloquent\Collection|static[] */ public function find($id, $columns = array('*')) { $Shop = $this->shop->whereId($id)->get($columns); return $Shop; } /** * @param $field * @param $value * @param array $columns * @return \Illuminate\Database\Eloquent\Collection|static[] */ public function findBy($field, $value, $columns = array('*')) { $Shop = $this->shop->where($field, '=', $value)->get($columns); return $Shop; } }
Laravel 是一套簡潔、優雅的PHP Web開發框架。它可以讓你從面條一樣雜亂的代碼中解脫出來;它可以幫你構建一個完美的網絡APP,而且每行代碼都可以簡潔、富于表達力。
看完上述內容,你們對如何在Laravel中使用Artisan命令生成自定義模板有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注億速云行業資訊頻道,感謝大家的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。