Laravel 4中的全局变量 [英] Global variable in laravel 4

查看:52
本文介绍了Laravel 4中的全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何做一个全局变量来为我节省几行复制并粘贴这些行.可能将其排列并放入一个变量中?我想在其他路线中使用此变量.

I was wondering how to do a global variable to save me few lines of copy and pasting this lines. Array it probably and put them in one variable instead? I want to use this variable in other routes.

  $providerEmail = Auth::user()->email;
  $providerName = Auth::user()->first_name;
  $providerSurname = Auth::user()->last_name;
  $providerMobile = Auth::user()->mobile;

推荐答案

您可以在App::before事件中创建全局singleton

You can create a global singleton within App::before event

App::before(function($request)
{
    // Singleton (global) object
    App::singleton('myApp', function(){
        $app = new stdClass;
        if (Auth::check()) {
            // Put your User object in $app->user
            $app->user = Auth::User();
            $app->isLoggedIn = TRUE;
        }
        else {
            $app->isLoggedIn = FALSE;
        }
        return $app;
    });
    $app = App::make('myApp');
    View::share('myApp', $app);
});

在任何视图中,都可以使用它

In any view, use it like

if($myApp->isLoggedIn) {
    $myApp->user->email;
    $myApp->user->first_name;
    // ...
}

在任何控制器中,您都可以使用

In any controller, you can use

$myApp = App::make('myApp');
if($myApp->isLoggedIn) {
    $myApp->user->email;
    $myApp->user->first_name;
    // ...
}

查看应用程序事件.

这篇关于Laravel 4中的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