如何在Zend框架1中获取布局中的会话值?

时间:2013-09-23 16:01:56

标签: php zend-framework

我想从layout.xml访问会话值。

我所做的代码是

Layout.xml

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

索引控制器/索引操作

  $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');

Home Controller / index action

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

主页/ index.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

我可以在Home / index.html中获取会话值。

期待积极的帮助。

2 个答案:

答案 0 :(得分:0)

为什么在布局中使用Zend_Session并在视图中使用Zend_Session_Namespace? 也许你应该在视图/布局中使用会话,但是从控制器或引导文件传递它作为参数

答案 1 :(得分:0)

我同意Amine的观点,将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; ?>