phucnguyenvn/laravel-eloquent-repository

Eloquent ORM的Repository模式

1.0.1 2019-01-21 12:01 UTC

This package is auto-updated.

Last update: 2024-09-22 00:42:04 UTC


README

用于辅助使用Eloquent ORM实现Repository模式的包。

安装

通过Composer安装

composer require phucnguyenvn/laravel-eloquent-repository

要配置包选项,请在config/app.php文件中声明Service Provider。

'providers' => [
    ...
    phucnguyenvn\EloquentRepository\Providers\RepositoryServiceProvider::class,
],

如果你使用的是Laravel 5.5或更高版本,Service Provider将自动被Package Discover识别。

用法

要开始使用,你需要创建你的仓库类,并扩展包中提供的EloquentRepository。你还需要设置将用于执行查询的模型

示例

namespace App\Repositories;

use App\Models\User;
use phucnguyenvn\EloquentRepository\Repositories\EloquentRepository;

class UserRepository extends EloquentRepository
{
    /**
     * Repository constructor.
     */
    public function __construct(User $user){
        parent::__construct($user);
    }
}

现在可以像使用Eloquent一样执行查询。

namespace App\Repositories;

use App\Models\User;
use phucnguyenvn\EloquentRepository\Repositories\EloquentRepository;

class UserRepository extends EloquentRepository
{
    /**
     * Repository constructor.
     */
    public function __construct(User $user){
        parent::__construct($user);
    }
    
    public function getAllUser(){
        return $this->all();
    }
    
    public function getByName($name) {
        return $this->where("name", $name)->get();
    }
    
    // You can create methods with partial queries
    public function filterByProfile($profile) {
        return $this->where("profile", $profile);
    }
    
    // Them you can use the partial queries into your repositories
    public function getAdmins() {
        return $this->filterByProfile("admin")->get();
    }
    public function getEditors() {
        return $this->filterByProfile("editor")->get();
    }
    
    // You can also use Eager Loading in queries
    public function getWithPosts() {
        return $this->with("posts")->get();
    }
}

要使用该类,只需将其注入到控制器中。

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Repositories\UserRepository;

class UserController extends Controller
{
    protected function index(UserRepository $repository) {
        return $repository->getAdmins();
    }
}

注入也可以在构造函数中完成,以便在所有方法中使用仓库。

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Repositories\UserRepository;
class UserController extends Controller
{
    private $userRepository;
	public function __construct()(UserRepository $userRepository) {
        $this->userRepository = $userRepository;
    }
    
    public function index() {
        return $this->userRepository->getAllUsers();
    }
    
}

Eloquent/QueryBuilder方法被封装为受保护的,仅对仓库类可用。在仓库中声明你自己的公开数据访问方法,以便通过控制器访问它们。