php - Getting Instance Of SilexApplication


I am creating an application with Silex and was wondering if it is possible to somehow get the instance of theSilex\Application in a place where I can't domethod_name(Application $application) in the method parameters?

For example, say I have a private method on a controller that is not an action. If I putApplication $application as the parameter, it throws an error saying I need to pass it in.

I would rather not have to manually pass that method in if I don't have to.




There's really only two ways to do it.

a) PassSilex\Application as an argument to the constructor of your class and assign it as an instance variable.

b) Pass theSilex\Application to your private method as an argument by hand.

Are you sure you need the full app in your class? The point of dependency injection is to inject dependencies directly, instead of injecting the container (yes,Silex\Application extends\Pimple, which is a Dependency Injection Container.




From your comment on the other answer, your goal of getting at the Silex/Application is to get at the Twig service there. The way that I've solved getting at the current application in another function for my Silex projects is:

use \Silex\Application;
use \Symfony\Component\HttpFoundation\Request;

class myController {
  private $a;

  // Route defined as:
  // $app->get('/foo', 'myController::showPage');
  public function showPage(Application $a) {
    $this->a = $a;
    return $this->doAwesome();

  private function doAwesome() {
    $twig = $this->a['twig'];
    return $twig->render('awesomePage.twig');

Every function that is an endpoint for a route would then save the Application passed to it as a class property, for other functions to get at. It means you have to remember to do$this->a = $a; in every function that usesdoAwesome() (before callingdoAwesome()), but that's the cleanest way I've come up with to tackle that.

People are also looking for solutions to the problem: how to write a php embed code that calls another php in a html page


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.