Silex Application Walkthrough and Request for Controller Classes

I need an easy way to access $ app and $ request in my controller classes. The document says to do this,

public function action(Application $app, Request $request) { // Do something. } 

but it doesn't make sense to enter $ app and $ request for each method. Is there a way to enable $ app and $ request for each controller by default, possibly using a constructor? I would like to use it as a $ this-> app.

Thanks.

+7
silex
source share
2 answers

In the Controllers as Services part of the documentation, you can see how to add dependencies to controller classes through the constructor - in this case, the repository.

+3
source share

Maybe:

Create ControllerResolver.php somewhere in your project and put this inside:

 namespace MyProject; use Silex\ControllerResolver as BaseControllerResolver; class ControllerResolver extends BaseControllerResolver { protected function instantiateController($class) { return new $class($this->app); } } 

Then register it in your application (up to $app->run(); ):

 $app['resolver'] = function ($app) { return new \MyProject\ControllerResolver($app, $app['logger']); }; 

Now you can create a basic controller for your application, for example:

 namespace MyProject; use Silex\Application; use Symfony\Component\HttpFoundation\Response; abstract class BaseController { public $app; public function __construct(Application $app) { $this->app = $app; } public function getParam($key) { $postParams = $this->app['request_stack']->getCurrentRequest()->request->all(); $getParams = $this->app['request_stack']->getCurrentRequest()->query->all(); if (isset($postParams[$key])) { return $postParams[$key]; } elseif (isset($getParams[$key])) { return $getParams[$key]; } else { return null; } } public function render($view, array $parameters = array()) { $response = new Response(); return $response->setContent($this->app['twig']->render($view, $parameters)); } } 

And expand it:

 class HomeController extends BaseController { public function indexAction() { // now you can use $this->app return $this->render('home.html.twig'); } } 
0
source share

All Articles