PHP 依賴注入容器 Pimple 筆記

M1racle發表於2017-03-28

本文同步發表自:https://www.h57.pw/article/42

其實,想寫 laravel 的 container 的筆記的,可是,自己看了許久,也沒有很好的理解,理解到的部分也是很片面的東西,不過 laravel 的 container 真的很強大,要比今天寫的這個強大的多,不過強大的帶來的問題,就是可能會慢,畢竟用到了反射,今天這個 Pimple 則相對簡單的多了,沒有那麼多複雜的東西,用起來也很順手而且比較容易理解,所以今天就用這個做筆記了。

原本想分段做這個的筆記的,後來覺得應該吧知識點拆分開說明,然後再用整體程式碼在裡面做註釋的方式來解釋這段更好一些,於是乎,準備開整。

class Container implements \ArrayAccess

這個類實現了 ArrayAccess 介面,ArrayAccess 是個什麼東西了,大家首先看一下 PHP 官網的手冊 http://php.net/manual/zh/class.arrayaccess... 好吧,我就簡單說一句,就是讓物件能夠像陣列一樣操作了。具體需要實現的幾個介面,大家看一下手冊吧,我覺得我的說明肯定沒有手冊寫得好,我更多理解的東西,會在程式碼註釋中寫一下。

public function __construct(array $values = array())
    {
        $this->factories = new \SplObjectStorage();
        $this->protected = new \SplObjectStorage();

        foreach ($values as $key => $value) {
            $this->offsetSet($key, $value);
        }
    }

在構造方法中又出現了 SplObjectStorage 類,那麼這個 SplObjectStorage 是個什麼東西呢,我們再去看一下手冊 http://php.net/manual/zh/class.splobjectst... 這個在手冊中可惜翻譯的不完全(根本沒有翻譯),所以我就簡單的說說,這個類其實是實現了 Countable , Iterator , Serializable , ArrayAccess 這4個介面,這4個介面大家也可以看一下手冊,看完了就知道這個類是幹什麼的了,我再來拆分說下 Countable 就是讓一個類可以用一個計數器, Iterator 就是可以用 foreach 這些去迴圈,Serializable 就是可以序列化,ArrayAccess 上面說過了就不多說了。其實剛開始很難理解這個類,不過多看看手冊,別人的示例程式碼,自己在多寫一些可能就瞭解了。這個如何理解我也說不太好。大家見諒。

好吧,我覺得是額外知識點的就上面那些,等多的筆記我將在下面的程式碼註釋中說明白,大家可以看看,順便幫忙指正。

<?php

/*
 * This file is part of Pimple.
 *
 * Copyright (c) 2009 Fabien Potencier
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is furnished
 * to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

namespace Pimple;

/**
 * Container main class.
 *
 * @author  Fabien Potencier
 */
class Container implements \ArrayAccess
{
    private $values = array(); // 儲存 value 的陣列
    private $factories; // 儲存工廠方法的物件
    private $protected; // 儲存保護方法的物件
    private $frozen = array(); // 儲存凍結的陣列,也就是在這個陣列裡面的 key 的 value 是不可更改的了
    private $raw = array(); // 儲存
    private $keys = array(); // 儲存 key 的陣列

    /**
     * Instantiate the container.
     *
     * Objects and parameters can be passed as argument to the constructor.
     *
     * @param array $values The parameters or objects.
     */
    public function __construct(array $values = array())
    {
        // 構造工廠物件以及保護方法物件
        $this->factories = new \SplObjectStorage();
        $this->protected = new \SplObjectStorage();
        // 把初始化的值存放到現有的裡面
        foreach ($values as $key => $value) {
            $this->offsetSet($key, $value);
        }
    }

    /**
     * Sets a parameter or an object.
     *
     * Objects must be defined as Closures.
     *
     * Allowing any PHP callable leads to difficult to debug problems
     * as function names (strings) are callable (creating a function with
     * the same name as an existing parameter would break your container).
     *
     * @param string $id    The unique identifier for the parameter or object
     * @param mixed  $value The value of the parameter or a closure to define an object
     *
     * @throws \RuntimeException Prevent override of a frozen service
     * 設定相關值以及物件
     */
    public function offsetSet($id, $value)
    {
        // 如果這個值被 frozen 了,就不允許更改了
        // 應該是為了保持高效性,會把 get 過的值儲存起來,所以就不在呼叫了也就不允許更改了
        // 其實也可以更改,在下面的方法中說明
        if (isset($this->frozen[$id])) {
            throw new \RuntimeException(sprintf('Cannot override frozen service "%s".', $id));
        }
        // 儲存值方法
        $this->values[$id] = $value;
        // 儲存 key 的值
        $this->keys[$id] = true;
    }

    /**
     * Gets a parameter or an object.
     *
     * @param string $id The unique identifier for the parameter or object
     *
     * @return mixed The value of the parameter or an object
     *
     * @throws \InvalidArgumentException if the identifier is not defined
     * 獲取值得方法
     */
    public function offsetGet($id)
    {
        // 如果沒有設定 key 則丟擲異常
        if (!isset($this->keys[$id])) {
            throw new \InvalidArgumentException(sprintf('Identifier "%s" is not defined.', $id));
        }

        // 如果 raw 裡面已經有了, 或者 values 裡面儲存對應 key 的值不是個 obj,或者 protected 裡面也有對應的值 或者值裡面的方法存在,則直接返回,values 陣列裡面的結果
        if (
            isset($this->raw[$id])
            || !is_object($this->values[$id])
            || isset($this->protected[$this->values[$id]])
            || !method_exists($this->values[$id], '__invoke')
        ) {
            return $this->values[$id];
        }

        // 如果工廠方法裡面設定了相關方法則要直接返回
        if (isset($this->factories[$this->values[$id]])) {
            return $this->values[$id]($this);
        }

        // 獲取值裡面的方法
        $raw = $this->values[$id];
        // 執行上面獲取到的方法獲取返回值 並且覆蓋 values
        $val = $this->values[$id] = $raw($this);
        // 把原始方法儲存到 raw 陣列裡面,用來給 raw 方法呼叫
        $this->raw[$id] = $raw;
        // 把這個值設定為凍結,不允許將來的更改
        $this->frozen[$id] = true;
        // 返回結果值
        return $val;
    }

