I have a problem with my PHPUnit test on symfony2. To connect to my application, I use a web service, so I created a UserProvider. In my function
loadUserByUsername I use symfony2 parameters saved in
app/config/parameters.yml. As I'm not in a controller I need to use the global variable
$kernel and get my args like this :
$url = $kernel->getContainer()-getParameter('myparam');
When I use my application, it works, but when I write my test like this :
$crawler = $client->request('GET', '/login');
$form = $crawler->selectButton('submit')->form();
$form['_username'] = $username;
$form['_password'] = $pass;
and execute PHPUnit I get this error :
Fatal error : Call to a member function getContainer()
How can I access symfony2 parameters or use getContainer when I execute PHPUnit ?
Best How To :
In the Symfony documentation How to Create a custom UserProvider, under 'Create a Service for the User Provider' it states:
The real implementation of the user provider will probably have some dependencies or configuration options or other services. Add these as arguments in the service definition.
So, rather than using a global $kernel variable you should be passing the relevant parameters into your user provider service by defining them as arguments in the service definition. For example:
arguments: [%parameter_one%, %parameter_two%, ...]
As with any service, your user provider service class must then have a constructor which takes arguments corresponding to those in the service definition and stores them in private variables for use in the service's methods:
class WebserviceUserProvider implements UserProviderInterface
public function __construct($parameterOne, ...)
$this->parameterOne = $parameterOne;
I've been writing Symfony apps for four years and I've never need to use the global $kernel variable. I daresay there may be valid circumstances but in general I'd say it's to be avoided.