Mar 2

Although in hindsight this is DEAD easy, I’ve just had a bit of a hard time finding out how to do it, so I thought I’d make a quick post which will hopefully get indexed by Google and save some other folk the hard time I had. Thoughtful, eh.

So, to enable the slow query log in WAMP is as simple as adding

log-slow-queries=PATH to your config file.

The config file is located in your wamp installation directory, under bin/mysql/mysql.version/my.ini

In there you will find an entry for standard logs, which will look something like log-error=c:/wamp/logs/mysql.log

Add the slow query flag, and change the log file name to something like log-slow-queries=c:/wamp/logs/mysqlslow.log

Restart wamp, and you’re done.


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/


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.