問題描述
我有以下代碼:
<?php
if (!$this->Auth->user())
{
echo $this->element('header');
}
else
{
echo $this->element('header-bar');
}
?>
在我的視圖中,它應該為登錄用戶顯示不同的標題,但會引發以下錯誤:
inside my view which should show a different header for logged in users but throws the following error:
Notice (8): Undefined property: View::$Auth [APP/views/layouts/page.ctp, line 17]
Fatal error: Call to a member function user() on a non-object in /Users/cameron/Sites/thehive/app/views/layouts/page.ctp on line 17
我該如何解決這個問題?謝謝
How do I fix this? Thanks
推薦答案
注意: 另請查看 meotimdihia 的 下面的答案.它獲得了很多的贊成票.
Note: Also check out meotimdihia's answer below. It's got a lot of upvotes.
Auth 組件用于控制器.您需要在控制器中檢查授權,然后為視圖設置一個變量,例如 $this->set('authUser', $this->Auth->user());代碼>.然后在您看來,您可以執行以下操作:
The Auth component is for use in the Controller. You'll want to check for authorization in the controller, then set a variable for the view, e.g., $this->set('authUser', $this->Auth->user());
. Then in your view you can do:
if (!$authUser)
{
echo $this->element('header');
}
如果您希望為所有控制器方法自動完成此操作,您可以考慮修改 cake/libs/controller/app_controller.php
以使其包含 Auth 組件.
If you want this to be done automatically for all controller methods, you can look into modifying cake/libs/controller/app_controller.php
so that it includes the Auth component.
這篇關于CakePHP 檢查用戶是否在視圖中登錄的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!