0

I cannot transfer service into another service in array.

For example this is my config.yml:

services:
    car.price.calculator:
        class:        My\SuperBundle\CarCalculator
        arguments:    "something"

product_viewer:
    car:
        rest_client: "@car.price.calculator"  # <- this is the service I cannot transfer
        rest_url: http://example.com

and service.xml:

<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>
        <service id="product.browser" class="Mrok\ShopBundle\Price\Calculator">
            <argument key="car" type="collection">
                <argument key="rest_client">%product.browser.rest_client%</argument>
                <argument key="rest_url">%product.browser.rest_url%</argument>
            </argument>
        </service>
    </services>
</container>

my MrokShopExtension rewrites data from configuration into container parameters, ex

 $container->setParameter('product.browser.rest_client', $config[0]['car']['rest_client']); 

Calculator class:

class Calculator {

private $set;

public function __contruct(array $set) {
    $this->set = $set;
    var_dump($set);
}

and as a result I got (var_dump from code):

   array (size=2)
     'rest_client' => string '@car.price.calculator' <- and here is a problem, it is a string, should be object

How instead of getting the string as rest_client get class instance (service). I cannot change argument into:

<argument type="service" id="car.price.calculator" />

because I do not know what kind of service will end user inject.

I know I can pass whole container and service id as parameter - but I would like to avoid injecting container.

4
  • pass to your service (a)service.container and get another service with container or maybe need no '(a)car.price.calculator', but '%car.price.calculator%'
    – ZloyPotroh
    Mar 9, 2013 at 10:23
  • xcompl - I do not want to pass whole container, I would like to inject only services which I need
    – mrok
    Mar 9, 2013 at 10:48
  • Basically you can use compiler pass. (See symfony.com/doc/2.1/cookbook/service_container/…) You can use then addArgument... something like that $definition->addArgument(new Reference($container->getParameter('product.browser.rest_client'))); Please see symfony.com/doc/2.1/components/dependency_injection/… as well.
    – l3l0
    Mar 9, 2013 at 12:13
  • I think for renaming a service you should use setAlias rather than setParameter and then just use car.price.calculator without the @.
    – qooplmao
    Mar 9, 2013 at 23:54

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.