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 协议》,转载必须注明作者和本文链接
推荐文章: