adlogix/zf-symfony-container

用于利用symfony依赖注入容器的Zend Framework模块

0.4.0 2018-11-09 12:55 UTC

This package is auto-updated.

Last update: 2024-09-10 05:08:21 UTC


README

用于利用symfony依赖注入容器的Zend Framework模块

Build Status

安装

  1. 通过运行以下命令安装模块:
composer require adlogix/zf-symfony-container:^0.4
  1. Adlogix\ZfSymfonyContainer模块添加到您的config/application.config.php文件的模块部分

配置

Symfony容器参数可以在应用配置中定义

<?php
return [

    'zf_symfony_container' => [

        // directory where to look for the service container configurations (e.g. config/services.yaml)
        'config_dir' => 'config',

        // Caching options
        'cache' => [

            // directory where the cached container will be stored
            'dir' => 'data/ZfSymfonyContainer',

            // name of the file to generate the cached container class
            'filename' => 'zf_symfony_container_cache',

            // name of the class of the generated cached container
            'classname' => 'CachedContainer',

            // the namespace of the generated cached container
            'namespace' => 'Adlogix\ZfSymfonyContainer\DependencyInjection',

            // enable in dev mode
            'debug' => false
        ],


    ],
];

使用

有关如何使用DI容器的信息,请参阅Symfony DI组件的文档。

获取symfony定义的服务

任何现有的symfony服务将通过Zend的服务管理器直接可用

<?php

$service = $this->getServiceLocator()->get(\My\Public\Service::class);

使用Zend服务依赖构建symfony定义的服务

有时候您需要使用已加载到Zend服务管理器中的依赖项。例如,如果您正在使用Doctrine模块并且需要Entity Manager的实例,您可以使用ZendServiceProxyFactory类

services:

  _defaults:

    autowire: true      # Automatically injects dependencies in your services.
    autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
    public: false       # Allows optimizing the container by removing unused services; this also means
                        # fetching services directly from the container via $container->get() won't work.
                        # The best practice is to be explicit about your dependencies anyway.

  #
  # Define service that needs to be retrieved via the Zend Service Manager
  #

  Doctrine\ORM\EntityManagerInterface:
    factory: ['Adlogix\ZfSymfonyContainer\Service\Factory\ZendServiceProxyFactory', getService]
    arguments: ['@zend.container', 'doctrine.entitymanager.orm_default']
    class: Doctrine\ORM\EntityManagerInterface

在此配置下,symfony容器定义的服务需要Doctrine\ORM\EntityManagerInterface的实例,将从这个Zend服务管理器中接收。

获取symfony容器实例

<?php

$container = $this->getServiceLocator()->get('zf_symfony_container');

使用Zend配置作为Symfony参数

该模块负责将所有zend配置转换为Symfony参数,使您能够立即在服务定义文件中使用这些参数

<?php
// global.php
return [
    'myconfig' => 'hello world' 
];
services:
  Some\Service:
    arguments: ['%myconfig%']

当Zend配置包含深层级别的键时,"keys"将通过点连接。

<?php
// global.php
return [
    'deep' => [
        'level' => [
            'config' => 'hello world'            
        ]    
    ]    
];
services:
  Some\Service:
    arguments: ['%deep.level.config%']

注意:使用可调用的zend配置将被忽略,无法使用!