Zend\Expressive\Helper\ServerUrlHelper provides the ability to generate a full URI by passing only the path to the helper; it will then use that path with the current Psr\Http\Message\UriInterface instance provided to it in order to generate a fully qualified URI.


When you have an instance, use either its generate() method, or call the instance as an invokable:

// Using the generate() method:
$url = $helper->generate('/foo');

// is equivalent to invocation:
$url = $helper('/foo');

The helper is particularly useful when used in conjunction with the UrlHelper, as you can then create fully qualified URIs for use with headers, API hypermedia links, etc.:

$url = $serverUrl($url('resource', ['id' => 'sha1']));

The signature for the ServerUrlHelper generate() and __invoke() methods is:

function ($path = null) : string


Creating an instance

In order to use the helper, you will need to inject it with the current UriInterface from the request instance. To automate this, we provide Zend\Expressive\Helper\ServerUrlMiddleware, which composes a ServerUrl instance, and, when invoked, injects it with the URI instance.

As such, you will need to register the ServerUrlMiddleware as pipeline middleware, anytime before the routing middleware:

use Zend\Expressive\Helper\ServerUrlMiddleware;

// Programmatically:
// ...

Skeleton configures helpers

If you started your project using the Expressive skeleton package, the ServerUrlHelper and ServerUrlMiddleware factories are already registered for you, as is the ServerUrlMiddleware pipeline middleware.

Using the helper in middleware

Compose the helper in your middleware (or elsewhere), and then use it to generate URI paths:

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterfacel
use Psr\Http\Server\RequestHandlerInterface;
use Zend\Expressive\Helper\ServerUrlHelper;

class FooMiddleware implements MiddlewareInterface
    private $helper;

    public function __construct(ServerUrlHelper $helper)
        $this->helper = $helper;

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface
        $response = $handler->handle($request);

        return $response->withHeader(
            $this->helper->generate() . '; rel="self"'