ravivatechnical/laravel-repository-generator

生成 Laravel 仓库 | Laravel 依赖注入

dev-master 2023-03-25 13:43 UTC

This package is auto-updated.

Last update: 2024-09-25 16:50:07 UTC


README


Logo

Laravel Repository Generator

快速为您的项目生成仓库!



目录

  1. 特性
  2. 入门
  3. 使用方法
  4. 手动绑定
  5. 更多生成器包
  6. 贡献
  7. 许可

特性

使用此包,您可以使用 artisan make:repository 命令生成仓库。生成器将生成仓库、仓库接口,并将其自动(可更改为手动绑定)绑定到服务容器,以便您可以将接口注入到控制器中。

安装

使用 composer 安装 Laravel 仓库生成器。

composer require raviyatechnical/laravel-repository-generator:dev-master --dev

发布配置(可选)

php artisan vendor:publish --provider="RaviyaTechnical\RepositoryGenerator\RepositoryGeneratorServiceProvider" --tag="config"

使用方法

使用方法,请按照以下步骤操作。生成仓库,然后将其注入到控制器或服务中。

生成仓库

运行以下命令。

php artisan make:repository UserRepository

此示例将生成以下文件

app\Repositories\Eloquent\UserRepository
app\Repositories\UserRepositoryInterface

依赖注入

接下来,我们需要将接口注入到我们的控制器或服务的构造函数中。对于此示例,我们将使用 UserController。

<?php

namespace App\Http\Controllers;

use App\Repositories\UserRepositoryInterface;

class UserController extends Controller
{
    private $user;

    public function __construct(UserRepositoryInterface $userRepository)
    {
        $this->user = $userRepository;
    }
    
    // your controller functions
}

默认情况下,您将能够使用 Eloquent 方法,如 all()find()。您可以在仓库中扩展这些。现在您可以在您的函数中使用您的仓库,如下所示。

public function index()
{
    return $this->user->all();
}

手动绑定

默认情况下,该包将自动将仓库接口与仓库绑定,以便您可以将接口注入到控制器中。如果您想手动绑定,可以将 config\repository-generator.php 中的 auto_bind_interfaces 选项设置为 false。如果配置文件不存在,请确保首先按照安装章节中的说明发布它。

您可以将绑定添加到您的 AppServiceProvider 或创建一个新的提供者,使用 php artisan make:provider RepositoryServiceProvider(不要忘记将其添加到 config\app.php),然后在 register() 方法中添加绑定,如下面的示例所示。

<?php 

namespace App\Providers; 

use App\Repositories\Eloquent\UserRepository;
use App\Repositories\UserRepositoryInterface;
use Illuminate\Support\ServiceProvider; 

/** 
* Class RepositoryServiceProvider 
* @package App\Providers 
*/ 
class RepositoryServiceProvider extends ServiceProvider 
{ 
   /** 
    * Register services. 
    * 
    * @return void  
    */ 
   public function register() 
   { 
       $this->app->bind(UserRepositoryInterface::class, UserRepository::class);
   }
}

贡献

贡献使开源社区成为一个如此美妙的学习、灵感和创造的地方。您做出的任何贡献都 非常受欢迎

如果您有任何改进的建议,请分支仓库并创建一个拉取请求。您也可以简单地打开一个带有“增强”标签的问题。不要忘记为项目加星!再次感谢!

  1. 分支项目
  2. 创建您的功能分支(git checkout -b feature/AmazingFeature
  3. 提交您的更改(git commit -m 'Add some AmazingFeature'
  4. 将更改推送到分支(git push origin feature/AmazingFeature
  5. 打开一个拉取请求

第一个灵感包

https://github.com/timwassenburg/laravel-repository-generator

许可

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