tags:

views:

240

answers:

3

I am getting ready to deploy a cakephp app onto the web and i want to move all the assets (img, js, css) to a CDN to increase performance. Is there a way to globally change the location the HTML helper links to assets instead of having to change every link.

+1  A: 

I have a solution but it involves changing the core, I know I know...I have already slapped myself for doing it ;-)

We had a project that was built and then needed a CDN so we just added a bit of code to the HTML and Javascript helpers to assist us.

In the /cake/libs/view/helpers/html.php file add this at line 360

if (Configure::read('Asset.CDN.enabled')) {
    $static_servers = Configure::read('Asset.CDN.static_servers');

    if(sizeof($static_servers) > 0) {
        shuffle($static_servers);
        $url = $static_servers[0].$url;
    }
}

and in /cake/libs/view/helpers/javascript.php ass this at line 288

if (Configure::read('Asset.CDN.enabled')) {
    $static_servers = Configure::read('Asset.CDN.static_servers');

    if(sizeof($static_servers) > 0) {
        shuffle($static_servers);
        $url = $static_servers[0].$url;
    }
}

Then in your app/config.core.php file just add the following configuration options

// Static File Serving on a CDN
Configure::write('Asset.CDN.enabled', false);
Configure::write('Asset.CDN.static_servers', array('http://static0.yoursite.com.au/', 'http://static1.yoursite.com.au/'));

Now when you refresh your page each file that is outputted through the html/javascript helper will automatically pick a random static server.

Note that unless you are using absolute paths (including domain names) in your css files you will need to make sure the images are also on the static server.

I know you shouldn't really play around in the core but sometimes it is really just easier.

Cheers, Dean

Dean
You could/should inject the URL in `AppHelper::url()` (after getting the real URL from `parent::url()`), then you could stop slapping yourself. ;-)
deceze
A: 

If the routes and filenames persist, maybe mod_rewrite might be less painful.

RewriteCond %{REQUEST_URI} ^/css/
RewriteRule ^css/(.*)$ http://cd.yourdomain.com/css/$1 [R=301,L]
metrobalderas
+1  A: 

I had a similar problem, here's how I solved it:
http://stackoverflow.com/questions/1794412/adding-a-prefix-to-every-url-in-cakephp/1878334#1878334

The AppHelper::url() method is the place you should be interested in.

deceze