1. 程式人生 > >PHP實現Collection數據集類及其原理

PHP實現Collection數據集類及其原理

php

PHP 語言最重要的特性之一便是數組了(特別是關聯數組)。
PHP 為此也提供不少的函數和類接口方便於數組操作,但沒有一個集大成的類專門用來操作數組。

如果數組操作不多的話,個別函數用起來會比較靈活,開銷也小。
但是,如果經常操作數組,尤其是對數組進行各種操作如排序、入棧、出隊列、翻轉、叠代等,系統函數用起來可能就沒有那麽優雅了。

下面已實現的一個 Collection 類(數據集對象),來自 ThinkPHP5.0 的基礎類 Collection,就是一個集大成的類。


1、 Collection源碼

源碼確實不錯,也不是特別長,就全貼上了,方便閱讀。跳到下面的 例子 結合看會比較好理解。

namespace think;use ArrayAccess;use ArrayIterator;use Countable;use IteratorAggregate;use JsonSerializable;class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSerializable{    protected $items = [];

    public function __construct($items = [])
    {        $this->items = $this->convertToArray($items);
    }    public static function make($items = [])
    {        return new static($items);
    }    public function isEmpty()
    {        return empty($this->items);
    }    public function toArray()
    {        return array_map(function ($value) {            return ($value instanceof Model || $value instanceof self) ? $value->toArray() : $value;
        }, $this->items);
    }    public function all()
    {        return $this->items;
    }    public function merge($items)
    {        return new static(array_merge($this->items, $this->convertToArray($items)));
    }    /**     * 比較數組,返回差集     */
    public function diff($items)
    {        return new static(array_diff($this->items, $this->convertToArray($items)));
    }    /**     * 交換數組中的鍵和值     */
    public function flip()
    {        return new static(array_flip($this->items));
    }    /**     * 比較數組,返回交集     */
    public function intersect($items)
    {        return new static(array_intersect($this->items, $this->convertToArray($items)));
    }    public function keys()
    {        return new static(array_keys($this->items));
    }    /**     * 刪除數組的最後一個元素(出棧)     */
    public function pop()
    {        return array_pop($this->items);
    }    /**     * 通過使用用戶自定義函數,以字符串返回數組     *     * @param  callable $callback     * @param  mixed    $initial     * @return mixed     */
    public function reduce(callable $callback, $initial = null)
    {        return array_reduce($this->items, $callback, $initial);
    }    /**     * 以相反的順序返回數組。     */
    public function reverse()
    {        return new static(array_reverse($this->items));
    }    /**     * 刪除數組中首個元素,並返回被刪除元素的值     */
    public function shift()
    {        return array_shift($this->items);
    }    /**     * 把一個數組分割為新的數組塊.     */
    public function chunk($size, $preserveKeys = false)
    {        $chunks = [];
        foreach (array_chunk($this->items, $size, $preserveKeys) as $chunk) {            $chunks[] = new static($chunk);
        }        return new static($chunks);
    }    /**     * 在數組開頭插入一個元素     */
    public function unshift($value, $key = null)
    {        if (is_null($key)) {            array_unshift($this->items, $value);
        } else {            $this->items = [$key => $value] + $this->items;
        }
    }    /**     * 給每個元素執行個回調     */
    public function each(callable $callback)
    {        foreach ($this->items as $key => $item) {            if ($callback($item, $key) === false) {                break;
            }
        }        return $this;
    }    /**     * 用回調函數過濾數組中的元素     */
    public function filter(callable $callback = null)
    {        if ($callback) {            return new static(array_filter($this->items, $callback));
        }        return new static(array_filter($this->items));
    }    /**     * 返回數組中指定的一列     */
    public function column($column_key, $index_key = null)
    {        if (function_exists(‘array_column‘)) {            return array_column($this->items, $column_key, $index_key);
        }        $result = [];
        foreach ($this->items as $row) {            $key    = $value    = null;
            $keySet = $valueSet = false;
            if (null !== $index_key && array_key_exists($index_key, $row)) {                $keySet = true;
                $key    = (string) $row[$index_key];
            }            if (null === $column_key) {                $valueSet = true;
                $value    = $row;
            } elseif (is_array($row) && array_key_exists($column_key, $row)) {                $valueSet = true;
                $value    = $row[$column_key];
            }            if ($valueSet) {                if ($keySet) {                    $result[$key] = $value;
                } else {                    $result[] = $value;
                }
            }
        }        return $result;
    }    /**     * 對數組排序     */
    public function sort(callable $callback = null)
    {        $items = $this->items;
        $callback ? uasort($items, $callback) : uasort($items, function ($a, $b) {            if ($a == $b) {                return 0;
            }            return ($a < $b) ? -1 : 1;
        });
        return new static($items);
    }    /**     * 將數組打亂     */
    public function shuffle()
    {        $items = $this->items;
        shuffle($items);
        return new static($items);
    }    /**     * 截取數組     */
    public function slice($offset, $length = null, $preserveKeys = false)
    {        return new static(array_slice($this->items, $offset, $length, $preserveKeys));
    }    // ArrayAccess
    public function offsetExists($offset)
    {        return array_key_exists($offset, $this->items);
    }    public function offsetGet($offset)
    {        return $this->items[$offset];
    }    public function offsetSet($offset, $value)
    {        if (is_null($offset)) {            $this->items[] = $value;
        } else {            $this->items[$offset] = $value;
        }
    }    public function offsetUnset($offset)
    {        unset($this->items[$offset]);
    }    //Countable
    public function count()
    {        return count($this->items);
    }    //IteratorAggregate
    public function getIterator()
    {        return new ArrayIterator($this->items);
    }    //JsonSerializable
    public function jsonSerialize()
    {        return $this->toArray();
    }    /**     * 轉換當前數據集為JSON字符串     */
    public function toJson($options = JSON_UNESCAPED_UNICODE)
    {        return json_encode($this->toArray(), $options);
    }    public function __toString()
    {        return $this->toJson();
    }    /**     * 轉換成數組     */
    protected function convertToArray($items)
    {        if ($items instanceof self) {            return $items->all();
        }        return (array) $items;
    }
}


