开发者

How to access services inside non-controller function in Symfony 2

You may access the (let's say) Doctrine service inside the controller, using:

$d = $this->getDoctrine()

now I want my controller to call another function (in another class开发者_运维问答) and I want that class to have access to all services. Is that possible without passing the services as variable?


You have to inject dependent services to your class or method. If you were thinking about some global object you might access everywhere than it's not the right way to go (and you can't actually access the container this way). You'd miss the whole point of dependency injection.

You can inject the services to your class two ways:

  • Manually
  • Let DIC do it

First solution requires you to pass the dependency yourself either way (constructor, setter, method).

The later solution means you define your class as a service and let container construct it and inject the dependencies. It can only be done if you can delegate object creation to DIC. It cannot be done with Entities for example.

Be careful with injecting whole container. It's not the best practice. You'd introduce dependency on a whole container which might have different services depending on the configuration. Dependencies wouldn't be clear.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