专栏名称: SegmentFault思否
SegmentFault (www.sf.gg)开发者社区,是中国年轻开发者喜爱的极客社区,我们为开发者提供最纯粹的技术交流和分享平台。
目录
相关文章推荐
程序员的那些事  ·  快!快!快!DeepSeek 满血版真是快 ·  昨天  
码农翻身  ·  漫画 | 为什么大家都愿意进入外企? ·  昨天  
程序员的那些事  ·  清华大学:DeepSeek + ... ·  3 天前  
OSC开源社区  ·  升级到Svelte ... ·  5 天前  
51好读  ›  专栏  ›  SegmentFault思否

PHP容器——Pimple运行流程浅析

SegmentFault思否  · 公众号  · 程序员  · 2018-02-06 08:00

正文

需要具备的知识点

闭包

闭包和匿名函数在PHP5.3.0中引入的。

闭包是指:创建时封装周围状态的函数。即使闭包所处的环境不存在了,闭包中封装的状态依然存在。

理论上,闭包和匿名函数是不同的概念。但是PHP将其视作相同概念。 实际上,闭包和匿名函数是伪装成函数的对象。他们是Closure类的实例。

闭包和字符串、整数一样,是一等值类型。

创建闭包:

  1. $closure = function ($name) {

  2.    return 'Hello ' . $name;

  3. };

  4. echo $closure('nesfo');//Hello nesfo

  5. var_dump(method_exists($closure, '__invoke'));//true

我们之所以能调用 $closure 变量,是因为这个变量的值是一个闭包,而且闭包对象实现了 __invoke() 魔术方法。只要变量名后有 () ,PHP就会查找并调用 __invoke() 方法。

通常会把PHP闭包当作函数的回调使用。

array_map() , preg_replace_callback() 方法都会用到回调函数,这是使用闭包的最佳时机!

举个例子:

  1. $numbersPlusOne = array_map(function ($number) {

  2.    return $number + 1;

  3. }, [1, 2, 3]);

  4. print_r($numbersPlusOne);

得到结果:

  1. [ 2, 3, 4]

在闭包出现之前,只能单独创建具名函数,然后使用名称引用那个函数。这么做,代码执行会稍微慢点,而且把回调的实现和使用场景隔离了。

  1. function incrementNum ($number) {

  2.    return $number + 1;

  3. }

  4. $numbersPlusOne = array_map('incrementNum', [1, 2, 3]);

  5. print_r($numbersPlusOne);

SPL

ArrayAccess

实现ArrayAccess接口,可以使得object像array那样操作。ArrayAccess接口包含四个必须实现的方法:

  1. interface ArrayAccess {

  2.    //检查一个偏移位置是否存在

  3.    public mixed offsetExists ( mixed $offset  );

  4.    //获取一个偏移位置的值

  5.    public mixed offsetGet( mixed $offset  );

  6.    //设置一个偏移位置的值

  7.    public mixed offsetSet ( mixed $offset  );

  8.    //复位一个偏移位置的值

  9.    public mixed offsetUnset  ( mixed $offset  );

  10. }

SplObjectStorage

SplObjectStorage类实现了以对象为键的映射(map)或对象的集合(如果忽略作为键的对象所对应的数据)这种数据结构。这个类的实例很像一个数组,但是它所存放的对象都是唯一。该类的另一个特点是,可以直接从中删除指定的对象,而不需要遍历或搜索整个集合。

::class 语法

因为 ::class 表示是字符串。用 ::class 的好处在于 IDE 里面可以直接改名一个 class,然后 IDE 自动处理相关引用。

同时,PHP 执行相关代码时,是不会先加载相关 class 的。

同理,代码自动化检查 inspect 也可以正确识别 class。

Pimple 容器流程浅析

Pimpl是php社区中比较流行的容器。代码不是很多,详见https://github.com/silexphp/Pimple/blob/master/src/Pimple/Container.php。

