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