README.rst 9.6 KB

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