PageRenderTime 47ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/api/vendor/guzzle/guzzle/docs/webservice-client/using-the-service-builder.rst

https://gitlab.com/x33n/respond
ReStructuredText | 316 lines | 244 code | 72 blank | 0 comment | 0 complexity | 6f75a767df1bf01f8a8d13638011677b MD5 | raw file
  1. =======================
  2. Using a service builder
  3. =======================
  4. The best way to instantiate Guzzle web service clients is to let Guzzle handle building the clients for you using a
  5. ServiceBuilder. A ServiceBuilder is responsible for creating concrete client objects based on configuration settings
  6. and helps to manage credentials for different environments.
  7. You don't have to use a service builder, but they help to decouple your application from concrete classes and help to
  8. share configuration data across multiple clients. Consider the following example. Here we are creating two clients that
  9. require the same API public key and secret key. The clients are created using their ``factory()`` methods.
  10. .. code-block:: php
  11. use MyService\FooClient;
  12. use MyService\BarClient;
  13. $foo = FooClient::factory(array(
  14. 'key' => 'abc',
  15. 'secret' => '123',
  16. 'custom' => 'and above all'
  17. ));
  18. $bar = BarClient::factory(array(
  19. 'key' => 'abc',
  20. 'secret' => '123',
  21. 'custom' => 'listen to me'
  22. ));
  23. The redundant specification of the API keys can be removed using a service builder.
  24. .. code-block:: php
  25. use Guzzle\Service\Builder\ServiceBuilder;
  26. $builder = ServiceBuilder::factory(array(
  27. 'services' => array(
  28. 'abstract_client' => array(
  29. 'params' => array(
  30. 'key' => 'abc',
  31. 'secret' => '123'
  32. )
  33. ),
  34. 'foo' => array(
  35. 'extends' => 'abstract_client',
  36. 'class' => 'MyService\FooClient',
  37. 'params' => array(
  38. 'custom' => 'and above all'
  39. )
  40. ),
  41. 'bar' => array(
  42. 'extends' => 'abstract_client',
  43. 'class' => 'MyService\FooClient',
  44. 'params' => array(
  45. 'custom' => 'listen to me'
  46. )
  47. )
  48. )
  49. ));
  50. $foo = $builder->get('foo');
  51. $bar = $builder->get('bar');
  52. You can make managing your API keys even easier by saving the service builder configuration in a JSON format in a
  53. .json file.
  54. Creating a service builder
  55. --------------------------
  56. A ServiceBuilder can source information from an array, an PHP include file that returns an array, or a JSON file.
  57. .. code-block:: php
  58. use Guzzle\Service\Builder\ServiceBuilder;
  59. // Source service definitions from a JSON file
  60. $builder = ServiceBuilder::factory('services.json');
  61. Sourcing data from an array
  62. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  63. Data can be source from a PHP array. The array must contain an associative ``services`` array that maps the name of a
  64. client to the configuration information used by the service builder to create the client. Clients are given names
  65. which are used to identify how a client is retrieved from a service builder. This can be useful for using multiple
  66. accounts for the same service or creating development clients vs. production clients.
  67. .. code-block:: php
  68. $services = array(
  69. 'includes' => array(
  70. '/path/to/other/services.json',
  71. '/path/to/other/php_services.php'
  72. ),
  73. 'services' => array(
  74. 'abstract.foo' => array(
  75. 'params' => array(
  76. 'username' => 'foo',
  77. 'password' => 'bar'
  78. )
  79. ),
  80. 'bar' => array(
  81. 'extends' => 'abstract.foo',
  82. 'class' => 'MyClientClass',
  83. 'params' => array(
  84. 'other' => 'abc'
  85. )
  86. )
  87. )
  88. );
  89. A service builder configuration array contains two top-level array keys:
  90. +------------+---------------------------------------------------------------------------------------------------------+
  91. | Key | Description |
  92. +============+=========================================================================================================+
  93. | includes | Array of paths to JSON or PHP include files to include in the configuration. |
  94. +------------+---------------------------------------------------------------------------------------------------------+
  95. | services | Associative array of defined services that can be created by the service builder. Each service can |
  96. | | contain the following keys: |
  97. | | |
  98. | | +------------+----------------------------------------------------------------------------------------+ |
  99. | | | Key | Description | |
  100. | | +============+========================================================================================+ |
  101. | | | class | The concrete class to instantiate that implements the | |
  102. | | | | ``Guzzle\Common\FromConfigInterface``. | |
  103. | | +------------+----------------------------------------------------------------------------------------+ |
  104. | | | extends | The name of a previously defined service to extend from | |
  105. | | +------------+----------------------------------------------------------------------------------------+ |
  106. | | | params | Associative array of parameters to pass to the factory method of the service it is | |
  107. | | | | instantiated | |
  108. | | +------------+----------------------------------------------------------------------------------------+ |
  109. | | | alias | An alias that can be used in addition to the array key for retrieving a client from | |
  110. | | | | the service builder. | |
  111. | | +------------+----------------------------------------------------------------------------------------+ |
  112. +------------+---------------------------------------------------------------------------------------------------------+
  113. The first client defined, ``abstract.foo``, is used as a placeholder of shared configuration values. Any service
  114. extending abstract.foo will inherit its params. As an example, this can be useful when clients share the same username
  115. and password.
  116. The next client, ``bar``, extends from ``abstract.foo`` using the ``extends`` attribute referencing the client from
  117. which to extend. Additional parameters can be merged into the original service definition when extending a parent
  118. service.
  119. .. important::
  120. Each client that you intend to instantiate must specify a ``class`` attribute that references the full class name
  121. of the client being created. The class referenced in the ``class`` parameter must implement a static ``factory()``
  122. method that accepts an array or ``Guzzle\Common\Collection`` object and returns an instantiated object.
  123. Sourcing from a PHP include
  124. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  125. You can create service builder configurations using a PHP include file. This can be useful if you wish to take
  126. advantage of an opcode cache like APC to speed up the process of loading and processing the configuration. The PHP
  127. include file is the same format as an array, but you simply create a PHP script that returns an array and save the
  128. file with the .php file extension.
  129. .. code-block:: php
  130. <?php return array('services' => '...');
  131. // Saved as config.php
  132. This configuration file can then be used with a service builder.
  133. .. code-block:: php
  134. $builder = ServiceBuilder::factory('/path/to/config.php');
  135. Sourcing from a JSON document
  136. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  137. You can use JSON documents to serialize your service descriptions. The JSON format uses the exact same structure as
  138. the PHP array syntax, but it's just serialized using JSON.
  139. .. code-block:: javascript
  140. {
  141. "includes": ["/path/to/other/services.json", "/path/to/other/php_services.php"],
  142. "services": {
  143. "abstract.foo": {
  144. "params": {
  145. "username": "foo",
  146. "password": "bar"
  147. }
  148. },
  149. "bar": {
  150. "extends": "abstract.foo",
  151. "class": "MyClientClass",
  152. "params": {
  153. "other": "abc"
  154. }
  155. }
  156. }
  157. }
  158. Referencing other clients in parameters
  159. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  160. If one of your clients depends on another client as one of its parameters, you can reference that client by name by
  161. enclosing the client's reference key in ``{}``.
  162. .. code-block:: javascript
  163. {
  164. "services": {
  165. "token": {
  166. "class": "My\Token\TokenFactory",
  167. "params": {
  168. "access_key": "xyz"
  169. }
  170. },
  171. "client": {
  172. "class": "My\Client",
  173. "params": {
  174. "token_client": "{token}",
  175. "version": "1.0"
  176. }
  177. }
  178. }
  179. }
  180. When ``client`` is constructed by the service builder, the service builder will first create the ``token`` service
  181. and then inject the token service into ``client``'s factory method in the ``token_client`` parameter.
  182. Retrieving clients from a service builder
  183. -----------------------------------------
  184. Clients are referenced using a customizable name you provide in your service definition. The ServiceBuilder is a sort
  185. of multiton object-- it will only instantiate a client once and return that client for subsequent retrievals. Clients
  186. are retrieved by name (the array key used in the configuration) or by the ``alias`` setting of a service.
  187. Here's an example of retrieving a client from your ServiceBuilder:
  188. .. code-block:: php
  189. $client = $builder->get('foo');
  190. // You can also use the ServiceBuilder object as an array
  191. $client = $builder['foo'];
  192. Creating throwaway clients
  193. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  194. You can get a "throwaway" client (a client that is not persisted by the ServiceBuilder) by passing ``true`` in the
  195. second argument of ``ServiceBuilder::get()``. This allows you to create a client that will not be returned by other
  196. parts of your code that use the service builder. Instead of passing ``true``, you can pass an array of configuration
  197. settings that will override the configuration settings specified in the service builder.
  198. .. code-block:: php
  199. // Get a throwaway client and overwrite the "custom" setting of the client
  200. $foo = $builder->get('foo', array(
  201. 'custom' => 'in this world there are rules'
  202. ));
  203. Getting raw configuration settings
  204. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  205. You can get the raw configuration settings provided to the service builder for a specific service using the
  206. ``getData($name)`` method of a service builder. This method will null if the service was not found in the service
  207. builder or an array of configuration settings if the service was found.
  208. .. code-block:: php
  209. $data = $builder->getData('foo');
  210. echo $data['key'] . "\n";
  211. echo $data['secret'] . "\n";
  212. echo $data['custom'] . "\n";
  213. Adding a plugin to all clients
  214. ------------------------------
  215. You can add a plugin to all clients created by a service builder using the ``addGlobalPlugin($plugin)`` method of a
  216. service builder and passing a ``Symfony\Component\EventDispatcher\EventSubscriberInterface`` object. The service builder
  217. will then attach each global plugin to every client as it is created. This allows you to, for example, add a LogPlugin
  218. to every request created by a service builder for easy debugging.
  219. .. code-block:: php
  220. use Guzzle\Plugin\Log\LogPlugin;
  221. // Add a debug log plugin to every client as it is created
  222. $builder->addGlobalPlugin(LogPlugin::getDebugPlugin());
  223. $foo = $builder->get('foo');
  224. $foo->get('/')->send();
  225. // Should output all of the data sent over the wire
  226. .. _service-builder-events:
  227. Events emitted from a service builder
  228. -------------------------------------
  229. A ``Guzzle\Service\Builder\ServiceBuilder`` object emits the following events:
  230. +-------------------------------+--------------------------------------------+-----------------------------------------+
  231. | Event name | Description | Event data |
  232. +===============================+============================================+=========================================+
  233. | service_builder.create_client | Called when a client is created | * client: The created client object |
  234. +-------------------------------+--------------------------------------------+-----------------------------------------+
  235. .. code-block:: php
  236. use Guzzle\Common\Event;
  237. use Guzzle\Service\Builder\ServiceBuilder;
  238. $builder = ServiceBuilder::factory('/path/to/config.json');
  239. // Add an event listener to print out each client client as it is created
  240. $builder->getEventDispatcher()->addListener('service_builder.create_client', function (Event $e) {
  241. echo 'Client created: ' . get_class($e['client']) . "\n";
  242. });
  243. $foo = $builder->get('foo');
  244. // Should output the class used for the "foo" client