Slim 3 + Guzzle

Hi,

Can anybody here show clearly how to integrate Guzzle with Slim 3 using dependency container, so it is directly available in rotexsoft/slim3-skeleton-mvc-app controllers as e.g. “Client” object.

I would really appreciate “for the beginner” type of answer.
Thanks ahead

I can try to get you started at least. It looks like in config/dependencies-dist.php you would need to add it to the container. Something like this:

$container['client'] = function ($c) {
    $client = new \GuzzleHttp\Client();
    return $client;
};

From there, see the docs on Container Resolution to see ways you can pass it to your controllers.

1 Like

Yeap,

I already added this to my “dependencies.php”:

//Guzzle HTTP client
$container['httpClient'] = function() {
    $guzzle = new \GuzzleHttp\Client();
    return $guzzle;
};

And this seems to work in controller:

$container = $this->app->getContainer();
$guzzle = $container['httpClient'];

BTW - why do you add this $c as a closure function argument?

Habit. :slight_smile: Sometimes I need to access something in my settings file to pass to a constructor. For example I use Guzzle in my projects to hook up to services like mailgun. Passing the container into the function gets me access to my app settings where I’d pass API keys and such to the Guzzle client.

Isn’t it an 'antipattern"? I mean - passing the DI container into a function? I would rather pass it’s specific property to a function, not the container itself!

Correct! You don’t need to do it that way though. The docs show a few different methods, note where it says this.

Slim first looks for an entry of \HomeController in the container, if it’s found it will use that instance

You can setup your controller and its dependencies in the container, then the controller is given what it needs, and only what it needs, from the DI. See this example of creating the controller from the DI.

1 Like