Laravel Artisan 自定义模板生成背景
本文重点讲解如何借助 Laravel 的 Artisan 命令构建自定义模板。正如执行 php artisan make:controller ShopController 会自动创建 ShopController.php 文件一样,利用命令生成模板能显著提升开发速度。文中将附带相关截图与代码片段,以便读者更直观地理解操作流程。
在编写 Repository 代码时,通常的做法是先定义如 all()、create()、update()、delete()、findBy() 等方法接口的 ShopRepositoryInterface,随后创建实现该接口的 ShopRepository 类并注入对应的 Shop Model。其他如 PostRepository、TagRepository 也遵循此模式(见 当然,对于很多重用的Repository方法可以集体拿到AbstractRepository抽象类里供子类继承,实现代码复用)。既然有固定模式,是否可以通过命令行直接生成模板,例如输入 php artisan make:controller PostController 来获取 Controller 模板那样,一键生成 Repository 相关文件呢?
采用 Repository 模式封装 Model 逻辑,避免 Controller 中堆积过多业务代码,具有诸多优势:不仅便于测试,还能保持代码架构清晰,符合 SOLID 原则。使用 PHPUnit 进行测试时会深刻体会到其便利性。SegmentFault 上也有相关文章探讨此话题,作者计划近期另开文章深入讨论 Repository 模式及 PHPUnit 的使用。
经过对 Artisan 命令行的研究,这一想法是可行的。开发完成后,只需输入自定义指令 php artisan make:repository PostRepository --model=Post(这个option可要可不要),系统即可自动帮我生成 PostRepositoryInterface 及其对应的实现类 PostRepository。
定义 Repository 模板 Stub 文件
模板文件 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 自定义命令
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 命令。

实现 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
/**
* Created by PhpStorm.
* User: liuxiang
* Date: 16/6/22
* Time: 17:06
*/
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 的 Artisan 命令自动生成个人所需的模板,以减少日常开发中的重复劳动。Laravel 内置了许多模板生成命令,熟练使用可节省大量时间。这是作者在开发中遇到的实际需求,通过利用 Laravel Artisan 命令得以解决,可见 Laravel 的灵活性。有兴趣的读者可以下载代码尝试,并根据自身需求修改模板。近期作者打算专门写一篇关于 Repository 模式封装 Model 逻辑的方法与好处的文章,届时再见。希望对大家的学习有所帮助,也希望大家多多支持本站