akunbeben / laravository

此包已被废弃且不再维护。没有建议的替代包。

简化Laravel的仓库模式。

1.0.3 2021-04-30 16:16 UTC

This package is auto-updated.

Last update: 2023-08-10 07:59:37 UTC


README

laravel-logolockup-cmyk-red.svg

Laravository - Laravel的仓库模式

在Laravel中实现简化的仓库模式。

要求

  • Laravel 8.x

安装

执行以下命令以获取包的最新版本

composer require akunbeben/laravository

执行以下命令以创建RepositoryServiceProvider

php artisan repository:provider

转到config/app.php并将以下内容添加到你的服务提供者配置中App\Providers\RepositoryServiceProvider::class

RepositoryServiceProvider将作为依赖注入工作。

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

方法

Akunbeben\Laravository\Repositories\Interfaces

  • getAll();
  • getById($id, $relations = null)
  • create($attributes)
  • update($id, $attributes)
  • delete($id)

使用方法

创建新的仓库

要创建仓库,只需运行以下命令

php artisan make:repository User

你也可以添加-m--model选项来生成模型

php artisan make:repository User -m

这样你就不需要手动创建模型。

你可以在App\Repositories\文件夹下找到生成的文件

  • 仓库:App\Repositories\Eloquent\
  • 接口:App\Repositories\Interfaces\

UserRepository.php

namespace App\Repositories\Eloquent;

use Akunbeben\Laravository\Repositories\Eloquent\BaseRepository;

use App\Repositories\Interfaces\UserRepositoryInterface;
use App\Models\User;

class UserRepository extends BaseRepository implements UserRepositoryInterface
{
  protected $model;

  /**
   * Your model to use the Eloquent
   * 
   * @param User $model
   */
  public function __construct(User $model)
  {
    $this->model = $model;
  }
}

UserRepositoryInterface.php

namespace App\Repositories\Interfaces;

interface UserRepositoryInterface
{
    
}

在创建仓库之后,你需要在RepositoryServiceProvider.php中注册你的类和接口

...
class RepositoryServiceProvider extends ServiceProvider
{
  ...
  public function register()
  {
    ...
    $this->app->bind(UserRepositoryInterface::class, UserRepository::class);
  }
}

现在你可以在控制器中实现它。如下例所示

namespace App\Http\Controllers;

use App\Repositories\Interfaces\UserRepositoryInterface;

class UserController extends Controller
{
  protected $userRepository;

  public function __construct(UserRepositoryInterface $userRepository) {
    $this->userRepository = $userRepository;
  }
}

因此,你的控制器将更加简洁和简短。

class UserController extends Controller
{
  protected $userRepository;

  public function __construct(UserRepositoryInterface $userRepository) {
    $this->userRepository = $userRepository;
  }

  ...

  public function store(SomeFormRequest $request)
  {
    return $this->userRepository->create($request->validated());
  }
}