在使用Sentry bundle时,我创建了LoginController
控制器来检查用户是否登录了他们被重定向的地方,以防他们没有。我的目的是将所有受限页面扩展到该类,以使代码更高效。但为什么行不通呢?
// Extends the BaseController
class LoginController extends BaseController {
public function __construct() {
if(!Sentry::check()) return Redirect::to('login');
}
}
我的实际控制器:
class MainController extends LoginController {
public function getIndex() {
if(Sentry::getUser()->hasAccess('view dashboard')) {
return View::make('admin.index');
} else {
return 'You have no access!';
}
}
}
我总是得到错误:
Call to a member function hasAccess() on a non-object
工作原理:如果我在getIndex()
中直接添加if(!Sentry::check()) return Redirect::to('login');
而不是__construct
,重定向工作正常。为什么?
注意错别字!__construct缺少s.
我认为__construct()方法只会在初始化时被调用。在您的例子中,您是扩展它而不是初始化它。如果你这样做,它可能会工作。
class MainController extends LoginController {
public function __construct()
{
return parent::__construct();
}
public function getIndex() {
if(Sentry::getUser()->hasAccess('view dashboard')) {
return View::make('admin.index');
} else {
return 'You have no access!';
}
}
我也认为问题是
public function __construct()
{
parent::__construct();
}
如果你想执行父类,你需要调用父类的构造
可能是因为你没有登录?
你可能需要这样的东西
try
{
// Get the current active/logged in user
$user = Sentry::getUser();
}
catch (Cartalyst'Sentry'Users'UserNotFoundException $e)
{
// User wasn't found, should only happen if the user was deleted
// when they were already logged in or had a "remember me" cookie set
// and they were deleted.
}