Steven Musumeche
Steven Musumeche

Reputation: 2936

Symfony2 - inject static class into service (ImageWorkshop)

I'm creating a service that uses ImageWorkshop. In order to init a new image, I need to call:

$layer = ImageWorkshop::initFromPath(__DIR__.'/../path/to/myimage.jpg');

I'd like to inject ImageWorkshop as a dependency, but I can't figure out how to do this since it uses static methods. I know I could just call ImageWorkshop statically from my service, but I'm trying to declare my dependencies.

Upvotes: 1

Views: 1386

Answers (2)

Emii Khaos
Emii Khaos

Reputation: 10085

That's the perfect use case for service factories.

You declare your $layer as a service and create it with the static factory method in the service container.

services:
    myimage_layer:
        class:   PHPImageWorkshop\Core\ImageWorkshopLayer
        factory_class: PHPImageWorkshop\ImageWorkshop
        factory_method: initFromPath
        arguments:
            - "%kernel.root_dir%/../path/to/myimage.jpg"

Now you can inject the myimage_layer service into your service as a service argument.

EDIT: If you need the ImageWorkshop directly to call them, but don't want to write ImageWorkshop::initFromPath('...') directly in your code, you can decouple it with the class name. It's not really useful, because ImageWorkshop is not directly replaceable, but it helps for mocking in tests.

services:
    myimage_whatever:
        class:   Acme\Bundle\AcmeBundle\Image\Whatever
        arguments:
            - "PHPImageWorkshop\\ImageWorkshop"

Your service:

namespace Acme\Bundle\AcmeBundle\Image;

class Whatever
{
    private $imageWorkshop;

    public function __construct($imageWorkshop)
    {
        $this->imageWorkshop = $imageWorkshop;
    }

    public function doWhatever($path)
    {
        $layer = $this->imageWorkshop::initFromPath($path);
        // ...
    }
 }

Beware yourself, $imageWorkshop is no instance. Instead it's a string containing the fully qualified class name of ImageWorkshop to call the static method on it. I hope this should work.

Reference for calling a static method on a string variable containing the class name: http://php.net/manual/en/language.oop5.static.php#example-214

Upvotes: 3

wonde
wonde

Reputation: 1181

I would create a wrapper class and implement the static class methods in it

e.g

Class ImageWorkshopWrapper
{
  public function initFromPath($path)
  {
    ImageWorkshop::initFromPath($path);
  }

}

and inject ImageWorkshopWrapper class

Upvotes: 0

Related Questions