Search code examples
symfonyservicecode-injection

(Symfony 4) How do you manually add a vendor class to the container, then inject to a repository/service class?


I have a repository class for photos:

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

I am getting the typical 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?

The Imagine\ImageBox class clearly exists in my vendor folder and implements the BoxInterface, it starts out as follows:

namespace Imagine\Image;

use Imagine\Exception\InvalidArgumentException;

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

Here is a picture of my folder structure, you can see that this Box class is there and that it implements BoxInterface:

enter image description here

I'm stuck because it says that the service doesn't exist but you can see that it does.

Any help is greatly appreciated.


Solution

  • To reply your question regarding working with interfaces, check this section of the docs: https://symfony.com/doc/current/service_container/autowiring.html#working-with-interfaces

    However you're misunderstanding the purpose of services. Imagine's BoxInterface is by no means a service and shouldn't be declared as one. A service is needed only when you need only one instance of it through your whole application. BoxInterface just describes a coordinates of a picture, therefore there will be as many instances as you need pictures instances.

    Just create for example $box = new Imagine\Image\Box(50, 50); when you need a box.