سلام
و خسته نباشید
میخواستم بدونم روش استاندارد پیاده سازی ریپزیتوری پترن در لاراول چیه؟؟
کسی تا حالا انجام داده ؟؟
روشی که من در نظر دارم ساخت یک اینترفیس برای هر ریپزیتوری که توابع اختصاصی اون ریپزیتوری رو داشته باشه
و ساخت یک BaseRepository برای عملیات CRUD که تمام ریپزیتوری ها از این کلاس مشتق میشن
ممنون میشم اگر کسی تجربه ای داره بگه
با تشکر
سلام من از روش زیر استفاده میکنم.
۳ تا فوبدر به پروژه اضافه میکنم
۳ مثال هم برای هم قسمت قرار میدم:
Interface
<?php
namespace App\Repositories\Contracts;
interface ProductRepositoryInterface
{
public function search($name);
public function getAllByUser($user_id);
public function getAllByCategory($category_id);
}
Eloquent
<?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();
}
}
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'
);
}
}
و در نهایت سرویس پروایدری که ساختیم رو به کانفیگ لاراول اضافه میکنیم و برای استفاده داخل کنترلر به شکل زیر:
<?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;
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]);
}
}
موفق باشید.
@hesammousavi لطفا نظرتون رو بفرمایید
شاید پاسخ شما همینجا باشد
سلام @hesammousavi
دوره دیزاین پترن رو نگاه میکردم ظاهرا این پترن رو بهش اضافه نکردین