Laravel - Using the Repository Pattern

末鹿安然 提交于 2019-11-30 06:57:31
The Alpha

You are over thinking, repository is just a link/bridge between your controller and model and hence controller uses repository class instead of the model directly and in that repository you may declare your methods using the model from there, for example:

<?php namespace GD\Repositories\Category;

interface CategoryInterFace{

    public function all();

    public function getCategoriesWith($with);

    public function find($id);
}

Now implement the interface in the repository class:

<?php namespace GD\Repositories\Category;

use \EloquentCategory as Cat; // the model
class CategoryRepository implements CategoryInterFace {
    public function all()
    {
        return Cat::all();
    }

    public function getCategoriesWith($with)
    {
        return Cat::with($with)->get();
    }

    public function find($id)
    {
        return Cat::find($id):
    }
}

To use it in your controller:

<?php

use GD\Repositories\Category\CategoryInterFace;

class CategoryController extends BaseController {

    public function __construct(CategoryInterFace $category)
    {
        $this->cat = $category;
    }

    public function getCatWith()
    {
        $catsProd = $this->cat->getCategoriesWith('products');
        return $catsProd;
    }

    // use any method from your category
    public function getAll()
    {
        $categories = $this->cat->all();

        return View::make('category.index', compact('categories'));
    }

}

Note: Omitted the IoC binding of the repository because this is not your problem and you know that.

Update: I've written an article here: LARAVEL – USING REPOSITORY PATTERN.

There is a really easy way to do this and it is explored in depth in this link

http://heera.it/laravel-repository-pattern#.U6XhR1cn-f4

I was looking for the exact solution and it is working well so far

so the idea for you would be to declare this in your repository code

public function __construct(\Category $category)
{
    $this->category = $category;
} 
public function getAllUsers()
{
    return $this->category->all();
}

public function __call($method, $args)
{
    return call_user_func_array([$this->category, $method], $args);
}

forcing the Model to be called when some functions are missing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!