Create Laravel Repository with Service Provider

Tạo một class Repository giúp chúng ta rất là nhiều thứ hay chẳng hạn ta hay làm các chức năng thêm, xóa, sửa. Thay vì ta thường viết trong controller thì nhìn nó hơi dài và không được maintain lắm.

Chính vì thế mà ta tạo một class để quản lý các chức năng và đồng thời có thể tái sử dụng ở nhiều nơi trong ứng dụng của mình

# Đầu tiên hãy tạo thư mục Repositories

# Tạo file theo đường đẫn sau : app/Repositories/Interfaces/RepositoryInterface.php

<?php

namespace App\Repositories\Interfaces;

interface RepositoryInterface
{
    /**
     * Get all
     * @return mixed
     */
    public function getAll();

    /**
     * Get one
     * @param $id
     * @return mixed
     */
    public function find($id);

    /**
     * Create
     * @param array $attributes
     * @return mixed
     */
    public function create($attributes = []);

    /**
     * Update
     * @param $id
     * @param array $attributes
     * @return mixed
     */
    public function update($id, $attributes = []);

    /**
     * Delete
     * @param $id
     * @return mixed
     */
    public function delete($id);
}

File trên ta khai báo các function mà ta thường hay sử dụng trong các project của mình

# Tiếp theo tạo file kế thừa file trên, đồng thời viết các chức năng trong các function đó

app/Repositories/BaseRepository.php

<?php

namespace App\Repositories;

use App\Repositories\Interfaces\RepositoryInterface;

abstract class BaseRepository implements RepositoryInterface
{
    //model muốn tương tác
    protected $model;

   //khởi tạo
    public function __construct()
    {
        $this->setModel();
    }

    //lấy model tương ứng
    abstract public function getModel();

    /**
     * Set model
     */
    public function setModel()
    {
        $this->model = app()->make(
            $this->getModel()
        );
    }

    public function getAll()
    {
        return $this->model->all();
    }

    public function find($id)
    {
        $result = $this->model->find($id);

        return $result;
    }

    public function create($attributes = [])
    {
        return $this->model->create($attributes);
    }

    public function update($id, $attributes = [])
    {
        $result = $this->find($id);
        if ($result) {
            $result->update($attributes);
            return $result;
        }

        return false;
    }

    public function delete($id)
    {
        $result = $this->find($id);
        if ($result) {
            $result->delete();

            return true;
        }

        return false;
    }
}

Đoạn code bên trên cũng khá đơn giản, ta chỉ cấu hình các chức năng , cần thiết 

Tiếp theo, giả sử ta tạo một category có các chức năng thêm ,sửa,  xóa, vậy thì ta sẽ làm thế nào ta ::). Việc đầu tiên để kế thừa các chức năng trên ta sẽ làm như sau:

# Tạo file dưới đây, ta cần extends tới class RepositoryInterface, để có thể kế thừa các function của lớp cha, đồng thời ta cũng có thể khai báo các function khác mà ta cần bên trong class CategoryRepositoryInterface này luôn

app/Repositories/Interfaces/CategoryRepositoryInterface.php

<?php 

namespace App\Repositories\Interfaces;
use App\Repositories\Interfaces\RepositoryInterface;
use App\Models\Category;
interface CategoryRepositoryInterface extends RepositoryInterface{
    public function getCategory();
}

# Tiếp theo cũng như nói bên trên, bạn đã có khai báo các function trong class CategoryRepositoryInterface rồi, thì bạn cũng phải cần viết chức năng bên trong hàm của chúng

app/Repositories/CategoryRepository.php  : kế thừa class CategoryRepositoryInterface để viết code xử lý cho từng fucntion được khai báo

<?php 

namespace App\Repositories;
use App\Repositories\BaseRepository;
use App\Repositories\Interfaces\CategoryRepositoryInterface;

class CategoryRepository extends BaseRepository implements CategoryRepositoryInterface{
    
   //lấy model tương ứng
   public function getModel()
   {
       return \App\Models\Category::class;
   }

    public function getCategory()
    {
      return $this->model->all();

    }
    
}

Để sử dụng được chúng, thì bước này quan trọng, bạn cần phải khai báo nó trong Service Provider nhé, hãy tạo một service provider cho dễ xử lý

php artisan make:provider RepositoryServiceProvider

Bạn sẽ thấy chúng trong đường dẫn sau: app/Providers/RepositoryServiceProvider.php , ta cần khai báo các lớp trên vào file service provider này

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Repositories\CategoryRepository;
use App\Repositories\Interfaces\CategoryRepositoryInterface;
class RepositoryServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        $this->app->singleton(CategoryRepositoryInterface::class,CategoryRepository::class);
      
    }
}

Sau khi bạn có file service provider bên trên rồi, thì hay cho laravel biết rằng, ta có một service cần phải chạy, và hay chạy cho ta nhé, thì làm như sau

mở file config/app.php tìm đến "providers" và thêm class service provider vừa tạo bên trên vào mảng của "providers"

'providers' => [

        /*
         * Laravel Framework Service Providers...
         
         */
       
        App\Providers\RepositoryServiceProvider::class,

    ],

# Cách sử dụng để gọi trong Controller như sau:

use App\Repositories\Interfaces\CategoryRepositoryInterface;

class CategoryController extends Controller
{
    protected $cateRepo;

    public function __construct(CategoryRepositoryInterface $cateRepo)
    {
        $this->cateRepo = $cateRepo;
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {

         $categories = $this->cateRepo->getAll(); //dùng cái này cũng được nhé
       
        return view('pages.category.list')->with(array("categories"=>$this->cateRepo->getCategory()));
    }
}

Vậy là các bạn có một file Controller đẹp, maintain 

Bài Viết Liên Quan

Messsage

Ủng hộ tôi bằng cách click vào quảng cáo. Để tôi có kinh phí tiếp tục phát triển Website!(Support me by clicking on the ad. Let me have the money to continue developing the Website!)