在我的Laravel 4项目中,我使用share()
方法将当前用户绑定到视图中,如下所示:
View::share(['currentUser' => Sentry::getUser()]);
这在浏览网站时有效,所有视图都可以访问变量$currentUser
。但是,在尝试测试我的应用程序时,尽管用户肯定已登录,但该变量从未绑定。
class PagesControllerTest extends TestCase
{
public function setUp()
{
parent::setUp();
// This works, as halting the application and dumping the user manually demonstrate it as such.
Sentry::login(User::first());
}
public function testIndex()
{
$this->get('/');
$this->assertResponseOk();
}
}
但是,这只会导致错误的堆栈跟踪......
ErrorException: Trying to get property of non-object (View: ~/Sites/laravel/app/views/layouts/application.blade.php) (View: ~/Sites/laravel/app/views/layouts/application.blade.php)
...
Caused by
ErrorException: Trying to get property of non-object (View: ~/Sites/laravel/app/views/layouts/application.blade.php)
...
Caused by
ErrorException: Trying to get property of non-object
此失败的确切行是视图尝试访问$currentUser
变量的位置。
如果我使用视图编辑器,如下所示,它解决了此实例中的问题 - 但我希望变量在所有视图中可用,而不仅仅是我指定的变量,我也想知道为什么这种情况正在发生。
View::composer('layouts.application', function($view)
{
$view->with('currentUser', Sentry::currentUser());
});
答案 0 :(得分:1)
我猜你在app / start / global.php中正在做View::share
。通过调用parent::setUp()
来调用此文件,这是在您完成Sentry::login
之前,因此$currentUser
将为空。您应该找到一种方法来延迟View::share
(使用视图编辑器是一种方法)或者只是在视图中使用Sentry::getUser()
。