Yii2框架升级到新版本后,当我在controller里面继承init并写了一些自定义代码
public function init()
{
$someCondition = myBoolFunction();
if ($someCondition) {
return $this->redirect('my/url'));
}
}
提示错误
Call to a member function redirect() on string
翻看父类的init方法
/**
* {@inheritdoc}
* @since 2.0.36
*/
public function init()
{
parent::init();
$this->request = Instance::ensure($this->request, Request::className());
$this->response = Instance::ensure($this->response, Response::className());
}
发现init方法在Yii2.0.36版本有改动
init方法内有初始化request属性和response属性的代码
而我们使用的redirect方法,方法定义如下
public function redirect($url, $statusCode = 302)
{
// calling Url::to() here because Response::redirect() modifies route before calling Url::to()
return $this->response->redirect(Url::to($url), $statusCode);
}
正是使用了response属性,所以当我们在controller里面继承init方法后,一定不要忘了加一句
parent::init();
加上这句后,代码正常运行起来了,Yii2框架升级成功。
诸如asJson、asXml这样的方法
public function asJson($data)
{
$this->response->format = Response::FORMAT_JSON;
$this->response->data = $data;
return $this->response;
}
init方法如最开始那样写的话,框架升级后一样会报错,解决方法都可以按照本文的方法来。