temify/repository-pattern-maker

使用单条命令创建仓库、接口和外观

dev-main 2021-06-08 10:13 UTC

This package is auto-updated.

Last update: 2024-09-17 19:27:18 UTC


README

这是一个简单的Laravel 5和Laravel 6库,允许您通过单条命令实现Repository模式

安装

composer require temify/laravel-repository-pattern

功能

将生成

  • 服务类
  • 接口实现
  • 合同服务提供者

启用包(可选)

此包实现了Laravel自动发现功能。安装后,包提供者和外观会自动添加。

配置

发布配置文件

此步骤是必需的

php artisan vendor:publish --provider="Temify\RepositoryPattern\RepositoryPatterServiceProvider"

使用方法

发布配置文件后,只需运行以下命令

php artisan make:repo YOURMODEL

完成了,现在您已成功实现了Repository模式

示例

php artisan make:repo Product

ProductRepositoryInterface.php

<?php

namespace App\Repositories;

interface ProductRepositoryInterface
{
    /**
     * Get's a record by it's ID
     *
     * @param int
     */
    public function get($id);

    /**
     * Get's all records.
     *
     * @return mixed
     */
    public function all();

    /**
     * Deletes a record.
     *
     * @param int
     */
    public function delete($id);


}
#### ProductRepository.php

<?php

namespace App\Repositories;

use App\Models\Product;


class ProductRepository implements ProductRepositoryInterface
{
    /**
     * Get's a record by it's ID
     *
     * @param int
     * @return collection
     */
    public function get($id)
    {
        return Product::find($id);
    }

    /**
     * Get's all records.
     *
     * @return mixed
     */
    public function all()
    {
        return Product::all();
    }

    /**
     * Deletes a record.
     *
     * @param int
     */
    public function delete($id)
    {
        Product::destroy($id);
    }

    /**
     * Updates a post.
     *
     * @param int
     * @param array
     */
    public function update($id, array $data)
    {
        Product::find($id)->update($data);
    }
}

##### Now go to

```Repositories/RepositoryBackendServiceProvider.php```
and register the interface and class you have'just created

```php
<?php

namespace App\Repositories;

use Illuminate\Support\ServiceProvider;

class RepositoryBackendServiceProvider extends ServiceProvider
{

    public function register()
    {
        $this->app->bind(
            /*
            * Register your Repository classes and interface here
            **/

            'App\Repositories\ProductRepositoryInterface',
            'App\Repositories\ProductRepository'
        );
    }
}
现在在您的app/Http/Controllers/ProductController
<?php

namespace App\Http\Controllers;

use App\Models\Product;
use App\Repositories\ProductRepositoryInterface;

class ProductController extends Controller
{
    protected $product;

    public function __construct(ProductRepositoryInterface $product)
    {
        $this->$product = $product;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data = $this->product->all();

        return $data;
    }
  
}
完成了,全部完成。