仓库模式DEMO
1. 定义基类接口
<?php
namespace App\Repositories\Contracts;
interface BaseInterface{
public function allUsers();
}
2. 实现接口扩展抽象类
<?php
namespace App\Repositories\Eloquent;
use App\Repositories\Contracts\BaseInterface;
// 模式基类
use Illuminate\Database\Eloquent\Model;
// 容器
use Illuminate\Container\Container as App;
abstract class Repository implements BaseInterface
{
/*App容器*/
protected $app;
/*操作model*/
protected $model;
public function __construct(App $app)
{
$this->app = $app;
$this->makeModel();
}
// 创建指定的 model
public function makeModel()
{
$model = $this->app->make($this->model());
/*是否是Model实例*/
if (!$model instanceof Model){
throw new RepositoryException("Class {$this->model()} must be an instance of Illuminate\\Database\\Eloquent\\Model");
}
$this->model = $model;
}
// 指定子类的model
abstract function model();
// 实现基类接口的方法
// 获取所有用户信息
public function allUsers()
{
return $this->model->all();
}
}
3. 接口抽象类的具体实现类
<?php
namespace App\Repositories\Eloquent;
use App\Repositories\Eloquent\Repository;
use App\Models\User;
class UserRepository extends Repository
{
// 实现抽象类的方法 返回一个UserModel对象实例
public function model()
{
return User::class;
}
// 以下可以重新基类方法
}
4. 控制器中调用
use App\Repositories\Eloquent\UserRepository as UserRepo;
//私有成员方法
protected $userRepo;
//构造方法中注入实现类
public function __construct(UserRepo $userRepo)
{
$this->userRepo = $userRepo;
}
//调用接口实现类的方法
$this->userRepo->allUsers()
网友评论