3.1. Configure the container
配置容器
开发环境
PHP-DI 的容器已预先配置好,开发环境可以“即插即用”。您可以像这样简单地使用它:
$container = new Container();
默认情况下, PHP-DI 会启用 自动装配 enabled (默认情况下禁用注解 ).
要更改容器上的选项,可以使用ContainerBuilder
类:
$builder = new \DI\ContainerBuilder();
$container = $builder->build();
生产环境
在生产环境中,一般以性能优先:
$builder = new \DI\ContainerBuilder();
$builder->enableCompilation(__DIR__ . '/tmp');
$builder->writeProxiesToFile(true, __DIR__ . '/tmp/proxies');
$container = $builder->build();
阅读 关于性能 了解更多。
轻量级容器
如果要将 PHP-DI 容器当做简单容器 (没有自动装配或注解)使用, 则可以禁用其所有的额外功能。
$builder = new \DI\ContainerBuilder();
$builder->useAutowiring(false);
$builder->useAnnotations(false);
$container = $builder->build();
请注意,这不一定意味着容器会更快,因为所有内容都是可以缓存的。
在 关于性能中了解有关此内容的更多信息。
与其他容器一起使用PHP-DI
如果要一次使用多个容器,例如要在ZF2或Symfony 2中使用PHP-DI,则可以
使用 Acclimate之类的工具。
您只需要告知 PHP-DI 复合容器, 否则 PHP-DI 不会感知到 Symfony 的容器条目。
Acclimate 示例:
$container = new Acclimate\Container\CompositeContainer();
// 添加 Symfony 容器
$container->addContainer($acclimate->adaptContainer($symfonyContainer));
// 配置 PHP-DI 容器
$builder = new \DI\ContainerBuilder();
$builder->wrapContainer($container);
// 添加 PHP-DI 容器
$phpdiContainer = $builder->build();
$container->addContainer($phpdiContainer);
// 准备好了,用吧!
$foo = $container->get('foo');
忽略phpDoc错误
在v4.4中添加
如果你使用注解并且你的 phpDoc 并不总是正确的, 则可以将容器设置为静默忽略这些错误:
$builder->ignorePhpDocErrors(true);
例如
class Foo
{
/**
* @param NonExistentClass $param
*/
public function useAutowiring($param)
{
}
}
在这里, PHP-DI 会抛出一个异常,因为 NonExistentClass
不存在:这就是 phpDoc 错误。
有反馈说 PHP-FPM 可能会阻塞此类错误 并返回类似这样的消息:
Handler for fastcgi-script returned invalid result code 1
为了避免错误,请确保您的注解正确无误或暂时禁用注解($ builder-> useAnnotations(false)
),以防止发生致命错误并尝试在此处清除配置表单。
本译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。