2、 講解與例子

給出了例子有前後的關系,所以要結合所有例子來看。
Collection 的原理其實都是對 PHP 內置的函數和 SPL 的應用,如果要更加深入,看官方文檔也是一個不錯的選擇。


ArrayAccess的使用

Collection 既然是個類,那要怎麽才能像數組那樣便利的操作呢?如 $a[‘key‘] 。
答案是:繼承接口類 ArrayAccess,並實現該類的幾個接口,如下:

abstract public boolean offsetExists ( mixed $offset ) //判斷key即$offset的數組元素是否存在,相當於 isset($a[$offset])abstract public mixed offsetGet ( mixed $offset ) //數組元素獲取,相當於 $value = $a[$offset]abstract public void offsetSet ( mixed $offset , mixed $value ) //數組元素設置 相當於 $a[$offset] = $valueabstract public void offsetUnset ( mixed $offset ) //刪除數組元素,相當於 unset($a[$offset]);

現在回頭看看 Collection 的源碼是怎麽實現的。
如何使用,來個例子:

use think;$c = new Collection;$c[‘a‘] = ‘hello a‘;$c[‘b‘] = ‘you are b‘;echo $c[‘a‘] . ‘<br/>‘;echo $c[‘b‘] . ‘<br/>‘;foreach ($c as $k => $v) {    echo "key: $k, val: $v <br/>";}

結果輸出:

hello a
you are bkey: a, val: hello akey: b, val: you are b


JsonSerializable的使用

如果對一個對象進行 json 編碼的話,其實就是對該對象的 public 屬性進行 json 化,那如何定制 json 化的內容和輸出呢?
答案是:繼承 JsonSerializable 接口類,並實現類中的接口:

abstract public mixed jsonSerialize ( void ) //定制json化的字符串輸出

現在回頭看看 Collection 的源碼是怎麽實現的。
如何使用,來個例子:

echo json_encode($c) . ‘<br/>‘;

結果輸出:

{"a":"hello a","b":"you are b"}


Countable的使用

如果對一個對象進行 count() 操作的話,其實就是統計該對象的 public 屬性的總數,那如何定制 count() 呢?
答案是:繼承 Countable 接口類,並實現類中的接口:

abstract public int count ( void )

現在回頭看看 Collection 的源碼是怎麽實現的。
如何使用,來個例子:

echo ‘count: ‘ . $c->count() . ‘<br/>‘;// 或者echo ‘count: ‘ . count($c) . ‘<br/>‘;

結果輸出:

count: 2count: 2


IteratorAggregate、ArrayIterator的使用

如何實現叠代器的功能?如可進行 foreach 操作,提供叠代相關的函數等。
答案是:繼承接口類 IteratorAggregate (聚合式叠代器),並實現類中的接口:

abstract public Traversable getIterator ( void )

如何實現該接口,調用生成一個 ArrayIterator 類,該類可提供叠代器的所有功能。
現在回頭看看 Collection 的源碼是怎麽實現的。
如何使用,來個例子:

$c[‘c‘] = ‘not just c‘;$iter = $c->getIterator(); //獲取叠代器// 可方便地使用foreach操作foreach ($iter as $k => $v) {    echo "key: $k, val: $v <br/>";}echo ‘count: ‘ . $iter->count() . ‘<br/>‘; // 當前數組元素個數$iter->rewind(); // 數組位置復位echo ‘current: ‘ . $iter->current() . ‘<br/>‘; // 當前位置數組元素的值

結果輸出:

key: a, val: hello a 
key: b, val: you are b 
key: c, val: not just c 
count: 3current: hello a


內置函數的使用

功能操作的一般使用內置函數,PHP 提供的內置函數功能已經很強大了,只需要簡單地封裝成一個類方法即可,函數其實使用不難,忘記怎麽使用了去官網溜溜吧。

有些是為了兼容 PHP 低版本,所以還要另外實現一遍,如:

/** * 返回數組中指定的一列 */public function column($column_key, $index_key = null)

內置的 array_column() 需要 PHP5.5及以上版本才支持,而Collection類的應用目標是5.4及以上能使用,所以勉為其難地再實現了一遍。


PHP實現Collection數據集類及其原理