1.首先,得先了解services,services是一个单例模式(不明白什么是单例模式自行查询)
譬如:Yii::$service->helper
,对应的class是:https://github.com/fecshop/yii2_fecshop/blob/master/services/Helper.php
第一次执行的时候,这个class就会实例化对象,第二次访问Yii::$service->helper
,就不会实例化对象了,
因此每次执行 Yii::$service->helper
,对应的都是同一个对象,这也就是单例模式
,yii2 service的单例模式的实现参看:
http://www.fecshop.com/doc/fecshop-guide/develop/cn-1.0/guide-fecshop-service-abc.html#3
2.通过上面可以了解, Yii::$service->helper->errors
是单例模式,每次访问都是同一个对象(无论我在任何地方执行)
也就是类文件:https://github.com/fecshop/yii2_fecshop/blob/master/services/helper/Errors.php
那么我就可以通过Yii::$service->helper->errors->add('$attribute is empty or is not array');
, 将错误信息通过这个函数,写到对象变量中
/**
* 添加一条错误信息
* @param string $errors 错误信息,支持模板格式
* @param array $arr 错误信息模板中变量替换对应的数组
* Yii::$service->helper->errors->add('Hello, {username}!', ['username' => $username])
*/
public function add($errors, $arr = [])
{
if ($errors) {
$errors = Yii::$service->page->translate->__($errors, $arr);
$this->_errors[] = $errors;
}
}
也就是 $this->_errors
,因为这个是一个数组,那么我每次调用Yii::$service->helper->errors->add('')
,就会往这个对象变量数组$this->_errors
中添加数据
3.然后我就可以从这个对象变量中取出来数据了
public function get($separator = false)
{
if ($errors = $this->_errors) {
$this->_errors = false;
if (is_array($errors) && !empty($errors)) {
if ($separator) {
if ($separator === true) {
$separator = '|';
}
return implode($separator, $errors);
} else {
return $errors;
}
}
}
return false;
}
}
fecshop errors的设置为error只能取出来一次,取出来后就清空$this->_errors
,所以你会看到代码
$this->_errors = false;