README.rst 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. Pimple
  2. ======
  3. .. caution::
  4. This is the documentation for Pimple 3.x. If you are using Pimple 1.x, read
  5. the `Pimple 1.x documentation`_. Reading the Pimple 1.x code is also a good
  6. way to learn more about how to create a simple Dependency Injection
  7. Container (recent versions of Pimple are more focused on performance).
  8. Pimple is a small Dependency Injection Container for PHP.
  9. Installation
  10. ------------
  11. Before using Pimple in your project, add it to your ``composer.json`` file:
  12. .. code-block:: bash
  13. $ ./composer.phar require pimple/pimple "^3.0"
  14. Usage
  15. -----
  16. Creating a container is a matter of creating a ``Container`` instance:
  17. .. code-block:: php
  18. use Pimple\Container;
  19. $container = new Container();
  20. As many other dependency injection containers, Pimple manages two different
  21. kind of data: **services** and **parameters**.
  22. Defining Services
  23. ~~~~~~~~~~~~~~~~~
  24. A service is an object that does something as part of a larger system. Examples
  25. of services: a database connection, a templating engine, or a mailer. Almost
  26. any **global** object can be a service.
  27. Services are defined by **anonymous functions** that return an instance of an
  28. object:
  29. .. code-block:: php
  30. // define some services
  31. $container['session_storage'] = function ($c) {
  32. return new SessionStorage('SESSION_ID');
  33. };
  34. $container['session'] = function ($c) {
  35. return new Session($c['session_storage']);
  36. };
  37. Notice that the anonymous function has access to the current container
  38. instance, allowing references to other services or parameters.
  39. As objects are only created when you get them, the order of the definitions
  40. does not matter.
  41. Using the defined services is also very easy:
  42. .. code-block:: php
  43. // get the session object
  44. $session = $container['session'];
  45. // the above call is roughly equivalent to the following code:
  46. // $storage = new SessionStorage('SESSION_ID');
  47. // $session = new Session($storage);
  48. Defining Factory Services
  49. ~~~~~~~~~~~~~~~~~~~~~~~~~
  50. By default, each time you get a service, Pimple returns the **same instance**
  51. of it. If you want a different instance to be returned for all calls, wrap your
  52. anonymous function with the ``factory()`` method
  53. .. code-block:: php
  54. $container['session'] = $container->factory(function ($c) {
  55. return new Session($c['session_storage']);
  56. });
  57. Now, each call to ``$container['session']`` returns a new instance of the
  58. session.
  59. Defining Parameters
  60. ~~~~~~~~~~~~~~~~~~~
  61. Defining a parameter allows to ease the configuration of your container from
  62. the outside and to store global values:
  63. .. code-block:: php
  64. // define some parameters
  65. $container['cookie_name'] = 'SESSION_ID';
  66. $container['session_storage_class'] = 'SessionStorage';
  67. If you change the ``session_storage`` service definition like below:
  68. .. code-block:: php
  69. $container['session_storage'] = function ($c) {
  70. return new $c['session_storage_class']($c['cookie_name']);
  71. };
  72. You can now easily change the cookie name by overriding the
  73. ``cookie_name`` parameter instead of redefining the service
  74. definition.
  75. Protecting Parameters
  76. ~~~~~~~~~~~~~~~~~~~~~
  77. Because Pimple sees anonymous functions as service definitions, you need to
  78. wrap anonymous functions with the ``protect()`` method to store them as
  79. parameters:
  80. .. code-block:: php
  81. $container['random_func'] = $container->protect(function () {
  82. return rand();
  83. });
  84. Modifying Services after Definition
  85. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  86. In some cases you may want to modify a service definition after it has been
  87. defined. You can use the ``extend()`` method to define additional code to be
  88. run on your service just after it is created:
  89. .. code-block:: php
  90. $container['session_storage'] = function ($c) {
  91. return new $c['session_storage_class']($c['cookie_name']);
  92. };
  93. $container->extend('session_storage', function ($storage, $c) {
  94. $storage->...();
  95. return $storage;
  96. });
  97. The first argument is the name of the service to extend, the second a function
  98. that gets access to the object instance and the container.
  99. Extending a Container
  100. ~~~~~~~~~~~~~~~~~~~~~
  101. If you use the same libraries over and over, you might want to reuse some
  102. services from one project to the next one; package your services into a
  103. **provider** by implementing ``Pimple\ServiceProviderInterface``:
  104. .. code-block:: php
  105. use Pimple\Container;
  106. class FooProvider implements Pimple\ServiceProviderInterface
  107. {
  108. public function register(Container $pimple)
  109. {
  110. // register some services and parameters
  111. // on $pimple
  112. }
  113. }
  114. Then, register the provider on a Container:
  115. .. code-block:: php
  116. $pimple->register(new FooProvider());
  117. Fetching the Service Creation Function
  118. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  119. When you access an object, Pimple automatically calls the anonymous function
  120. that you defined, which creates the service object for you. If you want to get
  121. raw access to this function, you can use the ``raw()`` method:
  122. .. code-block:: php
  123. $container['session'] = function ($c) {
  124. return new Session($c['session_storage']);
  125. };
  126. $sessionFunction = $container->raw('session');
  127. PSR-11 compatibility
  128. --------------------
  129. For historical reasons, the ``Container`` class does not implement the PSR-11
  130. ``ContainerInterface``. However, Pimple provides a helper class that will let
  131. you decouple your code from the Pimple container class.
  132. The PSR-11 container class
  133. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  134. The ``Pimple\Psr11\Container`` class lets you access the content of an
  135. underlying Pimple container using ``Psr\Container\ContainerInterface``
  136. methods:
  137. .. code-block:: php
  138. use Pimple\Container;
  139. use Pimple\Psr11\Container as PsrContainer;
  140. $container = new Container();
  141. $container['service'] = function ($c) {
  142. return new Service();
  143. };
  144. $psr11 = new PsrContainer($container);
  145. $controller = function (PsrContainer $container) {
  146. $service = $container->get('service');
  147. };
  148. $controller($psr11);
  149. Using the PSR-11 ServiceLocator
  150. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  151. Sometimes, a service needs access to several other services without being sure
  152. that all of them will actually be used. In those cases, you may want the
  153. instantiation of the services to be lazy.
  154. The traditional solution is to inject the entire service container to get only
  155. the services really needed. However, this is not recommended because it gives
  156. services a too broad access to the rest of the application and it hides their
  157. actual dependencies.
  158. The ``ServiceLocator`` is intended to solve this problem by giving access to a
  159. set of predefined services while instantiating them only when actually needed.
  160. It also allows you to make your services available under a different name than
  161. the one used to register them. For instance, you may want to use an object
  162. that expects an instance of ``EventDispatcherInterface`` to be available under
  163. the name ``event_dispatcher`` while your event dispatcher has been
  164. registered under the name ``dispatcher``:
  165. .. code-block:: php
  166. use Monolog\Logger;
  167. use Pimple\Psr11\ServiceLocator;
  168. use Psr\Container\ContainerInterface;
  169. use Symfony\Component\EventDispatcher\EventDispatcher;
  170. class MyService
  171. {
  172. /**
  173. * "logger" must be an instance of Psr\Log\LoggerInterface
  174. * "event_dispatcher" must be an instance of Symfony\Component\EventDispatcher\EventDispatcherInterface
  175. */
  176. private $services;
  177. public function __construct(ContainerInterface $services)
  178. {
  179. $this->services = $services;
  180. }
  181. }
  182. $container['logger'] = function ($c) {
  183. return new Monolog\Logger();
  184. };
  185. $container['dispatcher'] = function () {
  186. return new EventDispatcher();
  187. };
  188. $container['service'] = function ($c) {
  189. $locator = new ServiceLocator($c, array('logger', 'event_dispatcher' => 'dispatcher'));
  190. return new MyService($locator);
  191. };
  192. Referencing a Collection of Services Lazily
  193. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  194. Passing a collection of services instances in an array may prove inefficient
  195. if the class that consumes the collection only needs to iterate over it at a
  196. later stage, when one of its method is called. It can also lead to problems
  197. if there is a circular dependency between one of the services stored in the
  198. collection and the class that consumes it.
  199. The ``ServiceIterator`` class helps you solve these issues. It receives a
  200. list of service names during instantiation and will retrieve the services
  201. when iterated over:
  202. .. code-block:: php
  203. use Pimple\Container;
  204. use Pimple\ServiceIterator;
  205. class AuthorizationService
  206. {
  207. private $voters;
  208. public function __construct($voters)
  209. {
  210. $this->voters = $voters;
  211. }
  212. public function canAccess($resource)
  213. {
  214. foreach ($this->voters as $voter) {
  215. if (true === $voter->canAccess($resource) {
  216. return true;
  217. }
  218. }
  219. return false;
  220. }
  221. }
  222. $container = new Container();
  223. $container['voter1'] = function ($c) {
  224. return new SomeVoter();
  225. }
  226. $container['voter2'] = function ($c) {
  227. return new SomeOtherVoter($c['auth']);
  228. }
  229. $container['auth'] = function ($c) {
  230. return new AuthorizationService(new ServiceIterator($c, array('voter1', 'voter2'));
  231. }
  232. .. _Pimple 1.x documentation: https://github.com/silexphp/Pimple/tree/1.1