laravel 仓库模式
仓库模式的用途和作用
Repository层事实上是model层的代理。
假设有一个model实现了定义的接口并使用bind方法绑定这个模型。这有个需求说这个model不需要从数据库中提取,而是通过其他模式提取。这时候就可以重新建立一个模型重新编写接口里面定义的相关方法。然后在bind的里面把旧的模型改成新的模型。这样子的话就不用去修改其他的PHP文件里面的代码了。
创建仓库目录
app/Repository # 仓库目录
app/Repository/表名或者其他/Interfaces # 仓库接口定义
app/Repository/表名或者其他/Repositories # 仓库接口实现
创建接口和实现接口
<?php
<?php
namespace App\Repository\Order\Interfaces;
Interface OrderInterface{
// 获取用户的订单列表
public function getUserList(int $userId);
}
<?php
namespace App\Repository\Order\Repositories;
use Illuminate\Database\Eloquent\Model;
use App\Repository\Order\Interfaces\OrderInterface;
class OrderRepositories extends Model Implements OrderInterface{
protected $table = 'orders';
public function getUserList(int $userId){
return $this->where('user_test_id', $userId)->get();
}
}
创建服务主要是为了绑定接口
php artisan make:provider RepositoryServiceProvider
// 将RepositoryServiceProvider服务配置到应用中
// config\app.php
'providers' => [
App\Providers\RepositoryServiceProvider::class
]
在RepositoryServiceProvider中绑定接口
public function register(){
$this>app>bind(
'App\Repository\Order\Interfaces\OrderInterface',
'App\Repository\Order\Repositories\OrderRepositories'
);
}
测试路由
use App\Repository\Order\Interfaces\OrderInterface;
Route::get('/get-user-order', function(OrderInterface $order){
return $order->getUserList(1);
});
[{"id":1,"user_test_id":1,"order_number":"yaoxs\u7684\u8ba2\u5355\u7f16\u53f71","created_at":null,"updated_at":null},{"id":2,"user_test_id":1,"order_number":"yaoxs\u7684\u8ba2\u5355\u7f16\u53f72","created_at":null,"updated_at":null},{"id":3,"user_test_id":1,"order_number":"yaoxs\u7684\u8ba2\u5355\u7f16\u53f73","created_at":null,"updated_at":null}]
本作品采用《CC 协议》,转载必须注明作者和本文链接
1:解偶业务代码与模型相关代码,参考开闭原则
2:统一管理模型,例如后期升级,需要将 OrderRepository 改为 OrderV2Repository,则直接在 RepositoryServiceProvider 中改一行代码即可
这也属于锦上添花吧,一般的应用里不建议用,提高系统复杂度的同时,并没有解决什么实质性的大问题。
@LiamHao 最后一句不同意, 真有需要的时候能很好的解决问题