global variable for all controller and views

后端 未结 16 2113
Happy的楠姐
Happy的楠姐 2020-11-27 15:54

In Laravel I have a table settings and i have fetched complete data from the table in the BaseController, as following

public function __construct() 
{
             


        
16条回答
  •  遥遥无期
    2020-11-27 16:16

    If you are worried about repeated database access, make sure that you have some kind of caching built into your method so that database calls are only made once per page request.

    Something like (simplified example):

    class Settings {
    
        static protected $all;
    
        static public function cachedAll() {
            if (empty(self::$all)) {
               self::$all = self::all();
            }
            return self::$all;
        }
    }
    

    Then you would access Settings::cachedAll() instead of all() and this would only make one database call per page request. Subsequent calls will use the already-retrieved contents cached in the class variable.

    The above example is super simple, and uses an in-memory cache so it only lasts for the single request. If you wanted to, you could use Laravel's caching (using Redis or Memcached) to persist your settings across multiple requests. You can read more about the very simple caching options here:

    http://laravel.com/docs/cache

    For example you could add a method to your Settings model that looks like:

    static public function getSettings() {
        $settings = Cache::remember('settings', 60, function() {
            return Settings::all();
        });
        return $settings;
    }
    

    This would only make a database call every 60 minutes otherwise it would return the cached value whenever you call Settings::getSettings().

提交回复
热议问题