Best practice to create absolute URLs with Zend framework?

Without mvc

echo $this->serverUrl() . $this->baseUrl('cass/base.css');

or with mvc

echo  $this->serverUrl() . $this->url(array('controller'=>'index','action'=>'index'),null,true);

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'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 
// document root for example.com is in /htdocs 
// but application's index.php resides in /htdocs/myapp/public
echo $this->baseUrl('css/base.css'); 
//will return /myapp/public/css/base.css

echo $this->serverUrl() . $this->baseUrl('css/base.css');
//will return http://www.example.com/myapp/public/css/base.css

echo '//' . $this->getHelper('ServerUrl')->getHost() . $this->baseUrl('css/base.css');
//will return protocol relative URL //www.example.com/myapp/public/css/base.css