proklung/container-locator-bundle

自定义 Symfony 容器定位器包

安装: 2

依赖: 0

建议者: 0

安全: 0

星标: 2

关注者: 1

分支: 0

开放问题: 0

类型:symfony-bundle

1.0.2 2021-08-08 19:33 UTC

This package is auto-updated.

Last update: 2024-09-09 03:14:37 UTC


README

内部

安装

composer.json

    "repositories": [
        {
            "type": "git",
            "url": "https://github.com/proklung/container.locator.bundle"
        }
    ]
composer require proklung/container-locator-bundle

为什么?

实验。目前我的包中的 container 助手通过 我的包 调用主类 ServiceProvider,这是正常的。这个包实现的方式是另一种选择,看起来稍微“更干净”。

基于这样的认识,即每个通过 boot 方法初始化的包都会注入一个容器实例。

这个包所做的所有事情都是装饰包的 setContainer 方法,将容器保存到静态属性中。同时,它也解耦了具体的容器实现。

如何获取容器

ContainerLocator

  • 静态方法 instanceFromBundles() - 从包的配置文件中。代价是加载文件并遍历类,直到找到拥有 getContainer 方法的包。
  • 静态方法 instance() - 从这个包的类中。

结果,container 助手可能看起来像这样

    function container($classContainer = ContainerLocator::class)
    {
        $container = $classContainer::instance();
        if ($container === null) {
            throw new RuntimeException(
              'Service container '. is_object($classContainer) ? get_class($classContainer) : $classContainer.
                      ' not initialized.'
            );
        }

        return $container;
    }

语法糖

用于在非容器友好的地方使用(如 Bitrix 组件内部等)

ContainerHelper

  • public static function kernel() - Kernel
  • public static function kernelParameters() - Kernel 参数
  • public static function parameter(string $param) - 具体Kernel参数。
  • public static function twig() - Twig。
  • public_static function session() - Session。
  • public static function logger() - Logger(服务 public.logger)。