php-di/zf2-bridge

将PHP-DI集成到Zend Framework 2

1.0.20 2018-11-21 11:26 UTC

README

Build Status

此库提供了PHP-DI与Zend Framework 2的集成。

PHP-DI 是一个PHP依赖注入容器。

如果您正在寻找Zend Framework 1的集成,请访问 此处

使用

使用Composer要求库

{
    "require": {
        "php-di/php-di": "*",
        "php-di/zf2-bridge": "*"
    }
}

要在ZF2应用程序中使用PHP-DI,您需要编辑 application_root/config/application.config.php

    // ...
    'modules' => [
        ...
        'DI\ZendFramework2',
        ...
    ],

    'service_manager' => [
        // ...
        'factories' => [
            'DI\Container' => 'DI\ZendFramework2\Service\DIContainerFactory',
        ],
    ],

这就完了!

现在您的依赖项已经注入到控制器中!

如果您想自己指定di配置,创建此文件: application_root/config/php-di.config.php 并保存您的PHP DI配置,例如如下所示

return [
    'Application\Service\GreetingServiceInterface' => Di\object('Application\Service\GreetingService'),
];

如有需要,请访问 PHP-DI的文档

微调

要配置模块,您需要在config/autoload/global.php或config/autoload/local.php中某处覆盖模块配置。

return [
    'phpdi-zf2' => [
        ...
    ]
];

覆盖定义文件位置

return [
    'phpdi-zf2' => [
        'definitionsFile' => realpath(__DIR__ . '/../my.custom.def.config.php'),
    ]
];

启用或禁用注解

return [
    'phpdi-zf2' => [
        'useAnntotations' => true,
    ]
];

启用APCu

return [
    'phpdi-zf2' => [
        'cache' => [
            'adapter' => 'apcu',
            'namespace' => 'your_di_cache_key',
        ],
    ]
];

启用文件缓存

return [
    'phpdi-zf2' => [
        'cache' => [
            'adapter' => 'filesystem',
            'namespace' => 'your_di_cache_key',
            'directory' => 'your_cache_directory', // default value is data/php-di/cache
        ],
    ]
];

启用Redis缓存

如果您也使用Redis来存储PHP会话,则配置php-di缓存处理程序使用不同的数据库非常有用,因为您可能会在清除php-di定义缓存时意外删除所有会话。

return [
    'phpdi-zf2' => [
        'cache' => [
            'namespace' => 'your_di_cache_key',
            'adapter' => 'redis',
            'host' => 'localhost', // default is localhost
            'port' => 6379, // default is 6379
            'database' => 1, // default is the same as phpredis default
        ],
    ]
];

启用Memcached缓存

如果您正在使用Memcached,则应在每个memcached实例中只有一个项目。

return [
    'phpdi-zf2' => [
        'cache' => [
            'adapter' => 'memcached',
            'host' => 'localhost', // default is localhost
            'port' => 11211, // default is 11211
        ],
    ]
];

控制台命令

清除定义缓存

要从项目根目录清除定义缓存,请运行以下命令

php public/index.php php-di-clear-cache