Oct 8

Further to my last post about the quality of code in certain well known PHP projects, I just stumbled across this fantastically pointless finger spew.


function the_title($before = '', $after = '', $echo = true) {
$title = get_the_title();

if ( strlen($title) == 0 )
return;

$title = $before . $title . $after;

if ( $echo )
echo $title;
else
return $title;
}

How entirely pointless that is, indeed, it gets worse, the entire thing is bloody well restrictive.
$title = get_the_title(); goes off and gets the title, but it adds HTML to it. I just want to get the title, but instead I end up getting <span blah blah>TITLE</span>.

Very poor code folks, and I think the naming conventions for the functions are not even worth commenting about… oh go on, I can’t resist “the _title”? Nice and descriptive, ain’t it. :|

The thing is, I cannot understand why somebody would have done this. It’s just adding code that is in no way required. I think you’ll find that this particular program is riddled with dodgy designs, or lack thereof, like this, and if it was just coded properly in the first place, I dare say it would run considerably quicker, not to mention making the lives of us developers infinitely easier.


Sep 30

I’ve finally cracked, I can take it no more. I’m just going to have to blog about it.

Before I quit the world and disappeared sailing for 4 months this summer, I wrote a post titled “Drupal is shit“, in it a ranted about how I couldn’t stand Drupal, and that I use either Wordpress or an MVC framework in its place. That post drew quite a bit of attention this summer after Webschuur blogged a reply to my original post.

The time has now come for me to bitch about the very product I defended in that post; Wordpress.

Here, are you ready for it, I’m going to say it. Wordpress is shit!

Ok, it’s not on the face of things, I happen to love Wordpress, but I’ve been working on a contract rececntly which involves some fairly in depth Wordpress development. I’ve had to peer under its skirt and what I’ve found was not something you’d want to tell your friends about.

This post goes beyond my opinion of Wordpress though, I want it to highlight a more fundamental problem with PHP development. People just don’t seem to be very good at it, and it’s giving PHP a bad name.

I got a bit of a telling off in the Drupal thread for not giving examples of what I considered to be poor code, so I’m not going to allow that to happen again. Let’s take a look at a random snippet of Wordpress code.

Can anybody tell me what that does? I doubt it, and that makes for bad code from the off. Thankfully, despite the atrocious function naming and cringe inducing syntax, it is doc tagged, so a mouse over in eclipse tell me that the_post() “iterates the post index in the loop”. I’m still not entirely sure what’s going on here, but I’ve got a better idea.

Let’s dig a bit deeper, F3 in Eclipse open the declaration.

/**
* Iterate the post index in the loop.
*
* @see WP_Query::the_post()
* @since 1.5.0
* @uses $wp_query
*/
function the_post() {
global $wp_query;

$wp_query->the_post();
}

This hasn’t helped much, I still have no idea what’s going on, but it has invoked a sub rant about Globals.

Why do people use them? It’s such a dumb idea. You have no control over that variable, no idea where it comes from, and no idea who has fettled with it before it’s used in this function.

Now, at this point, I’d open declaration on the the_post() method, but I can’t since Eclipse has no idea what $wp_query is. I can’t even find it without a search through the code because Wordpress doesn’t do, is put classes in individual files. They are just mixed up where ever in an orgy of mouldy spaghetti code. Again, this is bad because it makes a developers life hard for no benefit.

Searching for “WP_Query” was of little benefit since it’s littered throughout the code. I had to try another tactic, let’s find the function itself with a search for “n the_post”.

Aha, found it in wp-includes/query.php which isn’t too bad I suppose, although I would have preferred the file be called the same as the class within it. wp_query.php. Makes it nice and obvious then doesn’t it.

Opening the file shows another horror story; a huge mix of procedural and OO code. I can understand why this may have happened, it was probably because they are trying to port it to OO yet retain backwards compatibility, at least I hope that was the reason, but this is just a bloody confusing mess.

Anyway, onward we go. Let’s open up the code for the_post() and see what’s going on.

/**
* Sets up the current post.
*
* Retrieves the next post, sets up the post, sets the 'in the loop'
* property to true.
*
* @since 1.5.0
* @access public
* @uses $post
* @uses do_action() Calls 'loop_start' if loop has just started
*/
function the_post() {
global $post;
$this->in_the_loop = true;
$post = $this->next_post();
setup_postdata($post);

if ( $this->current_post == 0 ) // loop has just started
do_action(’loop_start’);
}

I think this can be summarised with a simple, yet effective WTF!!!!???!!!

