我在我的Symfony2应用程序中调整了图像大小的图像服务。我希望能够以这种方式配置此服务,以便可以采用许多指示有效图像大小的参数。例如。这是我目前的服务定义:使用自定义标签定义Symfony2服务
my.service.image:
class: My\Service\ImageService
arguments: ["@service_container"]
不知何故,我想指出一个有效数量的图像大小。我研究过使用标签,但我不确定它们是否适合在这种情况下使用。在一个理想的世界,我可能想的东西,看起来像这样结束了:
my.service.image:
class: My\Service\ImageService
arguments: ["@service_container"]
sizes:
- { name: small, width: 100, height: 100 }
- { name: medium, width: 100, height: 100 }
- { name: large, width: 100, height: 100 }
什么是实现这一点,如何让我的服务感知的各种“规格”的最佳方式?
UPDATE:
我已经取得了一些进展,但我仍然停留在这个问题上。这是迄今为止我所取得的成就。
我用标签来实现不同尺寸:
my.service.image:
class: My\Service\ImageService
arguments: ["@service_container"]
tags:
- { name: my.service.image.size, alias: small, width: 100, height: 100 }
- { name: my.service.image.size, alias: medium, width: 200, height: 200 }
- { name: my.service.image.size, alias: large, width: 300, height: 300 }
试图按照食谱文档[1],我结束了我的包创建* CompilerPass类:
namespace My\Bundle\MyImageBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Reference;
class ImageServiceSizeCompilerPass implements CompilerPassInterface {
public function process(ContainerBuilder $container)
{
$definition = $container->get(
'my.service.image'
);
$taggedServices = $container->findTaggedServiceIds(
'my.service.image.size'
);
foreach($taggedServices as $defintion => $attributes)
{
foreach($attributes as $attribute)
{
$definition->addSize($attribute['alias'], $attribute['width'], $attribute['height']);
}
}
}
}
以上实际上是调用服务上的addSize
方法。我不确定上述内容是否正确,但似乎可行。
我现在遇到的问题是,当我在应用程序代码中从容器中请求my.service.image
时,它似乎再次实例化它,而不是返回它第一次创建的实例。
任何有识之士将不胜感激。
[1] http://symfony.com/doc/current/components/dependency_injection/tags.html