vendredi 26 mai 2017

Should I define model class functions for repeated controller codes in Laravel 5?

I use the code like that repeatedly in my controllers:

    ...    
    if (Cache::has('user_' . $id)) {
        $user = Cache::get('user_' . $id);
    } else {            
        $user = User::with('location')->find($id);
        if(!$user) {
            return Response::view('errors/404', array());
        }
        Cache::put('user_' . $id, $user, 15);
    }
    ...

Is it best practice to place them in Model classes as a class function? So that I would write just one line:

$user = User::getUserDetails($id);

And in model classes:

public function getUserDetails($id)
{        
    if(Cache::has('user_' . $id)) {
        $user = Cache::get('user_' . $id);
    } else {            
        $user = User::with('location')->find($id);
        if(!$user) {
            return Response::view('errors/404', array());
        }
        Cache::put('user_' . $id, $user, 15);
    }
    return $user;
}

What do you suggest?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2rZZipU
via IFTTT

Aucun commentaire:

Enregistrer un commentaire