pros/base

0.1.1 2021-12-03 07:55 UTC

This package is auto-updated.

Last update: 2024-09-29 06:03:15 UTC


README

此库用于方便地为Laravel项目注册代码库的方法

目标

我们旨在通过MVC加上Repository和服务层来降低真实项目的复杂性。这个结构在我们的真实项目中进行了测试,显著降低了复杂性,也更容易调试和阅读。

该结构专注于为Laravel 8.0及以上版本创建Repository和服务。

因此

  • Repository旨在与Model交互,一个Repository只有一个Model实例。创建新的Repository时,它会自动检测Model。例如:UserRepository将自动将User作为Model。

  • Service旨在解决逻辑问题。因此,您的控制器只需将参数传递给Service即可。

  • ApiLogicException有助于在API遇到问题时抛出异常。

  • ResponseTemplateTrait是json响应的标准,您无需再重复代码,只需调用即可。

安装

composer require pros/base

命令

该库支持3个命令

  • php artisan make:remose <name>根据name生成Repository、Model和服务。

    例如:php artisan make:remose User将生成

    • Models/User.php
    • Repositories/UserRepository.php
    • Services/UserService.php
  • php artisan make:repo <name>生成Repository

  • php artisan make:service <name>生成Service

示例

  • Controller.php
use Illuminate\Routing\Controller as BaseController;

class Controller extends BaseController
{
    // this line is to register json response convenient methods
    use ResponseTemplateTrait;

    pubic function __construct(
        protected Service $service
    ){}

    public function index(Request $request) 
    {
        $param1 = $request->get('param1');
        $data = $this->service->methodName($param1)

        // this method comes from ResponseTemplateTrait
        // it also contains jsonError and jsonSuccessNoContent methods
        return $this->jsonSuccess($data);
    }
}
  • Service.php
class Service 
{
    pubic function __construct(
        protected Repository $repository
    ){}

    /**
    * for testing only, it can be whatever 
    */
    public function methodName($param1) : boolean
    {
        // This is for demo only,
        // you can throw new exception to avoid check error
        // here and there.
        // It helps code more readable.
        // But it doesn't limit you in returning error, both are fine
        if('a' === 'b') {
            throw new ApiLogicException('What the hell?');
        }

        // handle your code logic here and then interact with DB 
        // via repository
        return $this->repository->paramExists($param1);
    }
}
  • Repository.php
class Repostory extends BaseRepository 
{
    public funtion paramExists($param) : boolean
    {
        // $this can represents for Model, Eloquent, QueryBuilder
        // so feel free to use this as you desired
        // you also can use $this->model for same purpose. 
        return $this->where('a' = $param)->exists();
    }
}

许可证

终身MIT,如果你有来世,那么你不得不付钱 ;)

联系方式