我们的应用可以基于Pimple开发:

  1. namespace EasyWeChat\Foundation;

  2. use Pimple\Container;

  3. class Application extends Container

  4. {

  5.    /**

  6.     * Service Providers.

  7.     *

  8.     * @var array

  9.     */

  10.    protected $providers = [

  11.        ServiceProviders\ServerServiceProvider::class,

  12.        ServiceProviders\UserServiceProvider::class

  13.    ];

  14.    /**

  15.     * Application constructor.

  16.     *

  17.     * @param array $config

  18.     */

  19.    public function __construct($config)

  20.    {

  21.        parent::__construct();

  22.        $this['config'] = function () use ($config) {

  23.            return new Config($config);

  24.        };

  25.        if ($this['config']['debug']) {

  26.            error_reporting(E_ALL);

  27.        }

  28.        $this->registerProviders();

  29.    }

  30.    /**

  31.     * Add a provider.

  32.     *

  33.     * @param string $provider

  34.     *

  35.     * @return Application

  36.     */

  37.    public function addProvider($provider)

  38.    {

  39.        array_push($this->providers, $provider);

  40.        return $this;

  41.    }

  42.    /**

  43.     * Set providers.

  44.     *

  45.     * @param array $providers

  46.     */

  47.    public function setProviders(array $providers)

  48.    {

  49.        $this->providers = [];

  50.        foreach ($providers as $provider) {

  51.            $this->addProvider($provider);

  52.        }

  53.    }

  54.    /**

  55.     * Return all providers.

  56.     *

  57.     * @return array

  58.     */

  59.    public function getProviders()

  60.    {

  61.        return $this->providers;

  62.    }

  63.    /**

  64.     * Magic get access.

  65.     *

  66.     * @param string $id

  67.     *

  68.     * @return mixed

  69.     */

  70.    public function __get($id)

  71.    {

  72.        return $this->offsetGet($id);

  73.    }

  74.    /**

  75.     * Magic set access.

  76.     *

  77.     * @param string $id

  78.     * @param mixed  $value

  79.     */

  80.    public function __set($id, $value)

  81.    {

  82.        $this->offsetSet($id, $value);

  83.    }

  84. }

如何使用我们的应用:

  1. $app = new Application([]);

  2. $user = $app->user;

之后我们就可以使用 $user 对象的方法了。我们发现其实并没有 $this->user 这个属性,但是可以直接使用。主要是这两个方法起的作用:

  1. public function offsetSet($id, $value){}

  2. public function offsetGet($id){}

下面我们将解释在执行这两句代码,Pimple做了什么。但在解释这个之前,我们先看看容器的一些核心概念。

服务提供者

服务提供者是连接容器与具体功能实现类的桥梁。服务提供者需要实现接口 ServiceProviderInterface :

  1. namespace Pimple;

  2. /**

  3. * Pimple service provider interface.

  4. *

  5. * @author  Fabien Potencier

  6. * @author  Dominik Zogg

  7. */

  8. interface ServiceProviderInterface

  9. {

  10.    /**

  11.     * Registers services on the given container.

  12.     *

  13.     * This method should only be used to configure services and parameters.

  14.     * It should not get services.

  15.     *

  16.     * @param Container $pimple A container instance

  17.     */

  18.    public function register(Container $pimple);

  19. }

所有服务提供者必须实现接口 register 方法。

我们的应用里默认有2个服务提供者:

  1. protected $providers = [

  2.    ServiceProviders\ServerServiceProvider::class,

  3.    ServiceProviders\UserServiceProvider::class

  4. ];

以UserServiceProvider为例,我们看其代码实现:

  1. namespace EasyWeChat\Foundation\ServiceProviders;

  2. use EasyWeChat\User\User;

  3. use Pimple\Container;

  4. use Pimple\ServiceProviderInterface;

  5. /**

  6. * Class UserServiceProvider.

  7. */

  8. class UserServiceProvider implements ServiceProviderInterface

  9. {

  10.    /**

  11.     * Registers services on the given container.

  12.     *

  13.     * This method should only be used to configure services and parameters.

  14.     * It should not get services.

  15.     *







请到「今天看啥」查看全文