Symfony2 - 将静态类注入服务(ImageWorkshop)



我正在创建一个使用ImageWorkshop的服务。 为了初始化一个新图像,我需要调用:

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

我想将 ImageWorkshop 作为依赖项注入,但由于它使用静态方法,因此我不知道该怎么做。 我知道我可以从我的服务静态调用 ImageWorkshop,但我正在尝试声明我的依赖项。

这是服务工厂的完美用例。

$layer声明为服务,并使用服务容器中的静态工厂方法创建它。

services:
    myimage_layer:
        class:   PHPImageWorkshopCoreImageWorkshopLayer
        factory_class: PHPImageWorkshopImageWorkshop
        factory_method: initFromPath
        arguments:
            - "%kernel.root_dir%/../path/to/myimage.jpg"

现在,您可以将myimage_layer服务作为服务参数注入到服务中。

编辑:如果您需要直接调用ImageWorkshop,但不想直接在代码中编写ImageWorkshop::initFromPath('...'),则可以将其与类名分离。它不是很有用,因为它不能直接替换ImageWorkshop但它有助于在测试中模拟。

services:
    myimage_whatever:
        class:   AcmeBundleAcmeBundleImageWhatever
        arguments:
            - "PHPImageWorkshop\ImageWorkshop"

您的服务:

namespace AcmeBundleAcmeBundleImage;
class Whatever
{
    private $imageWorkshop;
    public function __construct($imageWorkshop)
    {
        $this->imageWorkshop = $imageWorkshop;
    }
    public function doWhatever($path)
    {
        $layer = $this->imageWorkshop::initFromPath($path);
        // ...
    }
 }

小心自己,$imageWorkshop不是实例。相反,它是一个字符串,其中包含 ImageWorkshop 的完全限定类名,用于对其调用静态方法。我希望这应该有效。

对包含类名的字符串变量调用静态方法的参考:http://php.net/manual/en/language.oop5.static.php#example-214

我会创建一个包装类并在其中实现静态类方法

例如

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

并注入 ImageWorkshopWrapper 类

最新更新