在 Yii 的控制器中创建构造函数方法 [英] Create constructor method in controller in Yii

查看:21
本文介绍了在 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';

这篇关于在 Yii 的控制器中创建构造函数方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