uri-templates.rst 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. =============
  2. URI templates
  3. =============
  4. The ``$uri`` passed to one of the client's request creational methods or the base URL of a client can utilize URI
  5. templates. Guzzle supports the entire `URI templates RFC <http://tools.ietf.org/html/rfc6570>`_. URI templates add a
  6. special syntax to URIs that replace template place holders with user defined variables.
  7. Every request created by a Guzzle HTTP client passes through a URI template so that URI template expressions are
  8. automatically expanded:
  9. .. code-block:: php
  10. $client = new Guzzle\Http\Client('https://example.com/', array('a' => 'hi'));
  11. $request = $client->get('/{a}');
  12. Because of URI template expansion, the URL of the above request will become ``https://example.com/hi``. Notice that
  13. the template was expanded using configuration variables of the client. You can pass in custom URI template variables
  14. by passing the URI of your request as an array where the first index of the array is the URI template and the second
  15. index of the array are template variables that are merged into the client's configuration variables.
  16. .. code-block:: php
  17. $request = $client->get(array('/test{?a,b}', array('b' => 'there')));
  18. The URL for this request will become ``https://test.com?a=hi&b=there``. URI templates aren't limited to just simple
  19. variable replacements; URI templates can provide an enormous amount of flexibility when creating request URIs.
  20. .. code-block:: php
  21. $request = $client->get(array('http://example.com{+path}{/segments*}{?query,data*}', array(
  22. 'path' => '/foo/bar',
  23. 'segments' => array('one', 'two'),
  24. 'query' => 'test',
  25. 'data' => array(
  26. 'more' => 'value'
  27. )
  28. )));
  29. The resulting URL would become ``http://example.com/foo/bar/one/two?query=test&more=value``.
  30. By default, URI template expressions are enclosed in an opening and closing brace (e.g. ``{var}``). If you are working
  31. with a web service that actually uses braces (e.g. Solr), then you can specify a custom regular expression to use to
  32. match URI template expressions.
  33. .. code-block:: php
  34. $client->getUriTemplate()->setRegex('/\<\$(.+)\>/');
  35. $client->get('/<$a>');
  36. You can learn about all of the different features of URI templates by reading the
  37. `URI templates RFC <http://tools.ietf.org/html/rfc6570>`_.