I don’t think I can bear to dig any deeper. What is wrong with using an iterator? There are well established design patterns for this sort of thing.

The bottom line is, Wordpress is like so many projects out there, a complete kludge of crap code. I will still defend Wordpress for being a good product, I can make it do things quickly (mostly) and for standard use it’s nice and easy to use, but my god do I pity you if you have to go beyond that.

HTML is also well and truly mixed in with the core code, which means to apply a specific design, you may well have to start hacking around within the functions of a plugin. This means that what should be a modular website with themes, quickly turns into a customised hunk of code that you can’t upgrade any more through fear of braking it all.

The above example reflects the vast majority of PHP code I’ve worked with, and it’s sadly a rare thing to stumble across well written and designed PHP software. The unshakable attachment to it’s roots as a hobiest language are all too apparent.

Come on folks, we can do better than this. When you turn up for work tomorrow, have a think about replacing those globals in your code with a static class or two, but more importantly, find out why you should. The PHP world will thank you for it, I promise.


Feb 20

I had a bit of a hard time getting Zend Framework to run on my 1&1 hosting. It was all down to the .htaccess file in the end. The default htaccess configuration in the ZF getting started guide just doesn’t work, and neither did all the other posts I could fine on the subject around the internet, however, I’ve finally cracked it.

Presuming you’ve put your ZF index file in the webroot, here’s what the 1and1 htaccess file should look like.


AddHandler x-mapp-php5 .php
AddType x-mapp-php5 .php
Options -MultiViews

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule !\.(txt|swf|js|ico|gif|jpg|png|css|xml)$ /

Note: The same file will not work on my local dev machine, which is running only PHP5. You will need to comment out the first two lines (AddHandler, AddType) to get it to run on a stadard PHP5 installation.


Feb 20

I was having a bit of a problem with TinyMCE not loading in Zend Framework (ZF). It turns out the .htaccess file was not configured correctly. It was redirecting .js to the index bootstrap and causing the page to fail to load.

The solution was the htaccess file as so…


Options -MultiViews

RewriteEngine On
RewriteBase /website
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule !\.(txt|swf|js|ico|gif|jpg|png|css|xml)$ /website/


Feb 16

I run another blog, although it’s hosted on wordpress.com rather than my domain, here.

The blog is about my boat, ‘Kudu’. It’s a 21ft Corribee - a sailing yacht - and we are planning some substantial voyages toghether. Anyway, the other evening I got an excited facebook message from a friend saying my blog was listed on the wordpress.com’s Blog Of The Day stat’s page. I had the 7th fastest growing blog on all of wordpress. I was ecstatic about it. The 7th fastest growing blog on all of wordpress!

I awoke in the morning to find I was no longer 7th, but 1st. I was shocked. I had THE fastest growing blog on all of wordpress, which means I had one of the fastest growing blogs on the entire internet at that point in time. Sadly it was short lived, I’ve since dropped off the list, but to sustain the sort of growth I was seeing was never going to happen.


Feb 16

I decided to rebuild my home page since it was originally done as little more than static pages. Ok, I used a bit of PHP to include headers and footers and do a couple of other litte things, but it was nothing clever.

Since it is trying to promote me as a developer, I thought I should apply a bit more effort than that. It turns out, I failed. I used Zend Framework to rebuild the site, and it just made everything even easier and less effort. From form validation to displaying my twitter feed, I had the lot built in about 4 hours, well, excluding the other 4 hours it took me trying to figure out how to get Zend Framework working with 1and1’s hosting.


Jan 16

I’m just giving some link love here since a friend of mine has just launched a new project.

Cardsmart.co.uk is a credit card comparison service and it went live about 3 minutes ago at the time of writing. It’s quite exciting to see the birth of a brand new company, it’s quite a refreshing change given all of the dying one’s that are around at the moment.

As I recall, they’ve got about 250 credit card offers on the site, which compared to money supermarket is a HUGE selection.

So there you have it, if you are in the market for a new bit of plastic check out the site.

JP, you owe me a beer. :D


Dec 3

.

.

Firstly I must apologise for this blog post, it’s perhaps a little spammy but I fancied owning the arses of the Dev team in ego searches, it’s a social experiment you see :)

My theory is that being skilled (or at least semi skilled in my case) at SEO brings a whole host of power to your social life that is as yet untapped. I mean, what if I were the top result for Olaf Spinkel? I’d pretty much own the worlds opinion on the guy. Or Parminder Matharu for that matter, or even Daniele Sangalli. They all members of the dev team at work and fortunately for them they are both good chaps and very talented developers. Also, I’m too nice to do anything nasty, but I’m not nice enough to not carry out the experiement. :p

