How can I get Request object inside a class in Symfony 2?
php, request, symfony
Solution
In addition to Czechnology's answer, you could also inject the request using a setter method. In services.yml add:
my_service:
class: Acme\DemoBundle\Service\WebserviceUserProvider
scope: request
calls:
- [setRequest , ["@request"]]
Then declare your class like this:
use Symfony\Component\HttpFoundation\Request;
class WebserviceUserProvider implements UserProviderInterface {
private $request;
public function setRequest( Request $request ) {
$this->request = $request;
}
// ...
}
If you have scope widening issues, you could also try injecting the service container and getting the requesting from it. In services declare your service like this:
my_service:
class: Acme\DemoBundle\Service\WebserviceUserProvider
calls:
- [setRequest , ["@service_container"]]
Now just use the container to get the request:
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
class WebserviceUserProvider implements UserProviderInterface {
private $request;
public function setRequest( ContainerInterface $container ) {
$this->request = $container->get('request');
}
// ...
}
Problem
I have a class in Symfony that implements an interface. I need to have $request to have POST params. This is my function: ``` class WebserviceUserProvider implements UserProviderInterface { public function loadUserByUsername($username) { $salt = ""; $roles = ""; // make a call to your webservice here ..... } ... } ``` I can't do this: ``` public function loadUserByUsername($username, Request $request) ``` because i need to implement the interface, and i get this error: FatalErrorException: Compile Error: Declaration of Actas\Gestion\UserBundle\Security\User\WebserviceUserProvider::loadUserByUsername() must be compatible with Symfony\Component\Security\Core\User\UserProviderInterface::loadUserByUsername($username) How can i get the request params? This class is called from login, and i need the password sent by it to use a WebService to authenticate the user. Thank you very much in advance! This is my services.xml in the Bundle: ``` # src/Actas/Gestion/UserBundle/Resources/config/services.yml parameters: webservice_user_provider.class: Actas\Gestion\UserBundle\Security\User\WebserviceUserProvider services: webservice_user_provider: class: "%webservice_user_provider.class%" scope: container calls: - [setServiceContainer , ["@service_container"]] ```