有没有一种方法可以为appserviceprovider值设置缓存?

时间:2019-02-19 14:47:46

标签: laravel caching

当前,我正在尝试为appserviceprovider中的视图设置缓存。我这样尝试过:

$user_id

但是此方法不返回值。我认为我不应该在这里“返回”。我该怎么办?我没有找到任何解决方案。提前致谢。

这样尝试实际上可以正常工作:

public function boot()
{
    $appServiceProvider = Cache::remember('appServiceProvider', 60, function () {
            View::composer('*', function ($view) {
            $view->with('home_references', Reference::where('position', 'home')->orderBy('order', 'asc')->get());
            $view->with('informations', ContactInformation::first());
            $view->with('header_posts', Post::latest()->limit(4)->get());
        });
    });
    return $appServiceProvider;
}

但是那是在重复自己。我需要将缓存设置为一个参数。在此示例中,存在3个查询。但可能是30个查询。我正在寻找更好的解决方案。

1 个答案:

答案 0 :(得分:0)

function调用中Cache::remember的返回值就是要缓存的内容。如果您不返回,则只是在缓存null

您将想要这样的东西:

public function boot()
{
    View::composer('*', function ($view) {
        $homeReferences = Cache::remember('home_references', 60, function () {
            return Reference::where('position', 'home')->orderBy('order', 'asc')->get();
        });

        $informations = Cache::remember('informations', 60, function () {
            return ContactInformation::first();
        });

        $headerPosts = Cache::remember('header_posts', 60, function () {
            return Post::latest()->limit(4)->get();
        });

        $view->with('home_references', $homeReferences);
        $view->with('informations', $informations);
        $view->with('header_posts', $headerPosts);
    });
}
相关问题