在 Yii 的控制器中创建构造函数方法

2022-01-04 00:00:00 php mysql yii

我刚刚开始学习Yii,在这里我创建了一个PostController 控制器.在这个控制器中,我有一个使用 Sessions 的要求.

I have just started to learn Yii, where I have created one PostController Controller. In this controller I am having one requirement of using Sessions.

所以我创建了一个构造函数方法,其代码如下

So I have created one constructor method and its code is as follows

public $session;
public function __construct() {
    $this->session = new CHttpSession;
    $this->session->open();
}

但是在创建此构造函数后,控制器无法正常工作并出现错误.删除此代码后,我的控制器运行良好.我在构造函数中编写了这段代码,以便在 actionCreateactionUpdate 的每个方法中不初始化 Session.

But after creating this constructor the controller was not working and gives error. And after deleting this code my controller was working perfectly. I have written this code inside constructor to not initialize the Session in each method for actionCreate and actionUpdate.

所以我的问题是如何在 Yii 中创建构造函数?

So my question is how can we create constructor in Yii?

谢谢

推荐答案

你只是忘记调用父构造函数:

You simply forgot to call parent constructor :

public function __construct()
{
  .....
  parent::__construct();
}

你可以使用 beforeAction 而不是覆盖 __construct.

Sergey 是对的,默认情况下 Yii 将启动会话 (autoStart),你只需要使用 Yii::app()->session,例如:

And Sergey is right, by default Yii will start session (autoStart), you just have to use Yii::app()->session, e.g. :

Yii::app()->session['var'] = 'value';

相关文章