Create Full URLs in ZF2 Views

Published on March 10, 2013 by

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.

Featured

Learn Zend Framework today!

Take an online course and become a ZF2 ninja!

Here is what you will learn:

  • Understand the theory of Zend Framework in details
  • How to implement an enterprise-ready architecture
  • Develop professional applications in Zend Framework
  • Proficiently work with databases in Zend Framework
  • ... and much more!
Zend Framework logo
Author avatar
Bo Andersen

About the Author

I am a back-end web developer with a passion for open source technologies. I have been a PHP developer for many years, and also have experience with Java and Spring Framework. I currently work full time as a lead developer. Apart from that, I also spend time on making online courses, so be sure to check those out!

Leave a Reply

Your e-mail address will not be published.