usage.rst 2.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. Usage
  2. =====
  3. Non-Controller Classes
  4. ----------------------
  5. Non-controller classes are configured, and managed by Symfony's DIC just like any
  6. other service that you configure using YML, XML, or PHP. The only difference is
  7. that you can do it via annotations which is a lot more convenient.
  8. You can use these annotations on services (for examples, see below):
  9. @Service, @Inject, @InjectParams, @Observe, @Tag
  10. Note that you cannot use the @Inject annotation on private, or protected properties.
  11. Likewise, the @InjectParams annotation does not work on protected, or private methods.
  12. Controllers
  13. -----------
  14. Controllers are a special type of class which is also treated specially by this
  15. bundle. The most notable difference is that you do not need to define these
  16. classes as services. Yes, no services, but don't worry you can still use all of
  17. the DIC's features, and even some more.
  18. Constructor/Setter Injection
  19. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  20. .. code-block :: php
  21. <?php
  22. use JMS\DiExtraBundle\Annotation as DI;
  23. class Controller
  24. {
  25. private $em;
  26. private $session;
  27. /**
  28. * @DI\InjectParams({
  29. * "em" = @DI\Inject("doctrine.orm.entity_manager"),
  30. * "session" = @DI\Inject("session")
  31. * })
  32. */
  33. public function __construct($em, $session)
  34. {
  35. $this->em = $em;
  36. $this->session = $session;
  37. }
  38. // ... some actions
  39. }
  40. .. note ::
  41. Constructor Injection is not possible when a parent definition
  42. also defines a constructor which is configured for injection.
  43. Property Injection
  44. ~~~~~~~~~~~~~~~~~~
  45. .. code-block :: php
  46. <?php
  47. use JMS\DiExtraBundle\Annotation as DI;
  48. class Controller
  49. {
  50. /** @DI\Inject("doctrine.orm.entity_manager") */
  51. private $em;
  52. /** @DI\Inject("session") */
  53. private $session;
  54. }
  55. .. note ::
  56. Injecting into private, or protected properties is only supported on controllers.
  57. Method/Getter Injection
  58. ~~~~~~~~~~~~~~~~~~~~~~~
  59. .. code-block :: php
  60. <?php
  61. use JMS\DiExtraBundle\Annotation as DI;
  62. class Controller
  63. {
  64. public function myAction()
  65. {
  66. // ...
  67. if ($condition) {
  68. $mailer = $this->getMailer();
  69. }
  70. }
  71. /** @DI\LookupMethod("mailer") */
  72. protected function getMailer() { /* empty body here */ }
  73. }
  74. You can use this type of injection if you have a dependency that you do not
  75. always need in the controller, and which is costly to initialize, like the
  76. mailer in the example above.