(Symfony 4)如何手动将供应商类添加到容器中,然后注入存储库/服务类?

问题描述 投票:0回答:1

我有一个照片的存储库类:

use Imagine\Image\ImageInterface;
use Imagine\Image\ImagineInterface;
use Imagine\Image\BoxInterface;

class PhotoRepository extends ServiceEntityRepository
{

protected $imagineInterface;
protected $mode;
protected $box;

public function __construct(ImagineInterface $imagineInterface,
    BoxInterface $box,
    $mode = ImageInterface::THUMBNAIL_OUTBOUND)
    {
        $this->imagineInterface = $imagineInterface; 
        $this->$box = $box; 
         $this->mode = $mode;
    }

我得到了典型的Cannot autowire service "App\Repository\PhotoRepository": argument "$box" of method "__construct()" references interface "Imagine\Image\BoxInterface" but no such service exists. Did you create a class that implements this interface?

Imagine \ ImageBox类显然存在于我的vendor文件夹中并实现BoxInterface,它开始如下:

namespace Imagine\Image;

use Imagine\Exception\InvalidArgumentException;

/**
 * A box implementation
 */
final class Box implements BoxInterface
{
    /**
     * @var integer
     */
    private $width;

这是我的文件夹结构的图片,你可以看到这个Box类在那里,它实现了BoxInterface:

enter image description here

我被困了,因为它说服务不存在,但你可以看到它确实存在。

任何帮助是极大的赞赏。

symfony service code-injection
1个回答
0
投票

要回答有关使用接口的问题,请查看文档的这一部分:https://symfony.com/doc/current/service_container/autowiring.html#working-with-interfaces

但是你误解了服务的目的。想象一下BoxInterface绝不是服务,不应该声明为一个服务。只有在整个应用程序中只需要一个实例时才需要服务。 BoxInterface只描述图片的坐标,因此您需要图片实例的实例数量。

当你需要一个盒子时,只需创建例如$box = new Imagine\Image\Box(50, 50);

© www.soinside.com 2019 - 2024. All rights reserved.