Javascript buffering with CakePHP

Posted by Luca on April 10th

Over time as I have AJAXified more and more of Juvely we have unfortunately had more and more little Javascript code blocks spread around the page. On the dashboard I think it was 4 or 5 codeblocks each with only about 3 lines of Javascript within them. I thought this was rather inefficient, so I was going to write a helper to store each block, and then output it all at the end, fortunately CakePHP has something that does just this built in!

The Javascript helper allows to cache all the code put through the codeBlock() function and then either output it at the end of the view, or include it from a seperate file. I decided to output it at the end of the view as this seemed more suitable for our uses. To enable this you simply need to include the Javascript helper in your controller and then put this somewhere in your view:

$javascript->cacheEvents();

The problem with this is that you have to put it in every view you want the Javascript buffered, and you might forget, so instead open up the code for the Javascript helper (cake/libs/view/helpers/javascript.php) and set the following variables at the top of the class:

var $_cacheEvents = true;
var $_cacheToFile = false;
var $_cacheAll = true;

Right, so how do you use it? Well simple, you just need to pass your code through $javascript->codeBlock() and tada! If like me you don’t current do this, you might want to do what I did to avoid horrible multiline PHP strings argg! I used PHPs output buffering functions to grab the code and then send it to the $javascript->codeBlock() function, I even made a nice little helper for it:

< ?php
class MiscHelper extends Helper
{
	var $helpers = array('javascript');

	function jsBlockStart()
	{
		ob_start();
	}

	function jsBlockEnd()
	{
		$this->javascript->codeBlock(str_replace("\t", "", ob_get_clean()));
	}
}
?>

Then I just need to enclose my Javascript in the tags from the helper like so:


< ?php $misc->jsBlockStart(); ?>
alert('This code is buffered!;');
< ?php $misc->jsBlockEnd(); ?>

Feel free to share this, and if anyone has an account for the CakePHP Bakery to post it there!

Some light entertainment

Here are a couple of links to distract you from your real work for a few minutes.

First, a little video from the game The Punisher which some Aussie I know made:
http://www.loreindustries.com/flash/PunisherHill.html

Second, a nice little addictive flash game. Please take note of the warnings that it is very addictive and you will waste many hours playing it:
http://www.handdrawngames.com/DesktopTD/

Anyway, back to work on Juvely now, we have set a deadline for when we are going to start the beta, and it isn’t very far away! Eeeeek!

1 Comment »

  1. You can register for the Bakery here: http://bakery.cakephp.org/users/register

    Comment by Daniel Hofstetter — 11th of April, 2007 @ 6:49 am

RSS feed for comments on this post. TrackBack URI

Leave a comment