diff --git a/doc/book/helpers/url-helper.md b/doc/book/helpers/url-helper.md index 2b39416e..c64b9e13 100644 --- a/doc/book/helpers/url-helper.md +++ b/doc/book/helpers/url-helper.md @@ -182,3 +182,57 @@ class FooMiddleware } } ``` + +## Base Path support + +If your application is running under a subdirectory, or if you are running +pipeline middleware that is intercepting on a subpath, the paths generated +by the router may not reflect the *base path*, and thus be invalid. To +accommodate this, the `UrlHelper` supports injection of the base path; when +present, it will be prepended to the path generated by the router. + +As an example, perhaps you have middleware running to intercept a language +prefix in the URL; this middleware could then inject the `UrlHelper` with the +detected language, before stripping it off the request URI instance to pass on +to the router: + +```php +use Locale; +use Zend\Expressive\Helper\UrlHelper; + +class LocaleMiddleware +{ + private $helper; + + public function __construct(UrlHelper $helper) + { + $this->helper = $helper; + } + + public function __invoke($request, $response, $next) + { + $uri = $request->getUri(); + $path = $uri->getPath(); + if (! preg_match('#^/(?P[a-z]{2})/#', $path, $matches)) { + return $next($request, $response); + } + + $lang = $matches['lang']; + Locale::setDefault($lang); + $this->helper->setBasePath($lang); + + return $next( + $request->withUri( + $uri->withPath(substr($path, 3)) + ), + $response + ); + } +} +``` + +(Note: if the base path injected is not prefixed with `/`, the helper will add +the slash.) + +Paths generated by the `UriHelper` from this point forward will have the +detected language prefix. diff --git a/mkdocs.yml b/mkdocs.yml index acf73f4c..4f69233b 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -18,4 +18,4 @@ pages: site_name: zend-expressive site_description: 'zend-expressive: PSR-7 Middleware Microframework' repo_url: 'https://github.com/zendframework/zend-expressive' -copyright: 'Copyright (c) 2015 Zend Technologies USA Inc.' +copyright: 'Copyright (c) 2016 Zend Technologies USA Inc.'