Call to undefined method Slim\Container::img()

Hi all,
I hope someone can help me figure this out. This is probably something supid, but I can’t figure this out.
I’m trying to inject a dependency like I have done in the past and it won’t work for some reason.
This works:

$container = $app->getContainer();
$container["mimey"] = function () {
    return new \Mimey\MimeTypes;

but this wont:

$container = $app->getContainer();
$container['img'] = function ($img) {
    return new \JBZoo\Image\Image($img);

I get Call to undefined method Slim\Container::img(), any ideas?

Hi @igor

The question is why should \JBZoo\Image\Image be a container service?

You are getting an “undefined method” error, because PHP is looking for a method (function) called img on the container when you use $this->img().

To work around this, you could do the following:

$imgFunc = $this->img; // get img as property, not method

This will still not work as expected, because when creating the container instance, the argument is the container itself, not $img. You cannot pass constructor arguments when getting an instance from the container.

You can work around this by returning a factory function instead of returning an Image instance directly:

$container['img'] = function ($container) {
    // return a factory function instead of an Image instance
    return function ($img) { 
        return new \JBZoo\Image\Image($img);

And in your controller:

$imgFactory = $this->img; // get the factory from the container
$image = $imgFactory($img); // call the factory function

@llvdl Thanks for your reply. I’ve just endup loading it like this:
use JBZoo\Image\Image:
and I guess @odan is right, I have no need to inject it in to a container. But your reply will help me in the future. :slight_smile:
Thanks everyone.