zoukankan      html  css  js  c++  java
  • Laravel实现多个视图共享相同的数据

    最近在用Laravel写一个cms,还没有完成,但是也遇到了许多难点,比如cms后台每个视图都要展示相同的导航菜单数据。

    环境:
    PHP 7.1
    Apache 2.4
    MySQL 5.7
    Laravel 5.4

    • 传统方法

    假设使用传统的方法,应该是在每个控制器中都调用数据,然后把数据都塞给视图。

    $menu = DB::table('menu')->get();
    return view('xx',['menu'=>$menu]);
    • 稍微优化

    新建一个BaseController,然后让BaseController去获取数据,然后在每个控制器都继承BaseController,最后将数据塞到视图中。

    基类

    class BaseController{
        protected $menu = null;//菜单数据
        public function  __construct(){
            $this->getMenu();//获取导航菜单
        }
        public function getMenu(){
            $this->menu = DB::table('menu')->get();
        }
    }
    

    A控制器

    class AController extends BaseController{
        public function index(){
            return view('admin.index',['menu'=>$this->menu,'user'=>$user]);
        }
    }

    缺点:在每个控制器中都需要重新设置相同的模板的数据(menu)

    • 最好优化方案

    使用Laravel中的View Composers来解决这个问题

    1、在AppProviders下创建一个ComposerServiceProvider类

    <?php
    
    namespace AppProviders;
    
    use IlluminateSupportFacadesView;
    use IlluminateSupportServiceProvider;
    
    class ComposerServiceProvider extends ServiceProvider {
        /**
         * Register bindings in the container.
         *
         * @return void
         */
        public function boot() {
            // 基于类的view composer
            View::composer(
                'admin.common.*', 'AppHttpViewComposersAdminComposer'
            );
        }
    
        /**
         * Register the service provider.
         *
         * @return void
         */
        public function register() {
            //
        }
    }

    在boot方法中定义要监听的视图,还可以使用通配符,这里我写的是admin.common.*,如果admin.common.* 下的视图被渲染的话将会调用AppHttpViewComposersAdminComposer@composer 方法

    2、注册ComposerServiceProvider

    config/app.php文件下的providers数组中进行注册

    AppProvidersComposerServiceProvider::class,

    3、创建AdminComposer类

    Laravel推荐把view composer类放在appHttpViewComposers目录下,这个目录一开始是没有的,需要新建

    <?php
    
    namespace AppHttpViewComposers;
    
    use AppLibsCommonUtils;
    use IlluminateHttpRequest;
    use IlluminateViewView;
    
    class AdminComposer {
    
        private $data = null;//CommonUtils对象
    
        public function __construct(Request $request) {
            $this->data = new CommonUtils($request);//新建一个CommonUtils对象
        }
    
        public function compose(View $view) {
            $view->with([
                'admin' => $this->data->admin,
                'mbx' => $this->data->mbx,
                'menu' => $this->data->menu,
                'msg' => $this->data->msg
            ]);//填充数据
        }
    }

    在这里我在构造方法中创建了一个对象,这个对象中包含着数据

    5、CommonUtils文件

    <?php
    /**
     * Created by PhpStorm.
     * User: Administrator
     * Date: 2017/4/20 0020
     * Time: 19:49
     */
    
    namespace AppLibs;
    
    use AppAdmin;
    use AppPerm;
    use IlluminateHttpRequest;
    use IlluminateSupportFacadesDB;
    
    class CommonUtils {
    
        public $admin = null;//管理员对象
        public $menu = null;//菜单对象
        public $mbx = null;//面包屑对象
        public $msg = null;//消息对象
    
        /**
         * 构造函数
         */
        public function __construct(Request $request) {
            $this->init($request);
        }
    
        /**
         * 初始化函数
         */
        private function init(Request $request) {
            $this->getAdmin($request);
            $this->getMsg();
            $this->getMenu($request);
            $this->getMbx($request);
        }
    
        /**
         * 获取管理员数据
         */
        private function getAdmin() {
            $this->admin = session('admin');
        }
    
        /**
         * 获取后台菜单数据
         */
        private function getMenu(Request $request) {
            $menu = DB::table('menu')->where('parentid', 0)->orderBy('sort')->get();
            $router = $request->getPathInfo();
            $perm = new Perm();
            $mbx = $perm->getMbx($router);
            foreach ($menu as $k => $m) {
                $m->active = '';
                //读取子菜单
                $childMenu = DB::table('menu')->where('parentid', $m->id)->orderBy('sort')->get();
                if (count($childMenu) > 0) {
                    foreach($childMenu as $v){
                        $v->active = '';
                        if($mbx[0]->router == $v->router){
                            $v->active = 'active';
                            $m->active = 'active';
                        }
                    }
                    $m->childMenu = $childMenu;
                } else {
                    $m->childMenu = null;
                }
            }
            $this->menu = $menu;
        }
    
        /**
         * 获取面包屑
         */
        private function getMbx(Request $request) {
            $router = $request->getPathInfo();
            $perm = new Perm();
            $mbx = $perm->getMbx($router);
            $this->mbx = $mbx;
        }
    
        /**
         * 获取未读消息
         */
        private function getMsg() {
            $adminModel = new Admin();
            $toId = $this->admin->id;
            $this->msg = $adminModel->getUnReadMsg($toId);
        }
    }

    在这里面分别获取了管理员、菜单、面包屑、消息数据,这些数据都是每个后台页面都要使用到的。

    注意:这里我将类定义成了CommonUtils,感觉名字取得不好,CommonUtils是存放在AppLibs下的,这个Libs文件夹是我新建的,用于存放工具类的。如果需要给AppLibs文件夹添加自动加载,需要在composer.json文件里做如下修改。

    这里写图片描述

  • 相关阅读:
    jQuery常用操作
    SharePoint2007深入浅出——使用jQuery UI
    深入浅出SharePoint——常用的url命令
    MySQL实战
    Emacs助力PowerShell
    电商平台实战——准备篇
    深入浅出SharePoint2012——安装Report Service
    (转).net面试题(老赵)
    (转)在.NET程序运行过程中,什么是堆,什么是栈?什么情况下会在堆(栈)上分配数据?它们有性能上的区别吗?“结构”对象可能分配在堆上吗?什么情况下会发生,有什么需要注意的吗?
    (转)类(class)和结构(struct)的区别是什么?它们对性能有影响吗?.NET BCL里有哪些是类(结构),为什么它们不是结构(类)?在自定义类型时,您如何选择是类还是结构?
  • 原文地址:https://www.cnblogs.com/cnsec/p/13407004.html
Copyright © 2011-2022 走看看