获取 Silex\Application 的实例
我正在使用 Silex 创建一个应用程序,并且想知道是否可以以某种方式获取 的实例Silex\Application
位于我无法在方法参数中执行 method_name(Application $application)
的地方?
例如,假设我在控制器上有一个不是操作的私有方法。如果我将 Application $application
作为参数,它会抛出一个错误,指出我需要传递它。
如果不需要,我宁愿不必手动传递该方法。
I am creating an application with Silex and was wondering if it is possible to somehow get the instance of the Silex\Application
in a place where I can't do method_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 put Application $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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
实际上只有两种方法可以做到这一点。
a) 将
Silex\Application
作为参数传递给类的构造函数,并将其分配为实例变量。b) 将
Silex\Application
作为参数手动传递给您的私有方法。您确定您的班级需要完整的应用程序吗?依赖注入的要点是直接注入依赖,而不是注入容器(是的,Silex\Application扩展了
\Pimple
,它是一个依赖注入容器。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.根据您对其他答案的评论,您访问 Silex/Application 的目标是访问那里的 Twig 服务。我解决在 Silex 项目的另一个函数中获取当前应用程序的方法是:
作为路由端点的每个函数都会将传递给它的应用程序保存为类属性,以供其他函数获取。这意味着您必须记住在每个使用
doAwesome()
的函数中执行$this->a = $a;
(在调用之前doAwesome()
),但这是我想出的解决这个问题的最干净的方法。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.