Create Full URLs in ZF2 Views

Sometimes it is useful to create full URLs within view scripts. For instance, if you are using view scripts to generate markup to be used in e-mails, you cannot link to your website by using relative links. The Zend\View\Helper\Url helper generates relative URLs by default. This can, however, be changed by providing an option in its third parameter.


// Using a route with the name "register" and the route "/register"
echo $this->url('register', array(), array('force_canonical' => true)); // Output: http://mydomain.com/register

Well, that was easy! But what if we do not want to generate an URL for a route? Luckily, the Zend\View\Helper\ServerUrl view helper can help us out. This view helper is not mentioned within the official documentation, so it can be quite easy to miss. It even provides a mechanism for automatically detecting the schema (usually http or https) if we do not wish to specify this explicitly. Either way, its usage is simple:


echo $this->serverUrl(); // Output: http://mydomain.com

The view helper’s __invoke magic method takes an optional parameter. If the boolean value TRUE is passed, it returns the server URL with the $_SERVER‘s request URI appended. Consider the following example:


// Current URL: http://mydomain.com/register
echo $this->serverUrl(true); // Output: http://mydomain.com/register

If passing a string, the helper will simply append that string to the end of the generated URL. By using a combination of the two mentioned view helpers, we can create an URL identical to the one in the first example:


// The "register" route has the following route: /register
echo $this->serverUrl($this->url('register')); // Output: http://mydomain.com/register

In most situations, it would probably make more sense to just use the Zend\View\Helper\Url helper for this, but that is of course entirely up to you and your personal preference. On the other hand, if you need the additional flexibility that the serverUrl helper provides in terms of manipulating the scheme and host, then this is indeed not a bad solution.

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *