Skip to content
This repository has been archived by the owner on Jan 29, 2020. It is now read-only.

Added docs on UrlHelper::setBasePath() #255

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions doc/book/helpers/url-helper.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<lang>[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.
2 changes: 1 addition & 1 deletion mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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 <a href="http://www.zend.com/">Zend Technologies USA Inc.</a>'
copyright: 'Copyright (c) 2016 <a href="http://www.zend.com/">Zend Technologies USA Inc.</a>'