Cannot autowire service "App\Service\MatchCarAdService": argument "$templating" of method - php

Hi I'm creating a service. This is the code,
namespace App\Service;
use Symfony\Component\DependencyInjection\ContainerInterface;
use App\Entity\CarAd;
class MatchCarAdService {
protected $mailer;
protected $templating;
public function __construct(ContainerInterface $container, \Swift_Mailer $mailer, $templating) {
$this->container = $container;
$this->mailer = $mailer;
$this->templating = $templating;
}
public function sendMail() {
$message = (new \Swift_Message('Hello Email'))
->setFrom('vimuths#yahoo.com')
->setTo('vimuths#yahoo.com')
->setBody(
$this->templating->render(
// templates/emails/matching-cars.html.html.twig
'emails/matching-cars.html.html.twig', []
), 'text/html'
);
$this->mailer->send($message);
This is services.yml
MatchCarAdService:
class: App\Service\MatchCarAdService
arguments: ['#mailer','#templating']
But I'm getting this error,
Cannot resolve argument $matchService of
"App\Controller\Api\SearchController()": Cannot autowire service
"App\Service\MatchCarAdService": argument "$templating" of method
"__construct()" has no type-hint, you should configure its value
explicitly.

Right now your constructor has 3 parameters but in arguments you are putting 2 only.
So there are two possible solutions:
Configure in your yaml
MatchCarAdService:
class: App\Service\MatchCarAdService
arguments: ['#container', '#mailer','#templating']
Use auto wiring with type hint
There it depends on your Symfony version, but change constructor to
public function __construct(ContainerInterface $container, \Swift_Mailer $mailer, Symfony\Component\Templating\EngineInterface; $teplating) {
$this->container = $container;
$this->mailer = $mailer;
$this->templating = $templating;
}
And you may have to composer require symfony/templating in order to get the Symfony\Bundle\FrameworkBundle\Templating\EngineInterface service.
Also the following configuration has to be added under framework:
templating:
enabled: true
engines: ['twig']

Symfony 3.3+ Answer
Answer by #M. Kebza solves your situation. But you can make this even simpler and bug-proof. Just use Symfony 3.3+ features.
A. Use Autowiring
services:
_defaults:
autowire: true
App\Service\MatchCarAdService: ~
App\Service\CleaningService: ~
App\Service\RentingService: ~
B. Use Autowiring + Autodiscovery - Even better!
services:
_defaults:
autowire: true
App\:
resource: ../src
This load all services in App\ namespace from ../src directory by PSR-4 convention.
You can see more examples in How to refactor to new Dependency Injection features in Symfony 3.3 post.

Related

symfony EventSubscriber ignored in Symfony 3.4

I'm trying to use an event subscriber to redirect person registering to a different route, than the standard FOSUser bundle directs them to. Going by some tutorials for Symfony 3.3, but wondered as I have version 3.4 if anything needs changing to make it work, as it currently just goes to the standard page? Thanks
EventSubscriber
namespace eventsBundle\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Http\Util\TargetPathTrait;
use Symfony\Component\Routing\RouterInterface;
use FOS\UserBundle\Event\FormEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;
use FOS\UserBundle\FOSUserEvents;
class RedirectAfterRegistrationSubscriber implements
EventSubscriberInterface
{
use TargetPathTrait;
private $router;
public function __construct(RouterInterface $router)
{
$this->router = $router;
}
public function onRegistrationSuccess(FormEvent $event)
{
die();
// main is your firewall's name
$url = $this->getTargetPath($event->getRequest()->getSession(),
'main');
if (!$url) {
$url = $this->router->generate('homepage');
}
$response = new RedirectResponse($url);
$event->setResponse($response);
}
public static function getSubscribedEvents()
{
return [
FOSUserEvents::REGISTRATION_SUCCESS =>
['onRegistrationSuccess',-5]
];
}
}
services.yml
services:
_defaults:
autowire: true
autoconfigure: true
eventsBundle\:
resource: '../../src/eventsBundle/*'
exclude: '../../src/eventsBundle/{Entity,Repository,Tests}'
eventsBundle\EventListener\RedirectAfterRegistrationSubscriber:
autowire: true
I added die(); just to make sure it was going to this but, has not effect
The services.yml file to change is the one in my bundle not the main services.yml under app/config, this now picks up the EventSubscriber
Looks like you need to add tag for your subscriber.
eventsBundle\EventListener\RedirectAfterRegistrationSubscriber:
autowire: true
tags:
- { name: kernel.event_subscriber }

How to inject an array of parameters in Symfony service?

I'm trying to inject some twig views as templates for a custom mailer service, which will be used as dependency by another service.
I don't get why, but it's like Symfony doesn't see the parameters I'm trying to inject in $parameters.
What is the proper way to inject this array of services as parameter ?
Here is the services.yaml part:
parameters:
locale: 'en'
template: '%fos_user.registration.confirmation.template%'
resetting: '%fos_user.resetting.email.template%'
from_email: 'somemail#mail.com'
confirmation: '%fos_user.registration.confirmation.from_email%'
resetting_password: '%fos_user.resetting.email.from_email%'
services:
user.mailer.rest:
class: App\Mailer\RestMailer
public: false
parent: fos_user.mailer.twig_swift
autoconfigure: false
autowire: true
arguments:
$parameters:
- '#template'
- '#resetting'
The RestMailer service constructor:
public function __construct(\Swift_Mailer $mailer, UrlGeneratorInterface $router, \Twig_Environment $twig, array $parameters)
{
$this->mailer = $mailer;
$this->router = $router;
$this->twig = $twig;
$this->parameters = $parameters;
}
public function sendConfirmationEmailMessage(UserInterface $user)
{
$template = $this->parameters['template']['confirmation'];
//...
Here is the returned error:
In DefinitionErrorExceptionPass.php line 54:
Cannot autowire service "App\Mailer\RestMailer": argument "$parameters" >of method "__construct()" is type-hinted "array", you should configure >its value explicitly.
Did you already configure in the services.yml?
If you want to use the parameters in config.yml, you have to set up in the services.yml to used/call the parameters.

How to call Entity Manager in a constructor?

I've been trying to call Entity Manager in a constructor:
function __construct()
{
$this->getDoctrine()->getEntityManager();
...
but, as I've seen in this answer: Stackoverflow question, it can't be done.
So I wonder if there is a way to achieve it, as I have to call it often, and want to do some stuff in the constructor after getting the repository.
Edit:
I've tried with #MKhalidJunaid answer:
//src/MSD/HomeBundle/Resources/config/services.yml
services:
imageTransController.custom.service:
class: MSD\HomeBundle\Controller\ImageTransController
arguments:
EntityManager: "#doctrine.orm.entity_manager"
-
//app/config/config.php
imports:
- { resource: parameters.yml }
- { resource: security.yml }
- { resource: doctrine_extensions.yml }
- { resource: "#MSDHomeBundle/Resources/config/services.yml" }
-
//src/MSD/HomeBundle/Controller/ImageTransController.php
namespace MSD\HomeBundle\Controller;
use Doctrine\ORM\EntityManager;
use MSD\HomeBundle\Entity\Imagen as Imagen;
use MSD\HomeBundle\Controller\HomeController as HomeController;
class ImageTransController extends HomeController
{
protected $em ;
function __construct(EntityManager $entityManager)
{
...
but I'm getting this error:
Catchable Fatal Error: Catchable Fatal Error: Argument 1 passed to MSD\HomeBundle\Controller\ImageTransController::__construct() must be an instance of Doctrine\ORM\EntityManager, none given, called in /home/manolo/MiServer/itransformer/app/cache/dev/jms_diextra/controller_injectors/MSDHomeBundleControllerImageTransController.php on line 13 and defined in /home/manolo/MiServer/itransformer/src/MSD/HomeBundle/Controller/ImageTransController.php line 38 (500 Internal Server Error)
New attempt:
I've also tried with #praxmatig answer:
//services.yml
parameters:
msd.controller.imagetrans.class: MSD\HomeBundle\Controller\ImageTransController
services:
msd.imagetrans.controller:
class: "%msd.controller.imagetrans.class%"
arguments: [ #doctrine.orm.entity_manager ]
-
//ImageTransController.php
namespace MSD\HomeBundle\Controller;
use Doctrine\ORM\EntityManager;
class ImageTransController
{
protected $em ;
function __construct(EntityManager $em)
{
$this->em = $em;
}
...
-
//routing.yml
msd_home_cambiardimensiones:
pattern: /cambiardimensiones
defaults: { _controller: MSDHomeBundle:msd.imagetrans.controller:cambiardimensionesAction }
but I get this error:
Unable to find controller "MSDHomeBundle:msd.imagetrans.controller" - class "MSD\HomeBundle\Controller\msd.imagetrans.controllerController" does not exist. (500 Internal Server Error)
You need to make a service for your class and pass the doctrine entity manager as the argument doctrine.orm.entity_manager.Like in services.yml
services:
test.cutom.service:
class: Test\YourBundleName\Yourfoldernameinbundle\Test
#arguments:
arguments: [ #doctrine.orm.entity_manager ]
#entityManager: "#doctrine.orm.entity_manager"
You must import your services.yml in config.yml
imports:
- { resource: "#TestYourBundleName/Resources/config/services.yml" }
Then in your class's constructor get entity manager as argument
use Doctrine\ORM\EntityManager;
Class Test {
protected $em;
public function __construct(EntityManager $entityManager)
{
$this->em = $entityManager;
}
}
Hope this makes sense
Don't extend the base controller class when you register controller as a service. There is a documentation about it here
class ImageTestController
{
private $em;
public function __construct(EntityManager $em)
{
$this->em = $em;
}
public function someAction()
{
// do something with $this->em
}
}
// services.yml
services:
acme.controller.image_test:
class: Acme\SomeBundle\Controller\ImageTestController
// routing.yml
acme:
path: /
defaults: { _controller: acme.controller.image_test:someAction }
Why do you want to grab the Doctrine 2 EntityManager in the constructor of a controller?
Why not simply do $em = $this->getDoctrine()->getManager(); (or $em = $this->getDoctrine()->getEntityManager(); in Symfony 2.0) in the action(s) you need it? This saves you from the overhead of initializing the EntityManager when you don't need it.
If you really do want to do this, there are clear instructions on How to define Controllers as Services. Basically it looks like this:
# src/MSD/HomeBundle/Controller/ImageTransController.php
namespace MSD\HomeBundle\Controller;
use Doctrine\ORM\EntityManager;
class ImageTransController
{
private $em;
public function __construct(EntityManager $em)
{
$this->em = $em;
}
public function indexAction()
{
// use $this->em
}
}
# src/MSD/HomeBundle/Resources/config/services.yml
parameters:
msd.controller.image_trans.class: MSD\HomeBundle\Controller\ImageTransController
services:
msd.controller.image_trans:
class: "%msd.controller.image_trans.class%"
arguments: ["#doctrine.orm.default_entity_manager"]
# app/config/routing.yml
msd_home_cambiardimensiones:
path: /cambiardimensiones
defaults: { _controller: msd.controller.image_trans:indexAction }
You have to add
use Doctrine\ORM\EntityManager;
in your controller
I see that you are trying to get the entity manager in the constructor of the controller, which is not the way to do so , unless you plan to define your controller as a service.
which on this case, you need to use dependency injection to inject the service entity manager.
But in general the common way to use entity manager in a controller is simply by getting it using the following code:
$entityManager = $this->container->get('doctrine.orm.entity_manager');
I think you are in the right direction, I would take the second option:
For the second option I think that the definition inside routing.yml is wrong
//routing.yml
msd_home_cambiardimensiones:
pattern: /cambiardimensiones
defaults: { _controller: msd.imagetrans.controller:cambiardimensionesAction }
Here just remove MSDHomeBundle from the _controller inside defaults
For the first option:
Does HomeController has its own constructor?
//src/MSD/HomeBundle/Resources/config/services.yml
services:
imageTransController.custom.service:
class: MSD\HomeBundle\Controller\ImageTransController
arguments: [#doctrine]
it could help then inside the constructor
__construct(Registry $doctrine)
$this->doctrine = $doctrine;
or
$this->em = $doctrine->getManager();

How to inject a repository into a service in Symfony?

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);
}
}
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%
In case if do not want to define each repository as a service, starting from version 2.4 you can do following, (default is a name of the entity manager):
#=service('doctrine.orm.default_entity_manager').getRepository('MycompanyMainBundle:Image')
Symfony 3.3, 4 and 5 makes this much simpler.
Check my post How to use Repository with Doctrine as Service in Symfony for more general description.
To your code, all you need to do is use composition over inheritance - one of SOLID patterns.
1. Create own repository without direct dependency on Doctrine
<?php
namespace MycompanyMainBundle\Repository;
use Doctrine\ORM\EntityManagerInterface;
use MycompanyMainBundle\Entity\Image;
class ImageRepository
{
private $repository;
public function __construct(EntityManagerInterface $entityManager)
{
$this->repository = $entityManager->getRepository(Image::class);
}
// add desired methods here
public function findAll()
{
return $this->repository->findAll();
}
}
2. Add config registration with PSR-4 based autoregistration
# app/config/services.yml
services:
_defaults:
autowire: true
MycompanyMainBundle\:
resource: ../../src/MycompanyMainBundle
3. Now you can add any dependency anywhere via constructor injection
use MycompanyMainBundle\Repository\ImageRepository;
class ImageService
{
public function __construct(ImageRepository $imageRepository)
{
$this->imageRepository = $imageRepository;
}
}
In my case bases upon #Tomáš Votruba answer and this question I propose the following approaches:
Adapter Approach
Without Inheritance
Create a generic Adapter Class:
namespace AppBundle\Services;
use Doctrine\ORM\EntityManagerInterface;
class RepositoryServiceAdapter
{
private $repository=null;
/**
* #param EntityManagerInterface the Doctrine entity Manager
* #param String $entityName The name of the entity that we will retrieve the repository
*/
public function __construct(EntityManagerInterface $entityManager,$entityName)
{
$this->repository=$entityManager->getRepository($entityName)
}
public function __call($name,$arguments)
{
if(empty($arrguments)){ //No arguments has been passed
$this->repository->$name();
} else {
//#todo: figure out how to pass the parameters
$this->repository->$name(...$argument);
}
}
}
Then foreach entity Define a service, for examplein my case to define a (I use php to define symfony services):
$container->register('ellakcy.db.contact_email',AppBundle\Services\Adapters\RepositoryServiceAdapter::class)
->serArguments([new Reference('doctrine'),AppBundle\Entity\ContactEmail::class]);
With Inheritance
Same step 1 mentioned above
Extend the RepositoryServiceAdapter class for example:
namespace AppBundle\Service\Adapters;
use Doctrine\ORM\EntityManagerInterface;
use AppBundle\Entity\ContactEmail;
class ContactEmailRepositoryServiceAdapter extends RepositoryServiceAdapter
{
public function __construct(EntityManagerInterface $entityManager)
{
parent::__construct($entityManager,ContactEmail::class);
}
}
Register service:
$container->register('ellakcy.db.contact_email',AppBundle\Services\Adapters\RepositoryServiceAdapter::class)
->serArguments([new Reference('doctrine')]);
Either the case you have a good testable way to function tests your database beavior also it aids you on mocking in case you want to unit test your service without the need to worry too much on how to do that. For example, let us suppose we have the following service:
//Namespace definitions etc etc
class MyDummyService
{
public function __construct(RepositoryServiceAdapter $adapter)
{
//Do stuff
}
}
And the RepositoryServiceAdapter adapts the following repository:
//Namespace definitions etc etc
class SomeRepository extends \Doctrine\ORM\EntityRepository
{
public function search($params)
{
//Search Logic
}
}
Testing
So you can easily mock/hardcode/emulate the behavior of the method search defined in SomeRepository by mocking aither the RepositoryServiceAdapter in non-inheritance approach or the ContactEmailRepositoryServiceAdapter in the inheritance one.
The Factory Approach
Alternatively you can define the following factory:
namespace AppBundle\ServiceFactories;
use Doctrine\ORM\EntityManagerInterface;
class RepositoryFactory
{
/**
* #param EntityManagerInterface $entityManager The doctrine entity Manager
* #param String $entityName The name of the entity
* #return Class
*/
public static function repositoryAsAService(EntityManagerInterface $entityManager,$entityName)
{
return $entityManager->getRepository($entityName);
}
}
And then Switch to php service annotation by doing the following:
Place this into a file ./app/config/services.php (for symfony v3.4, . is assumed your ptoject's root)
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;
$definition = new Definition();
$definition->setAutowired(true)->setAutoconfigured(true)->setPublic(false);
// $this is a reference to the current loader
$this->registerClasses($definition, 'AppBundle\\', '../../src/AppBundle/*', '../../src/AppBundle/{Entity,Repository,Tests,Interfaces,Services/Adapters/RepositoryServiceAdapter.php}');
$definition->addTag('controller.service_arguments');
$this->registerClasses($definition, 'AppBundle\\Controller\\', '../../src/AppBundle/Controller/*');
And cange the ./app/config/config.yml (. is assumed your ptoject's root)
imports:
- { resource: parameters.yml }
- { resource: security.yml }
#Replace services.yml to services.php
- { resource: services.php }
#Other Configuration
Then you can clace the service as follows (used from my example where I used a Dummy entity named Item):
$container->register(ItemRepository::class,ItemRepository::class)
->setFactory([new Reference(RepositoryFactory::class),'repositoryAsAService'])
->setArguments(['$entityManager'=>new Reference('doctrine.orm.entity_manager'),'$entityName'=>Item::class]);
Also as a generic tip, switching to php service annotation allows you to do trouble-free more advanced service configuration thin one above. For code snippets use a special repository I made using the factory method.
For Symfony 5 it is really simple, without need of services.yml to inject the dependency:
inject the Entity Manager in the service constructor
private $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
Then get the repository :
$this->em->getRepository(ClassName::class)
by replacing ClassName with your entity name.

How to inject a service in another service in Symfony?

I am trying to use the logging service in another service in order to trouble shoot that service.
My config.yml looks like this:
services:
userbundle_service:
class: Main\UserBundle\Controller\UserBundleService
arguments: [#security.context]
log_handler:
class: %monolog.handler.stream.class%
arguments: [ %kernel.logs_dir%/%kernel.environment%.jini.log ]
logger:
class: %monolog.logger.class%
arguments: [ jini ]
calls: [ [pushHandler, [#log_handler]] ]
This works fine in controllers etc. however I get no out put when I use it in other services.
Any tips?
You pass service id as argument to constructor or setter of a service.
Assuming your other service is the userbundle_service:
userbundle_service:
class: Main\UserBundle\Controller\UserBundleService
arguments: [#security.context, #logger]
Now Logger is passed to UserBundleService constructor provided you properly update it, e.G.
protected $securityContext;
protected $logger;
public function __construct(SecurityContextInterface $securityContext, Logger $logger)
{
$this->securityContext = $securityContext;
$this->logger = $logger;
}
For Symfony 3.3, 4.x, 5.x and above, the easiest solution is to use Dependency Injection
You can directly inject the service into another service, (say MainService)
// AppBundle/Services/MainService.php
// 'serviceName' is the service we want to inject
public function __construct(\AppBundle\Services\serviceName $injectedService) {
$this->injectedService = $injectedService;
}
Then simply, use the injected service in any method of the MainService as
// AppBundle/Services/MainService.php
public function mainServiceMethod() {
$this->injectedService->doSomething();
}
And viola! You can access any function of the Injected Service!
For older versions of Symfony where autowiring does not exist -
// services.yml
services:
\AppBundle\Services\MainService:
arguments: ['#injectedService']
More versatile option, is to once create a trait for the class you would want to be injected. For instance:
Traits/SomeServiceTrait.php
Trait SomeServiceTrait
{
protected SomeService $someService;
/**
* #param SomeService $someService
* #required
*/
public function setSomeService(SomeService $someService): void
{
$this->someService = $someService;
}
}
And where you need some service:
class AnyClassThatNeedsSomeService
{
use SomeServiceTrait;
public function getSomethingFromSomeService()
{
return $this->someService->something();
}
}
The class will autoload due to #required annotation. This generaly makes it much faster to implement when you want to inject services into numerous classes (like event handlers).

Categories