ArrayableTrait提供[Arrayable]接口的实现。实现了 toArray(),数据(数组)的输出。
作用:数据转化成数组输出。
代码:
特性全部代码如下:
/**
* ArrayableTrait provides a common implementation of the [[Arrayable]] interface.
* ArrayableTrait提供[Arrayable]接口的实现。
* ArrayableTrait implements [[toArray()]] by respecting the field definitions as declared
* in [[fields()]] and [[extraFields()]].
*
* @author Qiang Xue <[email protected]>
* @since 2.0
*/
trait ArrayableTrait
{
/**
* Returns the list of fields that should be returned by default by [[toArray()]] when no specific fields are specified.
*
* A field is a named element in the returned array by [[toArray()]].
*
* This method should return an array of field names or field definitions.
* If the former, the field name will be treated as an object property name whose value will be used
* as the field value. If the latter, the array key should be the field name while the array value should be
* the corresponding field definition which can be either an object property name or a PHP callable
* returning the corresponding field value. The signature of the callable should be:
*
* ```php
* function ($model, $field) {
* // return field value
* }
* ```
*
* For example, the following code declares four fields:
*
* - `email`: the field name is the same as the property name `email`;
* - `firstName` and `lastName`: the field names are `firstName` and `lastName`, and their
* values are obtained from the `first_name` and `last_name` properties;
* - `fullName`: the field name is `fullName`. Its value is obtained by concatenating `first_name`
* and `last_name`.
*
* ```php
* return [
* 'email',
* 'firstName' => 'first_name',
* 'lastName' => 'last_name',
* 'fullName' => function () {
* return $this->first_name . ' ' . $this->last_name;
* },
* ];
* ```
*
* In this method, you may also want to return different lists of fields based on some context
* information. For example, depending on the privilege of the current application user,
* you may return different sets of visible fields or filter out some fields.
* 在这个方法中,你可能还需要返回基于一些背景场不同的列表信息。例如,根据当前的应用程序的用户的特权
* 您可能会返回不同组可见字段或过滤掉某些字段。
* The default implementation of this method returns the public object member variables indexed by themselves.
* 此方法的默认实现返回自己索引的公众对象的成员变量
* @return array the list of field names or field definitions.
* @see toArray()
*/
public function fields()
{
// 获取该对象的 public 成员变量的名列表,赋给 $fields
$fields = array_keys(Yii::getObjectVars($this));
return array_combine($fields, $fields);
}
/**
* Returns the list of fields that can be expanded further and returned by [[toArray()]].
*
* This method is similar to [[fields()]] except that the list of fields returned
* by this method are not returned by default by [[toArray()]]. Only when field names
* to be expanded are explicitly specified when calling [[toArray()]], will their values
* be exported.
*
* The default implementation returns an empty array.
*
* You may override this method to return a list of expandable fields based on some context information
* (e.g. the current application user).
*
* @return array the list of expandable field names or field definitions. Please refer
* to [[fields()]] on the format of the return value.
* @see toArray()
* @see fields()
*/
public function extraFields()
{
return [];
}
/**
* Converts the model into an array.
* 该模型转换成一个数组。
* This method will first identify which fields to be included in the resulting array by calling [[resolveFields()]].
* It will then turn the model into an array with these fields. If `$recursive` is true,
* any embedded objects will also be converted into arrays.
* When embeded objects are [[Arrayable]], their respective nested fields will be extracted and passed to [[toArray()]].
* 如果模型实现了[可链接]界面,由此产生的阵列也将有一个`link`元素,它由接口指定指链接列表。
* If the model implements the [[Linkable]] interface, the resulting array will also have a `_link` element
* which refers to a list of links as specified by the interface.
*
* @param array $fields the fields being requested.
* If empty or if it contains '*', all fields as specified by [[fields()]] will be returned.
* Fields can be nested, separated with dots (.). e.g.: item.field.sub-field
* `$recursive` must be true for nested fields to be extracted. If `$recursive` is false, only the root fields will be extracted.
* @param array $expand the additional fields being requested for exporting. Only fields declared in [[extraFields()]]
* will be considered.
* Expand can also be nested, separated with dots (.). e.g.: item.expand1.expand2
* `$recursive` must be true for nested expands to be extracted. If `$recursive` is false, only the root expands will be extracted.
* @param bool $recursive whether to recursively return array representation of embedded objects.
* @return array the array representation of the object
*/
public function toArray(array $fields = [], array $expand = [], $recursive = true)
{
$data = [];
foreach ($this->resolveFields($fields, $expand) as $field => $definition) {
//如果是字符串,则返回该类的属性
//如果是函数,则返回该类的方法的回调值
$attribute = is_string($definition) ? $this->$definition : $definition($this, $field);
//递归,获取所有子元素
if ($recursive) {
//提取子元素
$nestedFields = $this->extractFieldsFor($fields, $field);
$nestedExpand = $this->extractFieldsFor($expand, $field);
if ($attribute instanceof Arrayable) {
$attribute = $attribute->toArray($nestedFields, $nestedExpand);
} elseif (is_array($attribute)) {
$attribute = array_map(
function ($item) use ($nestedFields, $nestedExpand) {
if ($item instanceof Arrayable) {
return $item->toArray($nestedFields, $nestedExpand);
}
return $item;
},
$attribute
);
}
}
$data[$field] = $attribute;
}
if ($this instanceof Linkable) {
$data['_links'] = Link::serialize($this->getLinks());
}
return $recursive ? ArrayHelper::toArray($data) : $data;
}
/**
* Extracts the root field names from nested fields.
* 从嵌套的字段中提取根字段
* Nested fields are separated with dots (.). e.g: "item.id"
* The previous example would extract "item".
*
* @param array $fields The fields requested for extraction
* @return array root fields extracted from the given nested fields
* @since 2.0.14
*/
protected function extractRootFields(array $fields)
{
$result = [];
foreach ($fields as $field) {
$result[] = current(explode('.', $field, 2));
}
if (in_array('*', $result, true)) {
$result = [];
}
return array_unique($result);
}
/**
* Extract nested fields from a fields collection for a given root field
* 从给定根字段的字段集合中提取嵌套字段
* Nested fields are separated(分开的) with dots (.). e.g: "item.id"
* The previous example would extract "id".
*
* @param array $fields The fields requested for extraction
* @param string $rootField The root field for which we want to extract the nested fields
* @return array nested fields extracted for the given field
* @since 2.0.14
*/
protected function extractFieldsFor(array $fields, $rootField)
{
$result = [];
foreach ($fields as $field) {
if (0 === strpos($field, "{$rootField}.")) {
$result[] = preg_replace('/^' . preg_quote($rootField, '/') . '\./i', '', $field);
}
}
return array_unique($result);
}
/**
* Determines which fields can be returned by [[toArray()]].
* 决定哪些 fields 会通过 toArray() 返回
* This method will first extract the root fields from the given fields.
* Then it will check the requested root fields against those declared in [[fields()]] and [[extraFields()]]
* to determine which fields can be returned.
* 此方法将检查对那些在[[fields()],并宣布必填字段[extraFields()]] 以确定哪些领域可以退换。
* @param array $fields the fields being requested for exporting
* @param array $expand the additional fields being requested for exporting
* @return array the list of fields to be exported. The array keys are the field names, and the array values
* are the corresponding object property names or PHP callables returning the field values.
*/
protected function resolveFields(array $fields, array $expand)
{
$fields = $this->extractRootFields($fields);
$expand = $this->extractRootFields($expand);
$result = [];
foreach ($this->fields() as $field => $definition) {
if (is_int($field)) {
$field = $definition;
}
//将我们传进来的定义的数组的值 赋值 给要输出的数组($this->>fields()返回值)
if (empty($fields) || in_array($field, $fields, true)) {
// 如果 $fields 为空, 或者 $field 在 $fields 中, 就将 $definition 赋到 $result 中
// 即 $fields 为空,就将所有的对象的属性都放入到结果中
// 不为空时,如果当前对象的属性在 $fields 中存在, 就将对象中定义的该属性的值放入到结果中
$result[$field] = $definition; //替换数组的值
}
}
//如果没有扩展数组,直接返回
if (empty($expand)) {
return $result;
}
//需要返回扩展数组时,仅仅只有定义过 extraFields 数组,才会返回扩展字段
foreach ($this->extraFields() as $field => $definition) {
if (is_int($field)) {
$field = $definition;
}
//将传进来的数组的值,赋值给定义的扩展数组
if (in_array($field, $expand, true)) {
// 如果$field 在 $expand 中, 就将 $definition 赋到 $result 中
// 即当前对象的扩展属性在 $fields 中存在, 就将对象中定义的该扩展属性的值放入到结果中
$result[$field] = $definition;//替换数组的值
}
}
return $result;
}
}
应用:
在YII2中 Model 类中,主要用到了ArrayableTrait该类。
Model类中重写了方法:fields, 在Model 中输出的数组元素为表的字段。
public function fields()
{
$fields = $this->attributes();
return array_combine($fields, $fields);
}
BaseActiveRecord 类继承的是Model类,类中重写了方法 fields() 和 extraFields()
/**
* {@inheritdoc}
*
* The default implementation returns the names of the columns whose values have been populated into this record.
*/
public function fields()
{
$fields = array_keys($this->_attributes);
return array_combine($fields, $fields);
}
/**
* {@inheritdoc}
*
* The default implementation returns the names of the relations that have been populated into this record.
*/
public function extraFields()
{
$fields = array_keys($this->getRelatedRecords());
return array_combine($fields, $fields);
}
用法:
输出的基本字段,是通过重写方法 fields() 得到的,扩展字段通过重写方法 extraFields() 得到的,不管是基本字段,还是扩展字段,都看成是要输出的字段就可以了。字段的元素的值可以是字符串,或者 回调函数。
- 数组元素的值是字符串,最后会解析 $this->xxxx,也就是说取的是类的属性。
说明:Yii中属性,有多种方式:类的pulic属性;getter()方法;等
这样在AR类中,关联的ActiveRecord中,使用 hasOne,hasMany的一系列 getter()读取器方法,就都可以被使用,这样就可以获取关联表的数据了。
- 数组元素的值是回调函数,最后解析 function($this, $field) {…}, 也就是说取的是回调函数的返回值,回调函数的参数是,当前对象,和要取的元素的字段名。
实战举例:
- 应用1:返回2个关联表的数据
控制器代码
$account = AccountAR::findOne($account_id);
$arr = $account->toArray([], ['payConfig', 'myExtraFieldsCall']);
toArray() 方法就拿到了 AccountAR对象的所有属性,和 扩展字段 extraFields
账户 account 的 AR 中的代码
public static $statusEnum = [
1 => '待跟进',
2 => '跟进中',
3 => '已签约',
4 => '已过期',
5 => '已作废',
6 => '已删除',
];
public $params;
public function rules()
{
$rules = parent::rules();
// 状态边界,枚举值,可以传文本或者对应的数字
$rules[] = [['agreement_status',], 'in', 'range' => function () {
return static::$statusEnum + array_flip(self::$statusEnum);
}];
return $rules;
}
//输出的扩展字段
public function extraFields()
{
//调用该类中的对应的getter 回调方法
//说明:这里最好 parent::extraFields()获取到的数组 后,然后在拼接我们要获取的字段
return parent::extraFields() + ['payConfig','myExtraFieldsCall'] + ['myCallbackField' => function(){
return $this->params ?? []; //所有类中的方法,都是可以直接使用$this的,调用类的属性
}];
}
//关联表ar_config (account.id = ar_config.account_id)
public function getPayConfig()
{
return $this->hasOne(ArConfigAR::class, ['account_id'=>'id']);
}
public function getMyExtraFieldsCall()
{
//扩展字段的回调函数
}
toArray输出结果:
array:25 [▼
"agreement_id" => 102
"project_id" => "39e60452-fa50-e8b4-9549-ccf683e02eaa"
"ar_account_id" => 0
"agreement_status" => "已作废"
"agreement_type" => "本地旅行社"
"company_name" => "事业单位17"
"company_code" => "12345678"
"company_type" => 1
"bank_card_number" => "888888888888888888"
"bank_name" => "世界银行"
"contract_no" => ""
"contract_limited_start" => null
"contract_limited_end" => null
"contract_channel" => ""
"contract_brokerage" => ""
"contract_brokerage_type" => 1
"contract_brokerage_cash" => "0.0000"
"contract_brokerage_rate" => "0.0000"
"is_auto_expire" => 0
"contract_original_url" => ""
"assign_code" => "2SKTL43P"
"is_show_terminal_memo" => 1
"created_at" => "2018-05-04 11:02:29"
"updated_at" => "2018-05-04 11:03:06"
//扩展字段(关联的模型,本身就是arrayAble的实例,底层方法里面递归处理toArray,最后关联的模型对象也会将模型的对象数据数组化输出)
"payConfig" => array:1 [▼
"id" => 161
"agreement_id" => 102
"sex" => "男"
"name" => "任我行"
"title" => "总裁"
"contact_information" => "18503005497"
"country" => "中国"
"certificate_type" => "身份证"
"certificate_no" => "429004199003041234"
"nation" => "汉族"
"is_delete" => 0
]
]
说明
-
说明1: extraFields 方法中先调用父类的方法extraFields后得到的数组1,然后合并我们自定的字段数组2,2数组合并返回。写法:parent::extraFields() + [其他的字段]
-
说明2: 灵活使用枚举值类型:array_flip函数的巧用
-
说明3:关联的模型(AR类,或者 对应的MODEL类),本身就是继承了arrayAble类,toArray方法里面递归处理,最后将关联的模型(对象)的属性数组化输出