DI具有多个注入类的实例

时间:2018-05-23 17:32:03

标签: php dependency-injection php-imagine

我正在使用Imagine库进行一些图像实时编辑,并且正在运行墙,了解如何解耦我可能需要动态构建多个实例的类。

受控示例

namespace App;

use Imagine\Image\{ Point, ImagineInterface };
use Imagine\Image\Palette\PaletteInterface;

class Image 
{
    protected $imagine;
    protected $palette;

    public function __construct(ImagineInterface $imagine, PaletteInterface $palette)
    {
        $this->imagine = $imagine;
        $this->palette = $palette;
    }

    public function buildImage($args)
    {
        $image = $this->imagine->open('some/file/path');
        $font = $this->imagine->font('some/font/path', 20, $this->palette->color('#000'));

        /* how to inject these when x/y are dynamically set? */
        $point1 = new Point($args['x1'], $args['y1']);
        $point2 = new Point($args['x2'], $args['y2']);

        $image->draw()->text('example one', $font, $point1);
        $image->draw()->text('example one', $font, $point2);
    }
}

1 个答案:

答案 0 :(得分:0)

我不确定这是最好的答案,但没有人插话,所以我会选择它。我创建了一个工厂类,它被注入到带有参数的image类中,并返回一个Imagine Point类的新实例,如下所示:

namespace App\Image;

use Imagine\Image\Point;

class PointFactory
{
    public function create($x, $y)
    {
        return new Point($x, $y);
    }
}

图像

namespace App;

use Imagine\Image\ImagineInterface;
use Imagine\Image\Palette\PaletteInterface;
use App\Image\PointFactory;

class Image 
{
    protected $imagine;
    protected $palette;

    public function __construct(ImagineInterface $imagine, PaletteInterface $palette, PointFactory $point)
    {
        $this->imagine = $imagine;
        $this->palette = $palette;
        $this->pointFactory = $point;
    }

    public function buildImage($args)
    {
        $image = $this->imagine->open('some/file/path');
        $font = $this->imagine->font('some/font/path', 20, $this->palette->color('#000'));

        /* how to inject these when x/y are dynamically set? */
        $point1 = $this->pointFactory->create($args['x1'], $args['y1']);
        $point2 = $this->pointFactory->create($args['x2'], $args['y2']);

        $image->draw()->text('example one', $font, $point1);
        $image->draw()->text('example one', $font, $point2);
    }
}

现在测试我创建一个工厂的模拟并传入它。