So, if I were number one for Olaf I could change the worlds opinion of him. I could tell you he likes to kick dogs or eat raw snails, and Google would believe me. This, as I’m sure you can see would work very well in the pub.

“Spinkel, another beer please”

“I bought the last one”

“Another beer, or I’ll tell Google you have all the Gary Glitter Albums and listen to them everyday!”

Ah, life will be grand, but I may get bored, give in, and 301 this page to a site of their choice eventually (after the law suit)… but not yet.

So not to make this too pointless, and to give me some tasty keywordey content, I’ll write something useful, and indeed genuinely deserved about these guys.

Who are Olaf Spinkel, Parminder Matharu and Daniele Sangalli?

Well, they are currently PHP developers at TradeDoubler. They work on Searchware 4 and are genuinely a very talented bunch of people. Olaf knows more about search engine APIs than anybody I know (apart from myself, of course :p ), he has after all spent over 18 months solid on a project involving nothing but tinkering with Google reports, Yahoo reports and the other one that everybody has forgotten about.

Parminder Matharu is our resident Business Objects guru and equally good at what he does. In fact he is so good I think he deserves some extra Google love so I’m going to put write his name again, but more bold, like Parminder Matharu. Then there’s Daniele, or Don Sangalli as we call him, is one of those rare creatures who can both write proper OO code (and that’s a big compliment given my standards of proper OO code!) and also produce well designed websites. He’s like a development unicorn, and unless you work here at TD, then the only chance you might get of spotting him is quietly sat in the back of the pub with a red wine on a Thursday night, surrounded by girls pining after his Italian dress sense and impecably mild nature.

Mr Olaf Spinkel is German, which was a rather pointless thing to say expect for it will help make this page number for for his name. That kind of power has got to be worth something in the pub I think. I should also compliment him to, not for any other reason than he also deserves it (and it get’s me top for ‘Olaf’). He wrote a data caching system that’s rather impressive and he also knows a consierable amount about search and the internet, although I would argue not enough to out rank me for “Nathan Whitworth” :D

Oh, he has a website, a very good one too if you can read German and like rock music, http://www.musik.terrorverlag.de/

Well, if you read this and would care to help me in this very valiant and slightly childish cause, then please either digg the page, or even better, give this page a link from your own site. In return, I promise to think of something entertaining to do with their fame.


Dec 3

Ooh, what’s this?

I’ve been noticing “Oohgle” adverts on the tube trains around London recently. They consist of no information about the product, just a bright pixelated search button containing the text “Oohgle”.

Now, I usually get a bit annoyed with adverts that don’t tell you what they are selling, but this time it was so sparse and gave no hint whatsoever about its purpose, that I had to look.  So, off to Google I went to follow the honey trap set out on the tube.

It turns out Oohgle seem to be some sort of advertising agency, but even their website is void of any hard facts about what they do. They have a tool called Prism Search which “analyses the relationship between OOH and Search” - OOH being “Out Of Home”, which apparently seems to mean bewildering people until they finally crack and curiosity gets the better of them - as I did.

However, Oohgle seem to be offering something a bit more intelligent than just bewilderment. The statement “The way we gather data means we’re not reliant on campaign-specific URLs” suggests to me that they are replacing URLs printed in traditional media with the suggestion to search for a particular keyword, and as we all know, keywords are trackable, which is where Prism Search seems to come into play.

Ooh Bugger

This concept is actually quite a reasonable idea, but it could go massively wrong.

If, for example, your expensive above the line campaign contained the keyword, oh I don’t know, let’s say ‘Oohgle‘, then to actually see any traffic off that you’re going to have to be number one for both PPC and Natural listings across all of the big engines.  That could be quite expensive depending on the keyword, but much worse than that, it means competitors can very easily hijack your expensive advertisment by being a little bit better at SEO or having a slightly more robust PPC campaign.

Ultimately this is a good idea, but unless you are prepared to invest a lot of money to safeguard your OOH keyword, then it’s a dangerous prospect, although does open the door for your PPC agency to be much more attentive to your competitors advertisements. If you can move quickly, you could be the one reaping the benefits, not them!


Oct 1

