2013-08-23 46 views
0

我在我的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

回答

0

我不知道你的exaclty是你的使用情况,但我想给你以下提示

  • 难道这些图像(它们的路径)保存为实体的属性?那为什么不直接在实体上使用 注解?

  • 如果你真的想要这个可配置的,那么为什么不创建一个真正的配置呢?

  • 如果你想的东西传递到您的服务(而不是要创建一个配置),你 可以使您的YML文件中paramters你的尺寸,并将其传递到您的 服务,或者你只是获取从参数您的服务本身使用 $ container-> getParameter('NAME');(假设你有一个注入容器)

希望我能帮上忙, nixo