Answer the question
In order to leave comments, you need to log in
How to inject $app object into controller in Silex?
Hello.
I use Silex. There is a controller provider class:
class UserControllerProvider implements ControllerProviderInterface
{
public function connect(Application $app)
{
$user = $app["controllers_factory"];
$user -> get ("/", "App\\Controller\\UserController::index" );
return $user;
}
}
class UserController
{
public function index()
{
return 1;
}
}
Answer the question
In order to leave comments, you need to log in
Actually, I found the answer myself. You need to extend the controller class a bit and you can use $app wherever you want:
use Silex\Application;
class UserController
{
private $app;
public function index ( Application $app )
{
$this -> app = $app;
return $this -> app['twig']->render('user.twig', array(
'user' => 1
));
}
}
I automated this process a little through kernel events
$app->on(KernelEvents::CONTROLLER, function (FilterControllerEvent $event) use ($app) {
$c = $event->getController();
/** @var BaseController $controller */
$controller = $c[0];
if ($controller instanceof BaseController) {
$controller->injectApp($app);
}
});
abstract class BaseController
{
protected $app;
public function injectApp(Application $app)
{
$this->app = $app;
return $this;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question