php Laravel 4 中的全局变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19952572/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 20:17:01  来源:igfitidea点击:

Global variable in laravel 4

phpvariableslaravellaravel-4global

提问by nCore

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;

回答by The Alpha

You can create a global singletonwithin App::beforeevent

您可以singletonApp::before事件内创建全局

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;
    // ...
}

Check out Application Events.

查看应用程序事件

回答by ajtrichards

The best way i've seen is by using a config file.

我见过的最好的方法是使用配置文件。

In your app -> config folder, you create a new file called (for example settings.php)

在您的应用程序 -> config 文件夹中,您创建一个名为(例如settings.php)的新文件

 app
     config
         settings.php

Then in your configuration file you just created (settings.php) you could add:

然后在您刚刚创建的配置文件 ( settings.php) 中,您可以添加:

<?php

$setting_data['foo'] = 'bar';
$setting_data['bar'] = 'foo';

return $setting_data;

You can then retrieve the config file from your code using:

然后,您可以使用以下方法从代码中检索配置文件:

echo Config::get('settings.foo'); // Will echo bar
echo Config::get('settings.bar'); // Will echo foo

回答by Antonio Carlos Ribeiro

Globals are bad. No matter of what, don't use global variables, don't think about using global variables, always think about how can you not use them in your code and still have all you need to have. Here are some reasons, and there are lot more.

全局是坏的。无论如何,不​​要使用全局变量,不要考虑使用全局变量,总是想着如何在代码中不使用它们并且仍然拥有您需要的一切。这里有一些原因,还有更多。

Instead, use Laravel power to help you:

相反,使用 Laravel 的力量来帮助你:

Enforce login on your routes creating groups of authenticated routes:

强制登录您的路由,创建经过身份验证的路由组:

Route::group(array('before' => 'auth'), function()
{
    Route::get('/users/posts', array('as'=>'users.posts.index', 'uses'=>'PostsController@usersPostsIndex'));
});

Now you know that every call to your posts will be authenticated, you can just

现在您知道对您帖子的每次调用都将经过身份验证,您只需

class PostsController extends Controller {

    public function usersPostsIndex()
    {
        return View::('users.posts.index')->
                with('user', Auth::user());
    }

}

In your view you'll just have to

在你看来,你只需要

{{$user->email}}
{{$user->first_name . ' ' . $user->last_name}}
{{$user->email}}
{{$user->mobile}}

If you don't want to write code to send a User instance to all your views, use the magic of Laravel's View Composers, adding this to your filters.php or creating a composers.php file:

如果您不想编写代码将 User 实例发送到您的所有视图,请使用 Laravel 的 View Composers 的魔力,将其添加到您的 filters.php 或创建一个 composers.php 文件:

View::composer(array('users.posts.index','users.posts.edit'), function($view)
{
    $view->with('user', Auth::user());
});

And this is now how your views can be used now:

这就是现在可以使用您的视图的方式:

class PostsController extends Controller {

    public function usersPostsIndex()
    {
        return View::('users.posts.index');
    }

    public function usersPostsEdit()
    {
        return View::('users.edit.index');
    }

}

Because Laravel will automatically inject Auth::user()in those views as $user.

因为 Laravel 会自动将Auth::user()这些视图作为$user.

回答by Justin

I like the View::sharemethod.

我喜欢这个View::share方法。

Add the following in app/controllers/BaseController.php

app/controllers/BaseController.php 中添加以下内容

class BaseController extends Controller {
    public function __construct() {       
        $name = 'Hyman';    
        View::share('user', $name); // Share $user with all views
    }
}

and now $userwill be available to all your views.

现在$user将提供给您的所有视图。

References: Laravel docs, blog post

参考资料: Laravel 文档博客文章

回答by Sajan Parikh

I also gave you the same answer in another question you asked, you did not respond. Link

我在你问的另一个问题中也给了你同样的答案,你没有回应。关联

There is no reason to have a separate variable for each property of your $providermodel. Simply save the entire model to a variable like this.

没有理由为$provider模型的每个属性设置一个单独的变量。只需将整个模型保存到这样的变量中即可。

if (Auth::check())
{
    $provider = Auth::user();
}

This would generally be done in a route like this.

这通常会在这样的路线中完成。

Route::get('/provider/page/example', function()
{
    $provider = Auth::user();

    return View::make('name.of.view', ['provider' => $provider]);
});

After having done that, you can access the different properties in of the $providerin your views like this.

完成后,您可以$provider像这样访问视图中的不同属性。

<p>Your email address is: {{$provider->email}} and your first name is {{$provider->first_name}}</p>

Another option is to use a controller and set this variable only once in the controller, making it accessible from all views using View::share().

另一种选择是使用控制器并在控制器中仅设置一次此变量,使其可以从使用View::share().

class ProviderController extends BaseController {

    protected $provider;

    public function __construct()
    {
        $this->provider = Auth::user();

        View::share('provider', $this->provider);
    }

    public function getIndex()
    {
        return View::make('some.view.name');
    }
}

After having done just this, you can use the $providervariable in your views as shown above using things like $provider->email. You can also use it elsewhere in the controller by using $this->provider.

完成此操作后,您可以$provider在视图中使用该变量,如上所示使用$provider->email. 您还可以使用$this->provider.

回答by Gerep

You should create an object to do that.

你应该创建一个对象来做到这一点。

Create a providerobject with those properties, email, name, etc and instantiate it and set the properties values, like:

创建provider具有这些属性、emailname等的对象并实例化它并设置属性值,例如:

$provider = new Provider();

$provider->email = Auth::user()->email;

And then you save the object in your session:

然后将对象保存在会话中:

$_SESSION['provider'] = $provider;

I'm not familiar with Laravel and I don't know if it's a good practice to work directly with the Authobject but a simpler solution would be:

我不熟悉 Laravel,我不知道直接使用Auth对象是否是一个好习惯,但更简单的解决方案是:

$_SESSION['provider'] = Auth::user();

Also be aware of working with sensitive information on your session :)

还要注意处理会话中的敏感信息:)