Skip to content

Instantly share code, notes, and snippets.

@tzkmx
Created June 7, 2016 14:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tzkmx/cbae68e3627a451db41303651f16b234 to your computer and use it in GitHub Desktop.
Save tzkmx/cbae68e3627a451db41303651f16b234 to your computer and use it in GitHub Desktop.
Inject services from Pimple Container in Controller arguments
<?php
namespace Controller;
use Silex\ControllerResolver as SilexControllerResolver;
use Symfony\Component\HttpFoundation\Request;
use \Pimple;
/**
* Extension of Silex\ControllerResolver, as that injects Application class if
* its requested by Controller by Typehinting; this looks for, and injects,
* services with same name as parameter argument and validates is the right
* class of the service.
*
* Example:
* You have a service, say a DBAL\Connection; accesible at $app['db'];
* Then you can inject it to your Controller, Typehinting and naming a parameter
* same Type as your Service, same name as the key in the ArrayAccess Object.
* // use Doctrine\DBAL\Connection;
* Class TestNameInjection
* {
* public function indexAction(Connection $db){
* return new Response("OK");
* }
* }
* This implementation is linked to the getArguments call of the
* ControllerResolver to load your Controller. Register it like this:
* $container['resolver'] = $container->share(function($container) {
* new Controller\ControllerResolver($container);
* });
* @author Jesus E. Franco Martinez <jefrancomix@gmail.com>
*/
class ControllerResolver extends SilexControllerResolver
{
public function __construct(Pimple $c)
{
$this->app = $c;
}
protected function doGetArguments(Request $request, $controller, array $parameters)
{
$keys = $this->app->keys();
foreach ($parameters as $param) {
if($param->getClass() != null && in_array($param->name, $keys)) {
$this->lookupInContainer($param, $request);
}
}
return parent::doGetArguments($request, $controller, $parameters);
}
private function lookupInContainer(\ReflectionParameter $param, Request $request)
{
$name = $param->name;
$class = $param->getClass();
$maybeObject = $this->app[$name];
if(is_object($maybeObject) && $class->isInstance($maybeObject)) {
$request->attributes->set($name, $maybeObject);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment