I am trying to build a basic REST client in PHP as a way to make myself familiar with the concept of dependency injection container. Ultimately, I would like to do something like:
$client = new RestClient();
$client->getService('user', array('id, optional fields...'));
But I also want to be able to specify which object should handle the request (if I want to use fopen instead of curl, for instance).
According to what I’ve read so far, a proper way to achieve this would be:
$request = new ServiceDefinition(
'Curl',
array('...')
);
$user = new ServiceDefinition('User',
array(new ServiceReference('request'))
);
$container = new ServiceContainer(array(
'request' => $request,
'user' => $user,
));
My question is: is there a simpler way to build the dependency between the user object and the request object ? (a basic setter injection on RestClient(), maybe ?)
Thanks in advance.
Depending on your existing familiarity with Dependency Injection, using a DI container may be jumping in at the deep end. In short, it’s certainly possible to substitute the container with simple setter injection:
Fabien Potencier has a good series on DI, the second part of which covers DI containers (and when to use them).