I’ve started using Zend Framework for a project I’m under taking here at TradeDoubler. I’m building a new part of Searchware that is essentially standalone, so figured that this is a great oportunity to push for framework support. Better form validation, less scope for creating errors in trivial donkey work coding because it’s already done for you, and ultimately a better experience for the user.

The problem I soon discovered with ZF, is that the documentation is not as good as I would of hoped. Their introductory videos are absolutely amazing, but when it comes to getting a real project started, they leave you feeling a bit left out in the cold.

Multi Page Forms

A good example of this, and something I’ve just been working on, is multi page forms. Zend Form is a great start and will go places, but right now, I think it’s not quite there. I discovered that subforms are the recommended way to implement multi page forms, but the example in the documentation again doesn’t quite explain how to do it, it just points you in a direction and expects you to figure the rest out for yourself. All very good, but some of us are fairly busy and would rather just read a comprehensive example.

A comprehensive example :)

This is how I decided to make a multi page form based on Zend Form subforms. I don’t know if this is the best way of doing it, and I am a complete newbie to ZF, but since I couldn’t find any other examples, and this does work, I’ll just have to presume it is until I’m corrected by one of you kind readers :p. This example will show you how to setup the required classes, build a simple form, validate, and then store the information and make it available to subsequent forms for decision making.

Note: This is not a beginners guide to Zend Framework or MVC. If you’re not quite sure how ZF works, or what MVC is, please check out the introductory vids on the Zend site. They are very good.

So, to kick things off we’re going to need to load up all the classes required for our forms. To do this, add the following lines to your boot strap file.


DEFINE('APPLICATION_PATH','/data/web/yourApplication');

Zend_Loader::loadClass("Zend_Form");
Zend_Loader::loadClass("Zend_Session");
Zend_Loader::loadClass("Zend_Session_Namespace");

// And any validation classes you will be using, for example
Zend_Loader::loadClass("Zend_Validate_NotEmpty");

This will set up our bootstrap file with everything we need to build a form, so the next job is editing your controller class. Add the following methods into your controller. They are used to store and read validated form values, but more on that later.


	private function storeFormValues(Zend_Form $form)
	{
		$formSession = new Zend_Session_Namespace('yourAppForm');

		foreach ($form->getValues() as $key => $value)
		{
			$formSession->$key = $value;
		}
	}

	private function getFormValues()
	{
		$formSession = new Zend_Session_Namespace('yourAppForm');

		$data = array();
		foreach ($formSession->getIterator() as $key => $value)
		{
			$data[$key] = $value;
		}
		return $data;
	}

You will also need to add the following method in your controller class.


	 protected function getForm($formName)
	 {
	 	// you will need to edit this later, but leave it for now.
	 	require_once APPLICATION_PATH . '/forms/parentForm.php';

	 	$mainForm = new Form_ParentForm($this->getFormValues());

	 	if ($formName == 'main')
	 	{
	 		$form = $mainForm;
	 	}
	 	else
	 	{
	 		$form = $mainForm->getSubForm($formName);
	 		$form->addElement('hidden','currentFormStage',array('value' => $formName));
	 	}

	 	return $form;
	 }

So, I’ll take a little time to explain that one since it’s not instantly obvious.

First off

require_once APPLICATION_PATH . '/forms/parentForm.php';

is the path to your form classes. I’ll explain how to create those later but for now, decide where you will want to store your forms, and point this there. Remember the constant APPLICATION_PATH was set in the bootstrap file.

The next line is

$mainForm = new Form_AddAccount($this->getFormValues());

This instantiates our parent form and passes to it any form data we have in our session.

The next part is

if ($formName == 'main')
{
	$form = $mainForm;
}

This is used later on in the controller to check whether the entire form (i.e. all of it’s sub pages are validated). The controller asks for the sub form name, but if this is ‘main’, then the parent class is sent back.

Creating our forms
So far we’ve built the required scaffolding for our multi page form that will be used by the controller. The next step is to create the forms themselves. As I’ve already mentioned the overall multi page form consists of a parent container form, and a collection of sub forms. For the sake of making it easy to read, I’m going to use VERY crude examples of forms, but please consult the Zend Form docs for more details about creating various form elements. That part of things is fairly well documented.

The entire parent class looks like this…


class Form_ParentForm extends Zend_Form
{
	private $formValues;

	public function __construct($formValues)
	{
		$this->formValues = $formValues;
		parent::__construct();
	}

	public function getFormValue($name)
	{

		if (isset($this->formValues[$name]))
		{
			return $this->formValues[$name];
		}
		else
		{
			return null;
		}

	}

