代码之家  ›  专栏  ›  技术社区  ›  D Lowther

注入级多重完整的DI

  •  0
  • D Lowther  · 技术社区  · 8 年前

    我用的是 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 回复  |  直到 8 年前
        1
  •  0
  •   D Lowther    8 年前

    我不确定这是最好的答案,但没有人插话,所以我要继续。我创建了一个工厂类,它被注入到图像类中,该类接受参数并返回一个类似这样的想象点类的新实例:

    工厂

    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);
        }
    }
    

    现在,为了测试,我创建了一个工厂的模拟模型,并将其传入。

    推荐文章