Laravel框架实现多个视图共享相同数据的方法详解(2)

目录下,这个目录一开始是没有的,需要新建

<?php
namespace App\Http\ViewComposers;
use App\Libs\CommonUtils;
use Illuminate\Http\Request;
use Illuminate\View\View;
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 App\Libs;
use App\Admin;
use App\Perm;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
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);
  }
}

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

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/5363.html