Calling a method on a service created dynamically using a package

I use the package m6web_guzzleto register multiple http clients:

m6web_guzzlehttp:
    clients:
        myclient:
            timeout: 3
            headers:
                "Accept": "application/json"
            delay: 0
            verify: false

I want to call a method in a service that it dynamically generates. In this case, the generated service name:

@m6web_guzzlehttp.guzzle.handlerstack.myclient

Here is what I do in my services constructor: (the third parameter entered is "@ m6web_guzzlehttp.guzzle.handlerstack.myclient")

/**
 * @param array        $parameters
 * @param Client       $client
 * @param HandlerStack $handlerStack
 */
public function __construct(array $parameters, Client $client, HandlerStack $handlerStack)
{
    $this->parameters = $parameters;
    $this->client = $client;
    $this->handlerStack->push(Middleware::retry([$this, 'retryDecider']));
}

So far this works well, but how can I transfer the last line (call push) to my file services.yml? Or another cleanup method to register this retry handler?

+6
source share
3 answers

bundle Extension.php :

$definition = $container->getDefinition('m6web_guzzlehttp.guzzle.handlerstack.myclient');
$definition->addMethodCall('push', [Middleware::retry([$this, 'retryDecider'])]);
+3

. .

. , - , Symfony (AFAIK) Closure - , Guzzle.

service.yml :

m6web_guzzlehttp.guzzle.handlerstack.myclient:
    class: GuzzleHttp\HandlerStack
    factory: ['GuzzleHttp\HandlerStack', create]

retry_decider:
    class: MyBundle\RetryDecider
    factory: ['MyBundle\RetryDecider', createInstance]

retry_handler:
    class: GuzzleHttp\Middleware
    factory: ['GuzzleHttp\Middleware', retry]
    arguments:
        - '@retry_decider'

handlerstack_pushed:
    parent: m6web_guzzlehttp.guzzle.handlerstack.myclient
    calls:
        - [push, ['@retry_handler']]

?

  • m6web_guzzlehttp.guzzle.handlerstack.myclient - - , .
  • retry_decider - . Closure createInstance. , , YML.
  • retry_handler - ,
  • handlerstack_pushed - push() , .

Et voilà - , , .

:

<?php

namespace MyBundle;

class RetryDecider {

    public static function createInstance() {
        return function() {
            // do your deciding here
        };
    }

}

- > handlerstack_pushed, .

, m6web_guzzlehttp.guzzle.handlerstack.myclient parameters.yml:

parameters:
    baseHandlerStackService: m6web_guzzlehttp.guzzle.handlerstack.myclient

handlerstack_pushed:

handlerstack_pushed:
    parent: "%baseHandlerStackService%"
    calls:
        - [push, ['@retry_handler']]

, ; -)

+2

, .

+1

All Articles