	public function init()
	{

		$this->setAction('index');
		$this->setMethod('post');

		require_once APPLICATION_PATH . '/forms/SubFormPageOne.php';
		require_once APPLICATION_PATH . '/forms/SubFormPageTwo.php';

		$pageOne = new Form_SubFormPageOne($this);
		$pageTwo = new Form_SubFormPageTwo($this);

		$this->addSubForm($pageOne,'pageOne');
		$this->addSubForm($pageTwo,'pageTwo');

	}

}

The only bit you need to be concerned about editing here is the init() method. Change setAction() and setMethod() as you see fit, but they will probably be ok as they are in most cases.
The next bit, the requires, is important. Remember in the controller class we edited the getForm() method. There was an include path in there that pointed to the parent form. You need to make sure that, obviously, this parent form is saved to the same place. You could put the subforms in other directories, but I don’t see any benefit of doing so, so I’d recommend you keep then all bundled together in the same directory.

Once you have included then, you instantiate the subforms (actually, they are instances of Zend_Form and not SubForm, but that is ok), and then pass them to addSubForm. Hopefully this is quite easy to follow so I’m not going to explain it any further. If you get stuck, please feel free to ask me a question.

So then, our final step in building the forms is to create the sub forms. The subform class looks like this.


class Form_SubFormPageOne extends Zend_Form
{
	private $parentForm;

	public function __construct(Zend_Form $parentForm)
	{
		$this->parentForm = $parentForm;
		parent::__construct();
	}

	public function init()
	{

		// engine dropdown
		$engineSelect = $this->createElement('select','engine');

		$engineSelect->addMultiOption('','Please Choose...');
		$engineSelect->addMultiOption('google','Google');
		$engineSelect->addMultiOption('yahoo','Yahoo');
		$engineSelect->addMultiOption('msn','MSN');

		$engineSelect->setRequired(true);

		$this->addElement($engineSelect);

		// create submit button
		$this->addElement('submit', 'btnNext', array( 'label' => 'Next')); 

	}

}

Apart from changing the class name to suit your needs, the only other thing you should need to edit is the init() method. In here you create the form elements, apply validation, decorators and so on. This work in exactly the same way as a single page form, so please consult one of the many Zend Form examples for details on adding elements. As you can see our example form simply gives a dropdown list of search engines and a submit button.

Plugging it all together
So we’ve got our scaffolding, and we’ve got our forms. The only thing left to do now is to stick it all together, and this happens in the ‘action’ method of the controller. In most cases, and certainly this one, it will be the index action.

This method is a bit longer than the others so rather than me blabbering on here, I’ll let the comments to the talking. :)


public function indexAction()
{
	$request = $this->getRequest();

	// is this a post back, i.e was the form submitted or is it a first visit.
	if ($request->isPost())
	{
		/*
		Get an instance of the current form.
		Remember currentFormStage was appended
		to the form as a hidden field in the getForm method.
		*/
		$form = $this->getForm($_POST['currentFormStage']);

		// does is pass validation?
		if ($form->isValid($_POST))
		{
			// yes, so save the values to our session.
			$this->storeFormValues($form);

			/*
			So, we've just check a subform and it was valid.
			Does this now make our entire form collection valid?
			Let's check by getting in instance of the parent form.
			*/
			if ($this->getForm('main')->isValid($this->getFormValues()))
			{
				/*
				The form is complete, so redirect to the
				finish action (you will need to create this)
				*/
				$this->_redirect("index/finish");
			}

			/*
			A crude but workable method of choosing which form to go to next.
			*/
			switch ($_POST['currentFormStage'])
			{
				case 'pageOne':
					$newForm = 'pageTwo';
					break;
				default:
					$newForm = 'pageOne';
				break;
			}
			/* get an instance of our new form.
			having passed page one, this would be now page two.
			*/
			$form = $this->getForm($newForm);

		}

	}
	else
	{
		/*
		If this is the first time the page is loaded
		i.e. no forms submitted, let's make sure the session is
		empty.
		*/
		$formSession = new Zend_Session_Namespace('yourAppForm');
		$formSession->unsetAll();

		// and then load the first form page.
		$form = $this->getForm('pageOne');
	}

	$this->view->printForm = $form;

}

And there it is, you’re done. You have a working multi page form in the Zend framework. One final note, the last line $this->view->printForm = $form; is simply to pass the form to the view. The view file for this controller/action, would contain printForm; ?>

I hope that helped clear things up, and if anybody has any questions, please feel free to post them.