A
A
Artem2016-10-31 15:23:59
PHP
Artem, 2016-10-31 15:23:59

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;
    }
}

There is a class of the controller itself:
class UserController
{
    public function index()
    {
        return 1;
    }
}

I want to use the Twig template engine in the UserController class. The template engine object resides in the $app object. How do I pass $app to UserController? Or am I doing something wrong, since there is no solution out of the box?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Artem, 2016-10-31
@artymail

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
        ));
    }
}

A
Alexander Kubintsev, 2016-10-31
@akubintsev

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 question

Ask a Question

731 491 924 answers to any question