Ví dụ Repository Pattern Laravel
Đầu tiên, chúng ta sẽ tạo repository interface. Có thể tạo nó ở bất cứ đâu,nhưng trong ví dụ này, chúng ta sẽ sử dụng cấu trúc thư mục như sau:
app/Repositories/Contracts: Tất cả file repository interfaces chứa ở đây
app/Repositories/Eloquent: Tất cả interface Eloquent implementations chứa ở đây
app/Repositories/Providers: Service providers for repositories chứa ở đây
Tạo file ProductRepositoryInterface:
<?php namespace App\Repositories\Contracts; interface ProductRepositoryInterface { public function search($name); public function getAllByUser($user_id); public function getAllByCategory($category_id); }
Tạo file ProductRepository
<?php namespace App\Repositories\Eloquent; use App\Repositories\Contracts\ProductRepositoryInterface; use App\Entity\Product; class ProductRepository implements ProductRepositoryInterface { public function search($name) { return Product::where('title', 'LIKE', '% ' . $name . '%') ->get(); } public function getAllByUser($user_id) { return Product::where('user_id', '=', $user_id) ->get(); } public function getAllByCategory($category_id) { return Product::where('category_id', '=', $category_id) ->get(); } }
Đăng ký service provider:
<?php namespace App\Repositories\Providers; use Illuminate\Support\ServiceProvider; class ProductRepositoryServiceProvider extends ServiceProvider { public function register() { $this->app->bind( 'App\Repositories\Contracts\ProductRepositoryInterface', // To change the data source, replace this class name // with another implementation 'App\Repositories\Eloquent\ProductRepository' ); } }
Thêm class ProductRepositoryServiceProvider vào array providers trong file config/app.php
App\Repositories\Providers\ProductRepositoryServiceProvider::class,
File controller:
<?php namespace App\Http\Controllers; use Illuminate\Routing\Controller as BaseController; use Illuminate\Http\Request; use App\Repositories\Contracts\ProductRepositoryInterface; class ProductController extends BaseController { protected $productRepository; // $productRepository will call the methods from the // class defined above in the service provider public function __construct(ProductRepositoryInterface $productRepository) { $this->productRepository = $productRepository; } public function search(Request $request) { $name = $request->input('name'); $products = $this->productRepository->search($name); return view('home.index', ['products' => $products]); } }
Nguồn tham khảo:https://www.developer.com/lang/php/the-repository-pattern-in-php.html