neighborhoods/dependency-injection-container-builder

基于Symfony的依赖注入容器构建器。

1.1.3 2021-07-02 19:42 UTC

This package is auto-updated.

Last update: 2024-08-29 05:37:55 UTC


README

基本使用示例

$container = (new \Neighborhoods\DependencyInjectionContainerBuilderComponent\TinyContainerBuilder())
    ->setContainerBuilder(new \Symfony\Component\DependencyInjection\ContainerBuilder())
    ->setRootPath(dirname(__DIR__))
    ->addSourcePath('src/ComponentName')
    ->addSourcePath('src/Prefab5')
    ->addSourcePath('fab/ComponentName')
    ->makePublic(SomeRepository::class)
    ->addCompilerPass(new \Symfony\Component\DependencyInjection\Compiler\AnalyzeServiceReferencesPass())
    ->addCompilerPass(new \Symfony\Component\DependencyInjection\Compiler\InlineServiceDefinitionsPass())
    ->build();
  • setContainerBuilder:设置器接受\Symfony\Component\DependencyInjection\ContainerBuilder的实例。可以提供非空容器。
  • setRootPath:接收项目根目录的路径(其中包含srcfab文件夹)
  • addSourcePath:接收包含容器构建器定义的文件夹的路径
  • makePublic:接收服务URI(通常是类名)并使其公开
  • makeAllPublic:使所有服务公开
  • addCompilerPass:接收\Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface的实例并将其提供给ContainerBuilder的addCompilerPass方法。
  • build:创建并返回一个\Psr\Container\ContainerInterface的实例

使用缓存

如果容器需要缓存,可以通过setCacheHandler提供\Neighborhoods\DependencyInjectionContainerBuilderComponent\CacheHandlerInterface

$cacheHandler = (new \Neighborhoods\DependencyInjectionContainerBuilderComponent\SymfonyConfigCacheHandler\Builder())
    ->setName('ContainerName')
    ->setCacheDirPath(dirname(__DIR__) . '/data/cache')
    ->setDebug(true)
    ->build();
$container = (new \Neighborhoods\DependencyInjectionContainerBuilderComponent\TinyContainerBuilder())
    // ... 
    ->setCacheHandler($cacheHandler)
    ->build();
  • setName:接收缓存的容器类的名称
  • setCacheDirPath:接收容器文件将要存储的目录的路径(绝对路径)
  • setDebug:接收一个布尔标志,表示是否开启“调试模式”。当开启调试模式时,缓存将“监听”源配置文件的变化。如果有任何更改,缓存将被视为无效,并将生成并存储新的缓存。建议仅在开发中使用true