views:

255

answers:

3

Is there a best practice for creating absolute URLs using the Zend framework? I wonder if there is some helper or if this would just be concatenating the scheme, host, etc. from the $_SERVER variable and then add the relative path generated by Zend.

A: 

I wouldnt use $_SERVER, I would use the values from Zend_Controller_Request_Http::getServer($keyName); (or the direct getters on the request object when that applies - i forget which ones are direct members of the object and which ones need to be accessed with getServer). Technically these are the exact same values, but IMO its better access it the Zend way than to use the raw PHP access. But yes catting those together should get you what you need. This is actually the way i did it for an SSL controller plugin/url helper.

There could be a better way though...

prodigitalson
+1  A: 

In my applications, I keep a "baseUrl" in my application config and I assign that to registry on bootstrapping. Later I use the following View Helper to generate the URL:

<?php

class Zend_View_Helper_UrlMap
{
    public function UrlMap($original)
    {
        $newUrl  = $original;
        $baseUrl = Zend_Registry::get('baseUrl');

        if (strpos($newUrl, "http://") === false) {
            $newUrl = $baseUrl . $newUrl;
        }

        return $newUrl;
    }
}

Benefit: I can make any change on all the URLs in the view from one place.

Hope this helps.

phpfour
`Zend_Registry` is pretty unnecessary. A much better approach would use `Zend_Controller_Front::setBaseUrl()` and `Zend_Controller_Front::getBaseUrl()`. That way, you can also use the included view helper so you don't have to roll your own.
Richard Nguyen
+3  A: 

phpfour's way is OK, but you have to check for https://, ftp:// and mailto: too... :)

I prefefer having all urls root-absolute (/files/js/jquery.js). The "hardcore zend way" is

<?php echo $this->baseUrl('css/base.css'); ?>
Tomáš Fejfar
+1, it's best to use a standard approach 99% of the time - Zend Framework already includes this for you. If you need to change the URL base manually, you can also set it in the bootstrap yourself.
Richard Nguyen