arungpisyadi/laravel-repository-and-service-pattern-pack

简单的Laravel仓库和服务模式,效果显著!

v0.0.3 2023-04-29 12:32 UTC

This package is auto-updated.

Last update: 2024-09-29 15:28:13 UTC


README

使用简单的仓库,您可以获得仓库模式的强大功能,而不必编写太多代码。该包自动将接口绑定到实现,您只需更改配置以指定当前使用的实现即可!

需求

  • Laravel 8
  • PHP 7.4||8.*

安装

您可以通过composer安装此包

$ composer require yaza/laravel-repository-service

发布配置文件(重要)

php artisan vendor:publish --provider="LaravelEasyRepository\LaravelEasyRepositoryServiceProvider" --tag="easy-repository-config"

配置文件中的配置是标准的,可以根据进一步的需求进行扩展。除非您非常清楚自己在做什么,否则无需更改任何内容。这是已发布的配置文件的内容

return [
    /**
     * The directory for all the repositories
     */
    "repository_directory" => "app/Repositories",

    /**
     * Default repository namespace
     */
    "repository_namespace" => "App\Repositories",

    /**
     * The directory for all the services
     */
    "service_directory" => "app/Services",

    /**
     * Default service namespace
     */
    "service_namespace" => "App\Services",

    /**
     * Default repository implementation
     */
    "default_repository_implementation" => "Eloquent",

    /**
     * Current repository implementation
     */
    "current_repository_implementation" => "Eloquent",
];

快速使用

此包覆盖了默认的Laravel php artisan make:model User 命令,并添加了一些标志,可以帮助您快速设置仓库和服务。

// will genearate controller, factory, service, seeder, repository, resource and migration
php artisan make:model User --all

// use the service and repository flag to generate the class
php artisan make:model User --service --repository

// use the short form to generate model with service and repository
php artisan make:model User -sr -rt

您也可以仅创建仓库、仅创建服务或同时创建两者

php artisan make:repository User
// or
php artisan make:repository UserRepository

// or create together with a service
php artisan make:repository User --service
// or
php artisan make:repository UserRepository --service

// or create a service separately
php artisan make:service User
// or
php artisan make:service UserService

php artisan make:repository User 将生成两个文件。一个是接口文件,另一个是仓库类文件。接口会根据当前使用的实现自动绑定到相应的类。如果没有提供接口的实现,您可以手动提供或尝试使用服务时将引发错误。

Eloquent是默认实现。未来将添加其他实现。这是因为该包主要是为了简化Laravel中仓库模式的使用。创建的类包括

// app/Repositories/Interfaces/UserRepository.php

<?php

namespace App\Repositories\Interfaces;

use LaravelEasyRepository\Repository;

class UserRepositoryInterface extends Repository{

    // Write something awesome :)
}

// app/Repositories/Eloquent/UserRepository.php

<?php

namespace App\Repositories\Eloquent;

use LaravelEasyRepository\Repository;
use LaravelEasyRepository\Implementations\Eloquent;
use App\Repositories\Interfaces\UserRepositoryInterface;

class UserRepository extends Eloquent implements UserRepositoryInterface{

    /**
    * Model class to be used in this repository for the common methods inside Eloquent
    * Don't remove or change variable $model or $this->model
    * @property Model|mixed $model;
    */
    protected $model;

    public function __construct(Model $model)
    {
        $this->model = $model;
    }
}

如果您包含服务标志或在运行命令时创建了一个服务,则生成的服务文件将仅调用接口并自动绑定到仓库。

// app/Services/UserService

<?php

namespace App\Services;

use {repositoryInterfaceNamespace}\{repositoryInterface};
class UserService {

   /**
   * don't change $this->mainRepository variable name
   * because used in service class
   */
   protected $mainRepository;

  public function __construct({repositoryInterface} $mainRepository)
  {
    $this->mainRepository = $mainRepository;
  }

   // Define your custom methods :)
}

在您的控制器中,您可以使用如下方式

<?php

namespace App\Http\Controllers;

use App\Services\UserService;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function __construct(UserService $mainService)
    {
        $this->mainService = $mainService;
    }
    
    public function all () {
      return $this->mainService->all();
    }

}

仓库和服务还内置了5个常见的CRUD方法

interface Repository
{
    /**
     * Fin an item by id
     * @param int $id
     * @return Model|null
     */
    public function find(int $id);

    /**
     * Find or fail an item by id
     * @param int $id
     * @return Model|null
     */
    public function findOrFail(int $id);

    /**
     * Return all items
     * @return Collection|null
     */
    public function all();

    /**
     * Return query builder instance to perform more manouvers
     * @return Builder|null
     */
    public function query();

    /**
     * Create an item
     * @param array|mixed $data
     * @return Model|null
     */
    public function create($data);

    /**
     * Update a model
     * @param int|mixed $id
     * @param array|mixed $data
     * @return bool|mixed
     */
    public function update($id, array $data);

    /**
     * Delete a model
     * @param int|Model $id
     */
    public function delete($id);

    /**
     * multiple delete
     * @param array $id
     * @return mixed
     */
    public function destroy(array $id);

}

用于构建具有响应、结果服务的REST API的附加组件,如

  • 在服务中
<?php

namespace App\Services;

use LaravelEasyRepository\Traits\ResultService;
use {repositoryInterfaceNamespace}\{repositoryInterface};

class UserService {
 use ResultService;

  /**
    * don't change $this->mainRepository variable name
    * because used in service class
    */
    protected $mainRepository;

   public function __construct({repositoryInterface} $mainRepository)
   {
     $this->mainRepository = $mainRepository;
   }

    // Define your custom methods :)
    
    public function all () {
        try {
            $result = $this->mainRepository->all();
            return $this->setStatus(true)
                        ->setResult($result)
                        ->setCode(200)
                        ->setMessage('your message');
        } catch (\Exception $e) {
            return $this->exceptionResponse($e);
        }            
    }    
}
  • 在控制器中
<?php

namespace App\Http\Controllers;

use App\Services\UserService;
use Illuminate\Http\Request;
use LaravelEasyRepository\Traits\Response;

class UserController extends Controller
{
   use Response;
    public function __construct(UserService $mainService)
    {
        $this->mainService = $mainService;
    }
    
    public function all () {
      $result = $this->mainService->all();
      return $this->responseJson(
        $result->getStatus(),
        $result->getMessage(),
        $result->getResult(),
        $result->getCode()
      );
    }

}
  • 输出或响应如
{
    "success": true,
    "code": 200,
    "message": 'Your message',
    "data": [
        {
            "id": 1,
            "name": "tes",
            "email": "sales@scootcruise.com",
            "email_verified_at": null,
            "created_at": null,
            "updated_at": null
        }
    ]
}

变更日志

有关最近更改的更多信息,请参阅CHANGELOG

许可证

MIT许可证(MIT)。有关更多信息,请参阅许可证文件