    /**
     * Checks if a parameter or an object is set.
     *
     * @param string $id The unique identifier for the parameter or object
     *
     * @return bool
     * 獲取 key 是否存在
     */
    public function offsetExists($id)
    {
        return isset($this->keys[$id]);
    }

    /**
     * Unsets a parameter or an object.
     *
     * @param string $id The unique identifier for the parameter or object
     * 刪除掉 key
     */
    public function offsetUnset($id)
    {
        // 如果存在則刪除相關的值
        if (isset($this->keys[$id])) {
            // 如果儲存的是個物件,則刪除相關的值
            if (is_object($this->values[$id])) {
                unset($this->factories[$this->values[$id]], $this->protected[$this->values[$id]]);
            }
            // 刪除普通陣列裡面的值
            unset($this->values[$id], $this->frozen[$id], $this->raw[$id], $this->keys[$id]);
        }
    }

    /**
     * Marks a callable as being a factory service.
     *
     * @param callable $callable A service definition to be used as a factory
     *
     * @return callable The passed callable
     *
     * @throws \InvalidArgumentException Service definition has to be a closure of an invokable object
     * 設定工廠方法
     */
    public function factory($callable)
    {
        if (!method_exists($callable, '__invoke')) {
            throw new \InvalidArgumentException('Service definition is not a Closure or invokable object.');
        }

        $this->factories->attach($callable);

        return $callable;
    }

    /**
     * Protects a callable from being interpreted as a service.
     *
     * This is useful when you want to store a callable as a parameter.
     *
     * @param callable $callable A callable to protect from being evaluated
     *
     * @return callable The passed callable
     *
     * @throws \InvalidArgumentException Service definition has to be a closure of an invokable object
     */
    public function protect($callable)
    {
        if (!method_exists($callable, '__invoke')) {
            throw new \InvalidArgumentException('Callable is not a Closure or invokable object.');
        }

        $this->protected->attach($callable);

        return $callable;
    }

    /**
     * Gets a parameter or the closure defining an object.
     *
     * @param string $id The unique identifier for the parameter or object
     *
     * @return mixed The value of the parameter or the closure defining an object
     *
     * @throws \InvalidArgumentException if the identifier is not defined
     * 其實這個就是獲取設定的物件或者方法
     */
    public function raw($id)
    {
        if (!isset($this->keys[$id])) {
            throw new \InvalidArgumentException(sprintf('Identifier "%s" is not defined.', $id));
        }
        if (isset($this->raw[$id])) {
            return $this->raw[$id];
        }

        return $this->values[$id];
    }

    /**
     * Extends an object definition.
     *
     * Useful when you want to extend an existing object definition,
     * without necessarily loading that object.
     *
     * @param string   $id       The unique identifier for the object
     * @param callable $callable A service definition to extend the original
     *
     * @return callable The wrapped callable
     *
     * @throws \InvalidArgumentException if the identifier is not defined or not a service definition
     * 修改已經存在的值
     */
    public function extend($id, $callable)
    {
        if (!isset($this->keys[$id])) {
            throw new \InvalidArgumentException(sprintf('Identifier "%s" is not defined.', $id));
        }

        if (!is_object($this->values[$id]) || !method_exists($this->values[$id], '__invoke')) {
            throw new \InvalidArgumentException(sprintf('Identifier "%s" does not contain an object definition.', $id));
        }

        if (!is_object($callable) || !method_exists($callable, '__invoke')) {
            throw new \InvalidArgumentException('Extension service definition is not a Closure or invokable object.');
        }

        $factory = $this->values[$id];

        $extended = function ($c) use ($callable, $factory) {
            return $callable($factory($c), $c);
        };

        if (isset($this->factories[$factory])) {
            $this->factories->detach($factory);
            $this->factories->attach($extended);
        }

        return $this[$id] = $extended;
    }

    /**
     * Returns all defined value names.
     *
     * @return array An array of value names
     * 獲取所有的 key
     */
    public function keys()
    {
        return array_keys($this->values);
    }

    /**
     * Registers a service provider.
     *
     * @param ServiceProviderInterface $provider A ServiceProviderInterface instance
     * @param array                    $values   An array of values that customizes the provider
     *
     * @return static
     * 註冊自己的服務用的,後續文章體現
     */
    public function register(ServiceProviderInterface $provider, array $values = array())
    {
        $provider->register($this);

        foreach ($values as $key => $value) {
            $this[$key] = $value;
        }

        return $this;
    }
}

好吧,上面註釋的都已經寫出來了,個人覺得很簡單,但是有幾個方法我覺得可以擴充套件開來說,可能在過幾天的文章裡面展開來說說,基本上就是 register、extend和 raw 這幾個方法的具體說明了。

哦對了,開始我覺得 factory 和 protect 方法差不多,其實還是有區別的,就是 factory 會有一個 $container 的引數,protect 方法就是儲存的普通方法,區別就這麼簡單了。不過更多的方法,也會在後續文章說明的。

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章