Repository模式是企业架构模式,目前按我理解就是解耦,升级,更换orm不会影响到业务逻辑。

下面介绍下Repository模式在Laravel框架项目开发中的使用。

第一步,在laravelapp目录下新建文件夹Repositories

第二步,建立相对应的接口类,我以文章模型Article为例,在Repositories目录下新建文件ArticleRepositoryInterface.php;

代码如下:

 <?php 
namespace App\Repositories;
interface ArticleRepositoryInterface {

		public function findById($id);
}

第三步:完成接口的实现,在Repositories目录下新建目录Eloquent, Eloquent目录下新建文件,AbstractRepository.phpArticleRepository.php

AbstractRepository.php为所有Repository实现的基类,代码如下:

<?php 
namespace App\Repositories\Eloquent;

use Illuminate\Database\Eloquent\Model;

abstract class AbstractRepository {

		protected $model;
		public function __construct(Model $model)
		{
				$this->model = $model;
		}

}

ArticleRepository.php,代码如下:

<?php 
namespace App\Repositories\Eloquent;
use App\Article;
use App\Repositories\ArticleRepositoryInterface;

class ArticleRepository extends AbstractRepository implements ArticleRepositoryInterface 
{
		public function __construct(Article $article)
		{
				$this->model = $article;
		}

		public function findById($id)
		{
				return $this->model->find($id);
		}
}

第四步,创建Repository的服务提供者

在控制台下,进入项目目录,执行命令

php artisan make:provider RepositoryServiceProvider

绑定接口的实现,修改RepositoryServiceProvider.php文件,可参考官网手册服务容器章节绑定接口到实现

代码如下:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class RepositoryServiceProvider extends ServiceProvider
{


		/**
		 * Register the application services.
		 *
		 * @return void
		 */
		public function register()
		{
				$this->app->bind(
						'App\Repositories\ArticleRepositoryInterface',
						'App\Repositories\Eloquent\ArticleRepository'
				);
		}
}

第五步,注册服务提供者

修改config目录下的app.php文件,修改 providers 数组,在数组中添加代码:

App\Providers\RepositoryServiceProvider::class,

第六步,调用,在你需要使用模型的控制器中引入命名空间,比如我在ArticleController中使用

//其它代码

use App\Repositories\ArticleRepositoryInterface;

class ArticleController extends Controller
{
		protected $article;

		public function __construct(ArticleRepositoryInterface $article)
		{
				$this->article = $article;
		}
		
		//其它代码
}

这样就完成了LaravelRepository模式的实现了

参考文档:

服务容器

服务提供者

安正超大神的开源项目