ArrayableTrait提供[Arrayable]接口的實現。實現了 toArray(),數據(數組)的輸出。

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() 得到的,不管是基本字段,還是擴展字段,都看成是要輸出的字段就可以了。字段的元素的值可以是字符串,或者 回調函數。

  1. 數組元素的值是字符串,最後會解析 $this->xxxx,也就是說取的是類的屬性。

說明:Yii中屬性,有多種方式:類的pulic屬性;getter()方法;等
這樣在AR類中,關聯的ActiveRecord中,使用 hasOne,hasMany的一系列 getter()讀取器方法,就都可以被使用,這樣就可以獲取關聯表的數據了。

  1. 數組元素的值是回調函數,最後解析 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方法裏面遞歸處理,最後將關聯的模型(對象)的屬性數組化輸出

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章