How to Use Cache and Keep code DRY in Laravel 5

- 1 answer

Ad

I have the following lines of code that are being repeated, not only in many methods of a Controller but also in more than one Controller.

$Categories = \Cache::rememberForever('Categories', function() {
    return \App\Models\Skill\Category_Model::all();
});

Is there any useful way that I can use this, such that the repeated code can be removed?

Ad

Answer

Ad

Use a Repository to access the Category_Model model:

//REPOSITORY CLASS
class CategoryRepository
{    
    public function getAll()
    {
        return \Cache::rememberForever('Categories', function() {
            return \App\Models\Skill\Category_Model::all();
        });
    }    
}

In the controllers where you need to get the categories, inject the repository from the controller's constructor, and access the repository from the methods:

//INJECT THE REPOSITORY IN YOU CONTROLLER'S CONSTRUCTOR
public function __construct( CategoryRepository $catRepo )
{
    $this->catRepo = $catRepo; 
}

public function index()
{
    //get the categories from the repository 
    $categories = $this->catRepo->getAll();  
}

This will keep your code DRY, as you only need to call $this->catRepo->getAll(); to get all the categories

Ad
source: stackoverflow.com
Ad