Phalcon \ Session \ Bag ..如何使用它们?

时间:2013-02-01 10:49:25

标签: php phalcon

在我的项目中,我使用以下代码通过服务中的Session Bags访问会话变量:

public function __construct()
{
    // Create session bag
    $className = get_class($this);
    $this->storage = new Phalcon\Session\Bag($className);    
}

但是这给出了一个例外“访问'session'服务需要依赖注入对象。”

好的,似乎我们需要在这里设置DI。最简单的方法 - 在DI中定义不共享的sessionBag服务($ di将自动设置)。但是,我怎么能理解我应该以这种方式为Session包设置哪个名称?例如:

$di->set('sessionBag', function() use ($config) {
    $name = ''; // ???
    $bag = new \Phalcon\Session\Bag($name);
    return $bag;
});      

2 个答案:

答案 0 :(得分:1)

您可以使您的类继承自Phalcon \ DI \ Injectable,当您访问持久属性时会隐式创建会话包:

class MyComponent extends Phalcon\DI\Injectable
{

    public function someMethod()
    {
        $this->persistent->someName = "peter";
    }

}

答案 1 :(得分:0)

//Start the session the first time when some component request
// the session service
$di->setShared('session', function() {
    $session = new Phalcon\Session\Adapter\Files();
    $session->start();
    return $session;
});

示例:

auth.php:     

public function __construct(){
    $this->_di = \Phalcon\DI::getDefault ();
    $this->user       = new \Phalcon\Session\Bag(get_class());
    $this->user->setDI($this->_di);
}

/**
 *
 * @param int
 *
 * @return bool
 */
public function authenticate($identity){
    $this->user->identity=$identity;
}
/**
 * @return boolean
 */
public function isAuthenticate(){
    return $this->user->identity?true:false;
}