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.
Answer
Solution:
There's really only two ways to do it.
a) Pass
Silex\Application
as an argument to the constructor of your class and assign it as an instance variable.b) Pass the
Silex\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.Answer
Solution:
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:
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.