dsmvovm27249 2014-10-16 02:21
浏览 71

Laravel 4 - 在哪里调用View :: share

all

I know View::share should be available anywhere within my application, A common place is in my routes.php file.

I am doing this.

1) User login system, after login successfully, share something for all the views.

2) when user click other pages, can use the shared variables.

Ok, my controller.

public function index() {
    $data = array(
        "pageTitle" => "index",
    );

    $privilegeMenu = $this->privilegeApi->getUserPrivilegeByUserId(Session::get('uid'));
    $topMenus = $this->menuApi->getTopMenuById($privilegeMenu);
    $subMenus = $this->menuApi->getSubMenuesById($privilegeMenu);

    View::share('topMenus', $topMenus);
    View::share('subMenus', $subMenus);

    return View::make('home.index',$data);
}

So, because I am using View share, that it is to say, in every other views, I can use topMenus and subMenus now.

But when I click other pages, I got the error: Undefined variable: topMenus.

So, I am so confused what happened? I dive into View::share source code

Laravel have a class named Environment under namespace Illuminate\View.

protected $shared = array();

public function share($key, $value = null)
{
    if ( ! is_array($key)) return $this->shared[$key] = $value;

    foreach ($key as $innerKey => $innerValue)
    {
        $this->share($innerKey, $innerValue);
    }
}

public function shared($key, $default = null)
{
    return array_get($this->shared, $key, $default);
}

And I found when user login successfully, topMenus shared successfully. But when I click other pages, can't topMenus in shared.

It seems everything OK, I am confused. Any one knows ?

Thanks in advanced.

  • 写回答

1条回答 默认 最新

  • duandao1931 2014-10-16 04:45
    关注

    This is because your View::share statement is never ran for other routes. In Laravel 4.x, there are quite a few places you could put it where it would be ran every time, but these two are most commonly used:

    1. The easiest and most simple way is to just add it at the end of your app/start/global.php which is ran at the start of every request, for all environments.

    2. The other way is to create a new service provider, make sure it's autoloadable and add it to your app/config/app.php's providers array.

    If all you want is share a few views, I'd say it's kinda of an overkill to create a whole new class just for that. If, however, you start noticing your app/start/global.php file is getting too cluttered, I'd recommend you start splitting stuff into service providers.

    PS: In Laravel 5, app/start/global.php was removed and you're left only with the second option.

    评论

报告相同问题?

悬赏问题

  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器