2013-09-23 32 views
0

我想從layout.xml訪問會話值。如何在Zend框架1中獲取佈局中的會話值?

我做的代碼是

Layout.xml

<h2><?php $myprofile=new Zend_Session('user_session'); 
    print $myprofile->username; ?> </h2> 

指數控制器/ index動作

$userid = $this->_user->getUserId($username,$password); 
    $session = new Zend_Session_Namespace('user_session'); 
    $session->username = $username; 
    $session->password = $password; 
    $session->uid = $userid; 
    $this->_redirect('home'); 

首頁控制器/ index動作

$this->session = new Zend_Session_Namespace('user_session'); 
$this->view->uname = $this->session->username; 

首頁/指數.phtml

<?php echo "The User Name is ".$this->uname?> 

但它顯示了一個錯誤

Fatal error: Call to protected Zend_Session::__construct() from context 'Zend_View' in/var/www/shoppingcart/application/layouts/scripts/layout.phtml on line 19 

我能夠獲得首頁/ index.html中的會話值。

期待積極幫助..

爲什麼downvote?

回答

0

爲什麼在視圖的佈局和Zend_Session_Namespace中使用Zend_Session? 也或許你should'n使用會話視圖/佈局,但把它作爲從控制器PARAM或引導文件

+0

我正在使用的佈局會使其​​顯示在用戶登錄後的每一頁。 –

0

我這裏胺同意,把Zend_Session視圖中的腳本通常被認爲是不好的做法。我確實會把它放進引導爲好,像下面這樣...

// Bootstrap.php 
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap 
{ 
    public function _initUserSession() 
    { 
     // If not already done, bootstrap the view 
     $this->bootstrap('view'); 
     $view = $this->getResource('view'); 

     // Initialise the session 
     $session = new Zend_Session_Namespace('user_session'); 

     // See if the username has been set, and if not at 
     // least make the variable 
     if (isset($session->username) 
      $view->username = $session->username; 
     else 
      $view->username = null;  
    } 
} 

然後在佈局,你可以這樣做:

<?php if ($this->username !== null) : ?> 
    The User Name is <?php echo $this->username ?> 
<?php else : ?> 
    No username has been set. 
<?php endif; ?> 
+0

我實際上是創建一個示例網站,其中會話設置(與用戶的詳細信息),當用戶登錄成功.. 所以現在我的疑問是如果我設置會話在用戶控制器索引操作(在登錄驗證的地方),我可以在將zend_session放入引導後訪問佈局中的會話值(如上面的示例)。 –

+0

一旦設置了會話,它將一直存在於應用程序中直到會話失效(可以是手動清除或會話超時)。所以是的,一旦控制器中的動作設置了會話,它就會在引導程序中可用。 –