10.Laravel使用视图组合器(View composer)

栏目: PHP · 发布时间: 7年前

内容简介:Laravel的视图组合器很有用,在网站中, 许多页面的侧边栏是相同的,将侧边栏公用部分提取出来肯定是必须的,让Controller专注于业务逻辑。参考:创建一个新的 provider类 ViewComposerServiceProvider

Laravel的视图组合器很有用,在网站中, 许多页面的侧边栏是相同的,将侧边栏公用部分提取出来肯定是必须的,让Controller专注于业务逻辑。

参考: https://laravel.com/docs/5.5/...

创建一个新的 provider类 ViewComposerServiceProvider

php artisan make:provider ViewComposerServiceProvider

编辑ViewComposerServiceProvider类文件中boot()方法,添加如下代码:

// 参数'*':代表所有视图,其实可以指定视图
// \App\Http\ViewComposers\PublicComposer:公共视图的业务逻辑,目录位置是自定义的
\View::Composer('*', '\App\Http\ViewComposers\PublicComposer');

在ConfigApp.php配置文件中配置$provider数组,加入自定义的ViewComposerServiceProvider类

App\Providers\ViewComposerServiceProvider::class

编辑AppHttpViewComposersPublicComposer类文件中compose()方法,添加公共数据的业务逻辑

public function compose(View $view)
{
    $categories = $this->cache('categories', function () {
        // 获取数据逻辑
        return Category::all();
    }, 60*24);

    $tags = $this->cache('tags', function () {
        return Tag::all();
    }, 60*24);

    // $view->with()方法绑定参数到视图
    $view->with(compact('categories', 'tags'));
}

// 封装一个缓存处理方法
private function cache($key, $callback, $time = 60)
{
    $key_result = [];
    if (Cache::has($key)) {
        $key_result = Cache::get($key);
    } else {
        $key_result = $callback();
        Cache::put($key, $key_result, $time);
    }
    return $key_result;
}

原文链接: http://www.mi360.cn/articles/4


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Modeling the Internet and the Web

Modeling the Internet and the Web

Pierre Baldi、Paolo Frasconi、Padhraic Smyth / Wiley / 2003-7-7 / USD 115.00

Modeling the Internet and the Web covers the most important aspects of modeling the Web using a modern mathematical and probabilistic treatment. It focuses on the information and application layers, a......一起来看看 《Modeling the Internet and the Web》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

MD5 加密
MD5 加密

MD5 加密工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具