Cake in the Wild

I’ve just finnished my first real live application built with CakePHP. It’s nothing too wild – a booking management system based on 10 tables, the only vaguely fancy bit a couple of AJAX lookup / search fields.

Considering it has been the project I’ve actually built using Cake, and I’ve been learning the framework on the job, it has been very painless. It hasn’t taken long – it is an internal project for another department that I’ve squeezed in when I need a break from whatever else I’m doing.

The hardest part has been geetiing used to the format of query results, but that is easily solved with a quick print_r() and it has been a dream to debug and tweak, just working through it with the main guy who will be using it.

Training Database

Reflections on learning CakePHP

I wrote this as a response to a post on this blog – it has a lot of useful links and it also got me thinking.

I’ve been a full time PHP developer for 3 years now (ASP prior to that) – over the past few months I’ve been learning and writing a couple of sites in Cake.

MVC is quite a different way of working to the way most PHP things seem to have been built (and the way I have built my projects) – but when you persevere and everything falls into place you don’t want to go back.

I find myself constantly checking to see if the work I’ve done so far in Cake is up to the point where I can stop using our current CMS framework at work and move to a Cake based system – unfortunately it isn’t quite there – but it will be soo, and I can’t wait.

Personally the hardest thing I have found is the transition to getting query results as quite complex arrays rather than the simple flat results that you get from mysql_fetch_array.

The one thing that I have found invaluble (when dealing with multi table relationships) as an aid is to simply pr() the variable holding my results array into the view I’m working on so I can see the paths I need to follow to the data I want.

Modified Muliple Checkbox Helper

I’ve been getting some very odd results with Joshua McFarrens excellent checkbox helper and ended up having to modify it slightly to get it to work. Here is my revised version:


'Text' pairs) 
     * @param array $selected Selected checkboxes 
     * @param string $inbetween String that separates the checkboxes. 
     * @param array $htmlAttributes Array of HTML options 
     * @param  boolean $return         Whether this method should return a value 
     * @return string List of checkboxes 
     */ 
    function checkboxMultiple($fieldName, $options, $selected = null, $inbetween = null, $htmlAttributes = null, $return = false) 
		{ 
			
       		$this->setFormTag($fieldName); 
       		 if ($this->tagIsInvalid($this->model, $this->field)) 
			 	{ 
            		if (isset($htmlAttributes['class']) && trim($htmlAttributes['class']) != "") 
						{ 
                			$htmlAttributes['class'] .= ' form_error'; 
           				}
					else 
						{ 
                			$htmlAttributes['class'] = 'form_error'; 
						} 
        		} 
				
        if (!is_array($options)) 
			{ 
            	return null; 
        	}  
			   
        if (!isset($selected)) 
			{ 
				$selected = $this->tagValue($fieldName); 
        	} 
				
		while(list($key, $name) = each($options))
			{
				$optionsHere = $htmlAttributes; 
				
				if(in_array($key, $selected))
					{
						$optionsHere['checked'] = 'checked'; 
					}
					
				$optionsHere['value'] = $key; 
            	$checkbox[] = "
  • " . sprintf($this->tags['checkboxmultiple'], $this->model, $this->field, $this->parseHtmlOptions($optionsHere), $name) . "
  • \n"; } return "\n" . sprintf($this->tags['hiddenmultiple'], $this->model, $this->field, null, $name) . "\n
      \n" . $this->output(implode($checkbox), $return) . "
    \n"; } } ?>

    (The difference between this and the original version is that the foreach loop has been replaced with a while(list loop that works in slightly different way.)

    HABTM / Checkbox working example

    Reading the CakePHP group messages, a lot of people seem to run into problems with creating HABTM relationships and changing from the default multipleSelect to using a series of checkboxes. In an app I was building I ran into a brick wall where I just wasn’t able to find out waht was wrong so I just decided to bake a quick example that I could use as a reference.

    This is for Cake 1.1.x.x

    I used a slightly modified copy of the SQL from the manual and used  Josh McFarren’s checkbox helper.

    --
    -- Table structure for table `posts`
    --
    
    CREATE TABLE `posts` (
      `id` int(10) unsigned NOT NULL auto_increment,
      `title` varchar(50) default NULL,
      `body` text,
      `created` datetime default NULL,
      `modified` datetime default NULL,
      `status` tinyint(1) NOT NULL default '0',
      PRIMARY KEY  (`id`)
    ) TYPE=MyISAM;
    
    -- --------------------------------------------------------
    
    --
    -- Table structure for table `posts_tags`
    --
    
    CREATE TABLE `posts_tags` (
      `post_id` int(10) unsigned NOT NULL default '0',
      `tag_id` int(10) unsigned NOT NULL default '0',
      PRIMARY KEY  (`post_id`,`tag_id`)
    ) TYPE=MyISAM;
    
    -- --------------------------------------------------------
    
    --
    -- Table structure for table `tags`
    --
    
    CREATE TABLE `tags` (
      `id` int(10) unsigned NOT NULL auto_increment,
      `name` varchar(100) default NULL,
      PRIMARY KEY  (`id`)
    ) TYPE=MyISAM;
    

    I have made two changes to the SQL above:

    1. Removed the user_id field in ‘posts’ (to simplify the example)
    2. Changed ‘tag’ to ‘name’ in ‘tags’ – I changed this because generateList was not working and the $tags array geneated for the view did not contain the tag name ‘tag’ – only the ‘tag_id’ value.

    You can download my working example, it contains all of the files that I create in bake and the files added and changed to use the checkboxHelper. To install the example:

    1. Bake a new application
    2. Connect to database
    3. Paste files from zip example to replace the newly baked files
    4. Create database tables using the SQL

    HABTM_checkbox_example.zip