I need to inject two objects into ImageService
. One of them is an instance of Repository/ImageRepository
, which I get like this:
$image_repository = $container->get('doctrine.odm.mongodb') ->getRepository('MycompanyMainBundle:Image');
So how do I declare that in my services.yml? Here is the service:
namespace Mycompany\MainBundle\Service\Image; use Doctrine\ODM\MongoDB\DocumentRepository; class ImageManager { private $manipulator; private $repository; public function __construct(ImageManipulatorInterface $manipulator, DocumentRepository $repository) { $this->manipulator = $manipulator; $this->repository = $repository; } public function findAll() { return $this->repository->findAll(); } public function createThumbnail(ImageInterface $image) { return $this->manipulator->resize($image->source(), 300, 200); } }
The Dependency Injection Container in Symfony2 allows components to be injected with their dependencies, and is often used as a Service Locator, which when combined with the DI-container pattern is considered to be an anti-pattern by many.
A repository is a way to retrieve entities, so put on repositories any method you need to get them, such as getUserByEmail or whatever.
In Symfony, these useful objects are called services and each service lives inside a very special object called the service container. The container allows you to centralize the way objects are constructed. It makes your life easier, promotes a strong architecture and is super fast!
Here is a cleaned up solution for those coming from Google like me:
Update: here is the Symfony 2.6 (and up) solution:
services: myrepository: class: Doctrine\ORM\EntityRepository factory: ["@doctrine.orm.entity_manager", getRepository] arguments: - MyBundle\Entity\MyClass myservice: class: MyBundle\Service\MyService arguments: - "@myrepository"
Deprecated solution (Symfony 2.5 and less):
services: myrepository: class: Doctrine\ORM\EntityRepository factory_service: doctrine.orm.entity_manager factory_method: getRepository arguments: - MyBundle\Entity\MyClass myservice: class: MyBundle\Service\MyService arguments: - "@myrepository"
I found this link and this worked for me:
parameters: image_repository.class: Mycompany\MainBundle\Repository\ImageRepository image_repository.factory_argument: 'MycompanyMainBundle:Image' image_manager.class: Mycompany\MainBundle\Service\Image\ImageManager image_manipulator.class: Mycompany\MainBundle\Service\Image\ImageManipulator services: image_manager: class: %image_manager.class% arguments: - @image_manipulator - @image_repository image_repository: class: %image_repository.class% factory_service: doctrine.odm.mongodb factory_method: getRepository arguments: - %image_repository.factory_argument% image_manipulator: class: %image_manipulator.class%
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With