I have a problem with my application after I moved it to docker container. I newbie with Symfony and I cannot understand where the problem is.
After I want to call my UserController index action my browser throws an error:
Controller "App\Controller\UserController" has required constructor arguments and does not exist in the container. Did you forget to define such a service?
Too few arguments to function App\Controller\UserController::__construct(), 0 passed in /projekty/taskit/vendor/symfony/http-kernel/Controller/ControllerResolver.php on line 133 and exactly 1 expected
My services.yaml file:
parameters:
locale: 'en'
services:
# default configuration for services in *this* file
_defaults:
autowire: true # Automatically injects dependencies in your services.
autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
public: false # Allows optimizing the container by removing unused services; this also means
# fetching services directly from the container via $container->get() won't work.
# The best practice is to be explicit about your dependencies anyway.
# makes classes in src/ available to be used as services
# this creates a service per class whose id is the fully-qualified class name
App\:
resource: '../src/*'
exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}'
# controllers are imported separately to make sure services can be injected
# as action arguments even if you don't extend any base controller class
App\Controller\:
resource: '../src/Controller'
tags: ['controller.service_arguments']
# add more service definitions when explicit configuration is needed
# please note that last definitions always *replace* previous ones
App\Entity\UserRepositoryInterface: '#App\DTO\UserAssembler'
UserController.php file
<?php
namespace App\Controller;
use App\Service\UserService;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
/**
* Class UserController
* #package App\Controller
*/
class UserController extends AbstractController
{
/**
* #var UserService
*/
private $userService;
/**
* #param UserService $userService
*/
public function __construct(UserService $userService)
{
$this->userService = $userService;
}
/**
* #Route("/users/", name="users_index")
*/
public function index()
{
$users = $this->userService->findAll();
return $this->render('user/index.html.twig', array('users' => $users));
}
}
And my UserService.php file code
<?php
namespace App\Service;
use App\Entity\UserRepositoryInterface;
use Doctrine\ORM\EntityNotFoundException;
/**
* Class UserService
* #package App\Service
*/
class UserService
{
/**
* #var UserRepositoryInterface
*/
private $userRepository;
/**
* #param UserRepositoryInterface $userRepository
*/
public function __construct(UserRepositoryInterface $userRepository)
{
$this->userRepository = $userRepository;
}
/**
* #return array
* #throws EntityNotFoundException
*/
public function findAll() : array
{
$users = $this->userRepository->findAll();
if (is_null($users)) {
throw new EntityNotFoundException('Table users is empty');
}
return $users;
}
}
It seems to me you are doing a lot of unnecessary things, which are already part of the framework. Like your service, what does it do? You can call your repositories directly from your controller. And in your controller, you are declaring variables and constructing which is also unnecessary. Just use dependency injection in your function in the controller. This little bit of code should work and replace both your controller and your service (which again, you can get rid of).
<?php
namespace App\Controller;
use App\Repository\UserRepository;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
/**
* Class UserController
* #package App\Controller
*/
class UserController extends AbstractController
{
/**
* #Route("/users/", name="users_index")
*/
public function index(UserRepository $userRepository)
{
$users = $this->userRepository->findAll();
return $this->render('user/index.html.twig', array('users' => $users));
}
}
Related
Plea
I have read the "Service Container" entry--and nearly every linked entry--in the Symfony 4 docs. I have tackled this issue on two separate occasions spending 4-6 hours each time. I clearly just don't get it...please help!
Want
I want to use dependency injection to use a service (SessionInterface) in a model (User) but I do not want to use the model constructor as then I would need to inject the dependency each time I hydrate and instantiate the model. I think I should be able to use method call and setter injection to meet this criteria.
Code
services.yaml
services:
_defaults:
autowire: true
autoconfigure: true
public: false
App\:
resource: '../src/*'
exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}'
App\Controller\:
resource: '../src/Controller'
tags: ['controller.service_arguments']
Model
namespace App\Model\System\User;
use App\Model\System\Client\Client;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Security\Core\User\{EquatableInterface, UserInterface};
class User implements EquatableInterface, UserInterface
{
private $session;
public function __construct(array $properties)
{
// stuff
}
public function clientAssumed(): Client
{
return $this->session->get('foo', 'bar');
}
/**
* #required
*
* #param SessionInterface $session
*/
public function setSession(SessionInterface $session)
{
$this->session = $session;
}
}
Controller
namespace App\Controller\Core;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security;
class CoreBase extends AbstractController
{
/**
* Displays authenticated User landing page.
*
* #Route("/home", name="core_home")
*
* #param Security $security
*
* #return Response
*/
public function landing(Security $security): Response
{
$data = [
'client' => $security->getUser()->clientAssumed(),
];
return $this->render('core/landing.html.twig', $data);
}
}
Service Information
php bin/console debug:container 'App\Model\System\User\User'
.
Information for Service "App\Model\System\User\User"
====================================================
---------------- ----------------------------
Option Value
---------------- ----------------------------
Service ID App\Model\System\User\User
Class App\Model\System\User\User
Tags -
Calls setSession
Public no
Synthetic no
Lazy no
Shared yes
Abstract no
Autowired yes
Autoconfigured yes
---------------- ----------------------------
Result
Too few arguments to function App\Model\System\User\User::setSession(), 0 passed in /srv/http/wwwroot/gw4/src/Controller/Core/CoreBase.php on line 25 and exactly 1 expected
I wanted to set password automatically when one register the form. So I use REGISTRATION_INITIALIZE to trigger the event. Unfortunately it's not working.
Listener:
<?php
namespace Acme\UserBundle\EventListener;
use Doctrine\ORM\EntityManager;
use FOS\UserBundle\Event\UserEvent;
use FOS\UserBundle\FOSUserEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class RegistrationListener implements EventSubscriberInterface
{
/**
* #var EntityManager
*/
private $em;
/**
* #param \Doctrine\ORM\EntityManager $entityManager
*/
public function __construct(EntityManager $entityManager)
{
$this->em = $entityManager;
}
/**
* {#inheritdoc}
*/
public static function getSubscribedEvents()
{
return array(
FOSUserEvents::REGISTRATION_INITIALIZE => 'onRegistrationInit',
);
}
public function onRegistrationInit(UserEvent $userEvent)
{
$user = $userEvent->getUser();
$user->setPassword('abcdeffffff');
}
Services:
#src/Acme/UserBundle/Resources/config/services.yml
services:
acme_user.registration:
class: Acme\UserBundle\EventListener\RegistrationListener
arguments:
entityManager: "#doctrine.orm.entity_manager"
tags:
- { name: kernel.event_subscriber}
So the password is not setting and it shows the password should not be blank.
What am I doing wrong? Any help!
EDIT:
The problem was I was defining service at the wrong place.
Instead of src/Acme/UserBundle/Resources/config/services.yml, It should be app/config/services.yml.
I saw src/Acme/UserBundle/Resources/config/services.ymlin http://symfony.com/doc/master/bundles/FOSUserBundle/controller_events.html, But was not working for me!
Maybe I am wrong, but I think your service definition uses features from Symfony 3.3 but you are using Symfony 3.2.8, e.g.
New in version 3.3: The ability to configure an argument by its name ($adminEmail) was added in Symfony 3.3. Previously, you could configure it only by its index (2 in this case) or by using empty quotes for the other arguments.
Try updating your service definition to:
#src/Acme/UserBundle/Resources/config/services.yml
services:
acme_user.registration:
class: Acme\UserBundle\EventListener\RegistrationListener
arguments: ["#doctrine.orm.entity_manager"]
tags:
- { name: kernel.event_subscriber}
And a remark: as you are actually using a subscriber you should rename the class RegistrationListener to RegistrationSubscriber.
I am able to use the new autowire feature of Symfony2 to inject a service into a service. However, I cannot inject a service into a controller. What am I not doing/doing wrong?
This is my services.yml file:
services:
home_controller:
class: AppBundle\Controller\HomeController
autowire: true
This is my ServiceConsumerDemo:
namespace AppBundle\Services;
class ServiceConsumerDemo {
private $serviceDemo;
public function __construct(ServiceDemo $serviceDemo) {
$this->serviceDemo = $serviceDemo;
}
public function getMessage(){
return $this->serviceDemo->helloWorld();
}
}
This is ServiceDemo:
namespace AppBundle\Services;
class ServiceDemo
{
public function helloWorld(){
return "hello, world!";
}
}
This is HomeController (which works):
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
class HomeController extends Controller
{
/**
* #Route("/")
*
*/
public function indexAction(Request $request)
{
$message[0] = $this->get('service_consumer_demo')->getMessage();
return new \Symfony\Component\HttpFoundation\JsonResponse($message);
}
}
This is HomeController which does not work
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use AppBundle\Services\ServiceConsumerDemo;
class HomeController extends Controller
{
private $serviceConsumerDemo;
public function __construct(ServiceConsumerDemo $serviceConsumerDemo) {
$this->serviceConsumerDemo = $serviceConsumerDemo;
}
/**
* #Route("/", name="homepage")
*
*/
public function indexAction(Request $request)
{
$message[0] = $this->serviceConsumerDemo->getMessage();
return new \Symfony\Component\HttpFoundation\JsonResponse($message);
}
}
This is the error thrown:
Catchable Fatal Error: Argument 1 passed to
AppBundle\Controller\HomeController::__construct() must be an instance
of AppBundle\Services\ServiceConsumerDemo, none given,
How do I access the Services in the Controller? I understand I need to declare the controller as a service. So I'm mentioning the controller in the services.yml file. Is there anything else that I need to do?
By default, controllers are not considered as services, so you can't use autowiring with them.
However, it's a simple enough fix - add a #Route annotation on the class (i.e. not on an action method in the class) with a service definition.
From the documentation:
The #Route annotation on a controller class can also be used to assign
the controller class to a service so that the controller resolver will
instantiate the controller by fetching it from the DI container
instead of calling new PostController() itself.
For example:
/**
* #Route(service="app_controller")
*/
class AppController extends Controller
{
private $service;
public function __construct(SomeService $service)
{
$this->service = $service;
}
/** #Route("/") */
public function someAction()
{
$this->service->doSomething();
}
}
and in your config:
app_controller:
class: AppBundle\Controller\AppController
autowire: true
Symfony 3.3+ May 2017 UPDATE!
Symfony 3.3 allows native way to approach this.
# app/config/services.yml
services:
_defaults:
autowire: true # all services in this config are now autowired
App\: # no more manual registration of similar groups of services
resource: ../{Controller}
This means App\Controller\SomeController is autowired by default and to be found in app/Controller/SomeController.php file.
You can read:
more about _defaults here
and more about PSR-4 service registration
Thanks to autowiring in Symfony 2.8+ I could create bundle, that adds autowiring even for controllers: Symplify/ControllerAutowire
You can read more about this in the article.
Usage is as simple as:
class YourController
{
public function __construct(SomeDependency $someDependency)
{
// ...
}
}
Nothing more is required.
You do not pass service to your controller in services.yml. Change it to:
services:
service_demo:
class: AppBundle\Services\ServiceDemo
service_consumer_demo:
class: AppBundle\Services\ServiceConsumerDemo
autowire: true
home_controller:
class: AppBundle\Controller\HomeController
autowire: true
arguments:
service: "#service_consumer_demo"
I am trying to use a custom UserProvider with the FOS User bundle package and the FOS Oauth package. I have been following this tutorial http://blog.tankist.de/blog/2013/07/17/oauth2-explained-part-2-setting-up-oauth2-with-symfony2-using-fosoauthserverbundle/.
When I try and register my new user service I am getting the following error
UserProvider::__construct() must implement interface Doctrine\Common\Persistence\ObjectRepository, array given
UserProvider:
UserProvider implements UserProviderInterface
{
/**
* #var ObjectRepository
*/
protected $userRepository;
/**
* #param ObjectRepository $userRepository
*/
public function __construct(ObjectRepository $userRepository)
{
$this->userRepository = $userRepository;
}
/**
* #param string $username
* #return mixed
*/
public function loadUserByUsername($username)
{ ... }
UserRepository
class UserRepository extends EntityRepository implements ObjectRepository
services.yml
parameters:
entity_name: Hornby\UserBundle\Entity\UserRepository
services:
user_provider_me:
class: Hornby\UserBundle\Provider\UserProvider
arguments:
name: [%entity_name%]
Your services.yml file is wrong. I'm not really sure what you want to achieve but you pass array
arguments:
name: [%entity_name%] #entity_name is just a string
as an argument to UserProvider class. Constructor of this class expects ObjectRepository and this is your problem here.
A translation of services.xml from link you provided should look rather like that:
parameters:
platform.entity.user.class: Acme\DemoBundle\Entity\User
platform.user.provider.class: Acme\DemoBundle\Provider\UserProvider
services:
platform.user.manager:
class: Doctrine\ORM\EntityManager
factory: ["#doctrine", getManagerForClass]
arguments: [%platform.entity.user.class%]
platform.user.repository:
class: Acme\DemoBundle\Repository\UserRepository
factory: ["#platform.user.manager", getRepository]
arguments: [%platform.entity.user.class%]
platform.user.provider:
class: %platform.user.provider.class%
arguments: [#platform.user.repository]
in my services constructor
public function __construct(
EntityManager $entityManager,
SecurityContextInterface $securityContext)
{
$this->securityContext = $securityContext;
$this->entityManager = $entityManager;
I pass entityManager and securityContext as argument.
also my services.xml is here
<service id="acme.memberbundle.calendar_listener" class="Acme\MemberBundle\EventListener\CalendarEventListener">
<argument type="service" id="doctrine.orm.entity_manager" />
<argument type="service" id="security.context" />
but now,I want to use container in services such as
$this->container->get('router')->generate('fos_user_profile_edit')
how can I pass the container to services?
It's easy, if service extends ContainerAware
use \Symfony\Component\DependencyInjection\ContainerAware;
class YouService extends ContainerAware
{
public function someMethod()
{
$this->container->get('router')->generate('fos_user_profile_edit')
...
}
}
service.yml
your.service:
class: App\...\YouService
calls:
- [ setContainer,[ #service_container ] ]
Add:
<argument type="service" id="service_container" />
And in your listener class:
use Symfony\Component\DependencyInjection\ContainerInterface;
//...
public function __construct(ContainerInterface $container, ...) {
It's 2016, you can use trait which will help you extend same class with multiple libraries.
<?php
namespace iBasit\ToolsBundle\Utils\Lib;
use Doctrine\Bundle\DoctrineBundle\Registry;
use Symfony\Component\DependencyInjection\ContainerInterface;
trait Container
{
private $container;
public function setContainer (ContainerInterface $container)
{
$this->container = $container;
}
/**
* Shortcut to return the Doctrine Registry service.
*
* #return Registry
*
* #throws \LogicException If DoctrineBundle is not available
*/
protected function getDoctrine()
{
if (!$this->container->has('doctrine')) {
throw new \LogicException('The DoctrineBundle is not registered in your application.');
}
return $this->container->get('doctrine');
}
/**
* Get a user from the Security Token Storage.
*
* #return mixed
*
* #throws \LogicException If SecurityBundle is not available
*
* #see TokenInterface::getUser()
*/
protected function getUser()
{
if (!$this->container->has('security.token_storage')) {
throw new \LogicException('The SecurityBundle is not registered in your application.');
}
if (null === $token = $this->container->get('security.token_storage')->getToken()) {
return;
}
if (!is_object($user = $token->getUser())) {
// e.g. anonymous authentication
return;
}
return $user;
}
/**
* Returns true if the service id is defined.
*
* #param string $id The service id
*
* #return bool true if the service id is defined, false otherwise
*/
protected function has ($id)
{
return $this->container->has($id);
}
/**
* Gets a container service by its id.
*
* #param string $id The service id
*
* #return object The service
*/
protected function get ($id)
{
if ('request' === $id)
{
#trigger_error('The "request" service is deprecated and will be removed in 3.0. Add a typehint for Symfony\\Component\\HttpFoundation\\Request to your controller parameters to retrieve the request instead.', E_USER_DEPRECATED);
}
return $this->container->get($id);
}
/**
* Gets a container configuration parameter by its name.
*
* #param string $name The parameter name
*
* #return mixed
*/
protected function getParameter ($name)
{
return $this->container->getParameter($name);
}
}
Your object, which will be service.
namespace AppBundle\Utils;
use iBasit\ToolsBundle\Utils\Lib\Container;
class myObject
{
use Container;
}
Your service settings
myObject:
class: AppBundle\Utils\myObject
calls:
- [setContainer, ["#service_container"]]
Call your service in controller
$myObject = $this->get('myObject');
If all your services are ContainerAware, I suggest to create a BaseService class that will contain all common code with your other services.
1) Create the Base\BaseService.php class:
<?php
namespace Fuz\GenyBundle\Base;
use Symfony\Component\DependencyInjection\ContainerAware;
abstract class BaseService extends ContainerAware
{
}
2) Register this service as abstract in your services.yml
parameters:
// ...
geny.base.class: Fuz\GenyBundle\Base\BaseService
services:
// ...
geny.base:
class: %geny.base.class%
abstract: true
calls:
- [setContainer, [#service_container]]
3) Now, in your other services, extends your BaseService class instead of ContainerAware:
<?php
namespace Fuz\GenyBundle\Services;
use Fuz\GenyBundle\Base\BaseService;
class Loader extends BaseService
{
// ...
}
4) Finally, you can use the parent option in your services declaration.
geny.loader:
class: %geny.loader.class%
parent: geny.base
I prefer this way for several reasons:
there is consistency between the code and the config
this avoids duplicating too much config for each service
you have a base class for each services, very helpful for common code