CakePHP Menu Helper for Tree data

This is the MenuHelper I use in my CMS system. It is designed to work with data from the Tree behaviour or from any $model->find(‘threaded’) call. I use it to generate multi level CSS menus (that you see at the top of most websites), contextual menus (that you see in sidebars, showing the current page and its ‘branch’) and sitemaps – which let’s face it are basically often just the same as a top level menu but without the fancy stuff to make them pop out when you hover over them.

Prerequisites, history, overview

There are a couple of prerequisites here which may mean that this isn’t applicable for a lot of people. The helper is designed to deal with ‘page’ structures organised in simple /parent/child/grand-child format e.g.

/home
/about
/about/company-history
/about/company-history/gallery
/about/ethos
/about/vacancies
/news
/news/2009/jan
/news/2009/feb
/news/2009/mar
/contact
(etc.)

In my system I have a model ‘Article’ with Tree behaviour attached. So in the example above ‘ethos’ is a child of ‘about’. Some of these pages have real content, but others just act as place holders for other controllers / models – ‘news’ is a placeholder for the ‘News’ model. But all of them (even the placeholders) have other data attached like content for sidebars or meta information.

The helper will add a ‘selected-item’ class to the LI corresponding to the current page, and if it has any parents it will add a ‘selected’ class to each of those parent LIs too.

I create a full slug for each ‘Article’ on $model->save()

The helper operates in 2 modes ‘tree’ (which is default) and ‘context’
‘tree’ will produce a whole list of nested ULs – can be used to generate top level navigation (works well with things like suckerfish)
‘context’ will only produce nested ULs for the current branch

Using the example above if you were on the /about/ethos page and you wanted the navigation fragment in the sidebar you would use ‘context’
/about
/about/company-history
/about/company-history/gallery
/about/ethos
/about/vacancies

Database Fields

These are the default field names, they can be simply overridden to match your database schema.

Required Fields

  • name
  • slug_url

Optional Fields

  • title_for_navigation
  • redirect_url
  • redirect_target

Example ‘threaded’ data

[Article] => Array
                (
                    [name] => Find out about us
                    [slug_url] => /about-us
                    [title_for_navigation] => About Us
                    [redirect_url] => 
                    [redirect_target] => 
                    [lft] => 15
                    [id] => 105
                    [rght] => 24
                    [parent_id] => 
                )
 
            [children] => Array
                (
                    [0] => Array
                        (
                            [Article] => Array
                                (
                                    [name] => Philosophy
                                    [slug_url] => /about-us/philosophy
                                    [title_for_navigation] => 
                                    [redirect_url] => 
                                    [redirect_target] => 
                                    [lft] => 16
                                    [id] => 111
                                    [rght] => 21
                                    [parent_id] => 105
                                )
)))

Usage

Include the helper in your controller as usual.

In a view / element to generate complete menu

 
echo $menu->setup($menu_data, array('selected' => $this->here));

In a view / element to generate a context menu from the same data, set the class of the parent UL

 
echo $menu->setup($menu_data, array('selected' => $this->here, 'type' => 'context', 'menuClass' => 'context-menu'));

In a view / element to generate a sitemap from different data, let the helper know to use the ‘Sitemap’ model rather than the default ‘Article’ model and set the parent UL class.

 
$sitemap = new MenuHelper();
echo $sitemap->setup($data,  array('modelName' => 'Sitemap', 'menuClass' => 'sitemap'));

The Helper Code

Download the Helper

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
<?php
/**
 * Menu Helper
 * 
 * @author John Elliott (http://www.flipflops.org)
 * @package app
 * @subpackage app.views.helpers
 * @version 1.0
 * @lastmodified 2009-09-29
 * 
 * This helper is designed to work with the data arrays returned by the Tree behaviour or $model->find('threaded');
 * More specifically it is designed to generate menus composed of nested ULs for use in CMS systems where all the URLs are pretty:
 * 	- naviagtion menus (usually at the top of the page)
 * 	- context menus (usually found at the side) and showing the links in the current branch
 * 	- sitemaps
 * 
 * Overview (A bit of history)
 * 
 * The helper is designed to deal with navigation / page structures organised in simple /parent/child/grand-child like structures
 * for instance:
 * 
 * /home
 * /about
 * /about/company-history
 * /about/company-history/gallery
 * /about/ethos
 * /about/vacancies
 * /news
 * /news/2009/jan
 * /news/2009/feb
 * /news/2009/mar
 * /contact
 * (etc.)
 * 
 * -------------------
 * URLs are generated in the model or controller not in the view / helper
 * -------------------
 * In the system from which this is taken, I create a full slug for each page on $model->save();
 * Some of the pages are actual pages of text and others are palceholders for content in other models
 * but they allow you do things like control the content of left / right columns, set default meta tags etc.
 * The purpose being to create really easy site structures with nice urls, the 
 * In the example above /home, /about etc. are all from a single model 'Article' which is my master model 
 * /news however is a placeholder for the 'News' model and /contact for the 'Contact' model
 * 
 *
 * 
 * Required Fields
 * ------------------
 * title / name (defaults to 'title')
 * page url (defaults to 'slug_url' e.g. /about/ethos)
 * 
 * Optional Fields
 * ------------------
 * title_for_navigation
 * redirect_url
 * redirect_target
 * 
 * Example data
 * ------------------
 * [Article] => Array
                (
                    [name] => Find out about us
                    [slug_url] => /about-us
                    [title_for_navigation] => About Us
                    [redirect_url] => 
                    [redirect_target] => 
                    [lft] => 15
                    [id] => 105
                    [rght] => 24
                    [parent_id] => 
                )
 
            [children] => Array
                (
                    [0] => Array
                        (
                            [Article] => Array
                                (
                                    [name] => Philosophy
                                    [slug_url] => /about-us/philosophy
                                    [title_for_navigation] => 
                                    [redirect_url] => 
                                    [redirect_target] => 
                                    [lft] => 16
                                    [id] => 111
                                    [rght] => 21
                                    [parent_id] => 105
                                )
 * 
 * 
 * 
 *
 * Usage:
 * 
 * Include the helper in your controller as usual.
 * 
 * The helper operates in 2 modes 'tree' (which is default) and 'context'
 * 'tree' will produce a whole list of nested Uls - can be used to generate top level navigation (works well with things like suckerfish)
 * 'context' will only produce nested ULs for the current branch
 * 
 * Using the example above if you were on the /about/ethos page and you wanted the navigation fragment in the sidebar you would use context
 * /about
 * /about/company-history
 * /about/company-history/gallery
 * /about/ethos
 * /about/vacancies
 * 
 * In a view / element to generate complete menu
 * echo $menu->setup($menu_data, array('selected' => $this->here));
 * 
 * In a view / element to generate a context menu from the same data, set the class of the parent UL
 * echo $menu->setup($menu_data, array('selected' => $this->here, 'type' => 'context', 'menuClass' => 'context-menu'));
 * 
 * 
 * In a view / element to generate a sitemap from different data, let the helper know to use the 'Sitemap' model rather than the default 'Article' model and set the parent UL class.
 * $sitemap = new MenuHelper();
 * echo $sitemap->setup($data,  array('modelName' => 'Sitemap', 'menuClass' => 'sitemap'));
 * 
 * Version Details
 * 
 * 1.0
 * + Initial release.
 */
class MenuHelper extends AppHelper {
 
	/**
	 * Current page in application
	 *
	 * @var string
	 */
	private $selected = '';
 
	/** Internal variable for the data
	 *
	 * @var array
	 */
	private $array = array();
 
	/**
	 * Default css class applied to the menu
	 *
	 * @var string
	 */
	private $menuClass = 'menu';
 
	/**
	 * Default DOM id applied to menu
	 *
	 * @var string
	 */
	private $menuId = 'top-menu';
 
	/**
	 * CSS class applied to the selected node and its parent nodes 
	 *
	 * @var string
	 */
	private $selectedClass = 'selected';
 
	/**
	 * CSS class applied to the exact selected node in the tree - in addition to $selectedClass
	 *
	 * @var unknown_type
	 */
	private $selectedClassItem = 'item-selected';
 
	/**
	 * Default Slug
	 *
	 * @var string
	 */
	private $defaultSlug = 'home';
 
	/**
	 * Type of menu to be generated:
	 * 'tree' - to generate a complete tree
	 * 'context' - to only render the specific barnch under the current page
	 *
	 * @var string
	 */
	private $type = 'tree';
 
	/**
	 * Model name used in $array e.g. $data[0]['Article']['name']
	 *
	 * @var string
	 */
	private $modelName = 'Article';
 
	/**
	 * Database column name - (i.e. a shorter version of the name / title for use only in naviagtion)
	 * e.g. A page called 'Welcome to the giant flea circus' 
	 * might be set to show up on navigation as 'home'
	 *
	 * @var string
	 */
	private $titleForNavigation = 'title_for_navigation';
 
	/**
	 * Database column name for title / name
	 * @var string
	 */
	private $title = 'name';
 
	/**
	 * Database column name for complete page slug e.g. /about/history/early-years
	 *
	 * @var string
	 */
	private $slugUrl = 'slug_url';
 
	/**
	 * Database column name for redirect_url for instance if /about/blog redirects to http://blog.somewebsite.com
	 *
	 * @var string
	 */
	private $redirectUrl = 'redirect_url';
 
	/**
	 * Target for redirect (see redirectUrl)
	 *
	 * @var string
	 */
	private $redirectTarget = 'redirect_target';
 
	/**
	 * Minumum number of items required to render a context menu
	 *
	 * @var int
	 */
	private $contextMinLength = 2;
 
	/**
	 * Internal Counter used in type: 'context'
	 *
	 * @var int
	 */
	private $li_count = 0;
 
	/**
	 * Internal flag to see if the page has been matched to an item
	 *
	 * @var bool
	 */
	private $matched = false;
 
	/**
	 * Internal counter
	 *
	 * @var int
	 */
	private $i = 0;
 
	/**
	 * Enter description here...
	 *
	 * @var unknown_type
	 */
	private $rootNode = '';
 
	function __construct(){
 
	}
 
	public function setOption($key, $value){
		$this->{$key} = $value;
	}
 
	public function getOption($key){
		return $this->{$key};
	}
 
	/**
	 * Setup the helper and return a string to echo
	 *
	 * @param array $array Data array containing the lists
	 * @param array $config Configuration variables to override the defaults
	 * @return string
	 */
	public function setup($array, $config = array()){
 
		// update and override the default variables 
		if(!empty($config)){
			foreach ($config as $key => $value) {
				$this->setOption($key, $value);
			}
		}
 
		// set the default slug selected if the current page does not match
		if($this->selected == '/'){
			$this->selected = $this->defaultSlug;
		}
 
		$this->array = $array;
 
 
 
		// get the root node of the selected tree if this a context menu
		if($this->type == 'context'){
			$this->rootNode = $this->getRootNode($this->selected);
		}
 
		$str = $this->buildMenu();
 
		// if the current page has matched one of the links in the tree
		// then get rid of the 'default_slected' placeholder
		if($this->matched == true){
			$str = str_replace('default_selected', '', $str);
		} else {
			$s = ' class="' . $this->selectedClass . '" ';
			$str = str_replace('default_selected', $s, $str);
		}
 
		// if this is a context menu, it looks daft if it only has 1 item 
		// if this is the case hide it
		if($this->type == 'context'){
			if($this->li_count < $this->contextMinLength){
				$str = '';
			}
		}
 
 
		return $this->output($str);	
 
	}
	/**
	 * Call the menu iterator method and if it returns a string warp it up in a UL
	 *
	 * @return string
	 */
	protected function buildMenu(){
 
		$str = $this->menuIterator($this->array);
 
		if($str != ''){
			$str = '<ul  id="' . $this->menuId . '" class="' . $this->menuClass . '">' . $str . '</ul>';
		}
 
		return $str;
	}
 
	/**
	 * Explode a url slug and get the root page
	 *
	 * @param string $string 
	 * @return string
	 */
	protected function getRootNode($string){
			$rootNode = '';
			if($string != ''){
				$node = explode('/', $string);
				// $node[0] will always be empty becuase the first char of $this->selected will always be '/'
				$rootNode = $node[1];
			}
			return $rootNode;
	}
 
 
	/**
	 * Recursive method to loop down through the data array building menus and sub menus
	 *
	 * @param array $array
	 * @param int $depth
	 * @return string
	 */
	protected function menuIterator($array){
 
		$str = '';
		$is_selected = false;
		foreach($array as $var){
 
			$continue = true;
			$selected = '';
			$sub = '';
 
			if($this->type == 'context' && ($this->getRootNode($var[$this->modelName][$this->slugUrl]) != $this->rootNode)){
				$continue = false;
			}
 
			if($continue == true){
 
				// if this is the first list item set default_selected placeholder
				$default_selected = '';
				if($this->i == 0){
					$this->i = 1;
					$default_selected = 'default_selected';
				}
 
 
 
				if(!empty($var['children'])){
					$sub .= '<ul>';
					$sub .= $this->menuIterator($var['children']);
					$sub .= '</ul>';	
				}
 
				$p = strpos($this->selected, $var[$this->modelName][$this->slugUrl]);
 
 
				if($p === false){
 
				} elseif($p == 0){
						// this is the selected item or a parent node of the selected item
						$selected = ' class="' . $this->selectedClass . '" ';
						$is_selected = true;
						$this->matched = true;
				}
 
				if($this->selected == $var[$this->modelName][$this->slugUrl]){
					// this is the exact selected item
					$selected = ' class="' . $this->selectedClass . ' ' . $this->selectedClassItem . '" ';
				}
 
				// keep track if this is a contextual menu 
				if($this->type == 'context'){
					$this->li_count++;
				}
 
 
				// Get the name / title to be used for the link text
				$name = $this->getName($var);
				// Get the URL / target for the link
				$url = $this->getUrl($var);
 
				$str .= '<li ' . $selected . ' ' . $default_selected . '>';
					$str .= '<a  href="' . $url['url'] . '" ' . $url['target'] . '><span>' . $name . '</span></a>';
					$str .= $sub;
				$str .= '</li>';
 
			}
		}
		return $str;
	}
	/**
	 * Look in the data and check if this is a straight url
	 * or whether it is actually a redirect
	 *
	 * @param array $var
	 * @return array
	 */
	protected function getUrl($var = null){
			$url = array();
 
			if(isset($var[$this->modelName][$this->redirectUrl]) && !empty($var[$this->modelName][$this->redirectUrl])){
				$url['url'] = $var[$this->modelName][$this->redirectUrl];
				if(isset($var[$this->modelName][$this->redirectTarget]) && !empty($var[$this->modelName][$this->redirectTarget])){
					$url['target'] = ' target="' . $var[$this->modelName][$this->redirectTarget] . '" ';
				}
			} else {
				$url['url'] = $var[$this->modelName][$this->slugUrl];
				$url['target'] = '';
			}
			return $url;
	}
 
	/**
	 * See if there is a title_for_navigation 
	 *
	 * @param array $var
	 * @return string
	 */
	protected function getName($var){
		if(isset($var[$this->modelName][$this->titleForNavigation]) && !empty($var[$this->modelName][$this->titleForNavigation])){
			$name = $var[$this->modelName][$this->titleForNavigation];
		} else {
			$name = $var[$this->modelName][$this->title];
		}
		return $name;
	}
 
 
 
}
?>

Symbiotica

Symbiotica Media Ltd - web design & development in Devon

I’ve been meaning to announce the launch of my company Symbiotica Media Ltd – based in Devon near the city of Exeter. As you will be unsurprised to learn it is a web development company – so if you need beautiful, functional websites and applications that are a joy to use, look no further.

I have been so busy that our main website still isn’t ready, but we now have a delicious looking blog up and running.

Symbiotica Media Development Ltd - web design & development in Devon

If you read flipflops.org regularly, you will rightly guess that we will be working with CakePHP quite a lot, but current projects also make extensive use of WordPress and Tarzan AWS. I’m also built and am using a great a little, lightweight XML template engine based on the Page Controller pattern, and hopefully more Django soon.

Sneak Preview

At the moment I’m working on an e-commerce project using the Amazon Product Advertising API. The website is called www.science-fictions.co.uk, and as the name suggests its theme is Science Fiction Books and Fantasy Literature.

The project is built on my brand new CakePHP based CMS system and the Tarzan AWS library which makes connecting to and utilizing Amazon web services, whilst not a breeze, rather enjoyable.

The website is hurtling along at an astonishing rate and with any luck, the first version should be up and live early next week.

www.Science-Fictions.co.uk - Books for Sci Fi and Fantasy lovers

Messing about with Tarzan and the Amazon AAWS web service

At the moment I building a couple of applications running of the Amazon AWS web services – in a nutshell e-commerce sites that utilize products available via Amazon or companies selling through Amazon and then let you check out using Amazon’s secure checkout (the site owner gets commission on each product sold).

The system is great, but it is huge and there are an awful of options. The documentation is good, but quite hard to navigate and sometimes quite confusing, basically it just boils down to reading the API Docs.

I’ve been using the Tarzan AWS framework / toolkit / library to deal with the hassle of connecting to and being authenticated by the Amazon system. Tarzan is a great system, but again it boils down to reading the API as there aren’t really any tutorials.

Finding the OfferListingId

Products sold via Amazon are identified by all kinds of data including ISBN codes, ASIN (Amazon ID numbers), OfferListingIds etc. I guess the trick is knowing which one to use in given circumstances.

One real gotcha that held me up (I had to post on the Tarzan group to find the answer) was that Tarzan is designed to use the OfferListingId of a product to identify it at key points (e.g. adding a product to the remote cart) – my understanding of this is that it is because every item has an OfferListingId – but not every number has an ASIN (this could be wrong and it could be because of another reason entirely).

My problem was that I could not find the OfferListingIds of the products I wanted to add to the cart, and so was trying to use the ASIN. After an age of debugging and trying to figure out what the hell was wrong, I looked at the actual Tarazn code and discovered that it was set up to only deal with OfferListingIds – so I changed it to work with ASINs and the rest of my code started working how it was supposed to (i.e. I could now add items to my remote cart).

Ryan Parman (the guy who wrote Tarzan) kindly explained that the OfferListingId is only contained in certain responses from Amazon – I had been requesting a result set which did not include the OfferListingId – problem solved. It turns out that the OfferListingId is returned if you request a ‘Large’ or ‘Offers’ response group, I had been using the ‘Medium’ group thinking that less data to work with would make my life easier. Silly me.

Serialize SimpleXML problems

When you add your first product to the remote Amazon shopping cart you have to use the create_cart() method. This creates a cart object and adds product(s) to it. Part of the response is a CartId which you need to use to access the cart again in future requests. The logical place for this is a Session.

My responses from Amazon via Tarzan pop out as SimpleXML objects, very handy and easy to work with. Unless you forget that PHP won’t let you serialize native objects… There are various solutions but my quick and dirty solution was to use type casting to change the SimpleXML object to a string e.g.

1
2
3
4
5
6
7
8
9
10
11
 
$response = $aaws->cart_create($item, $opt, AAWS_LOCALE_UK);
 
    if(isset($response->body->Cart->CartId)){
 
        $this->Session->write('Cart.CartId', (string)$response->body->Cart->CartId);
	$this->Session->write('Cart.URLEncodedHMAC', (string)$response->body->Cart->URLEncodedHMAC);
	$this->Session->write('Cart.CartItemId', (string)$response->body->Cart->CartItems->CartItem->CartItemId);
 
 
}

And it works like a treat.

(This is also worth a read: Serialize and Unserialize SimpleXML in php)

Flirting with Django – part 3 – setting plural model names in admin

This is probably a bit obvious to any experienced Django user, but it took me a bit of digging to find.

In Django when you create a model to use the automatic admin interface you have to add it to the admin.py file.

Here is an example which only includes a ‘news’ model:

1
2
3
4
5
6
7
8
 
from s2.portfolio.models import News
from django.contrib import admin
 
class NewsAdmin(admin.ModelAdmin):
    pass
 
admin.site.register(News)

The trouble is that it shows up in your Django admin interface as ‘Newss’ which is obviously a bit lame.

The answer is quite simple once you know how, you need to add ‘Meta’ information the model class (I believe this is an example of an ‘internal class’). The ‘Meta’ class contains information about each model such as the ordering with which records should be displayed in the admin etc. This is documented in the Django documentation here.

Example news model including the Meta information

1
2
3
4
5
6
7
8
9
10
11
12
13
14
 
class News(models.Model):
    title = models.CharField(max_length=200)
    summary = models.CharField(max_length=200)
    description = tinymce_models.HTMLField()
    slug = models.CharField(max_length=200)
    live = models.BooleanField(default=1)
    date = models.DateField()
 
    def __unicode__(self):
        return self.title
 
    class Meta:
        verbose_name_plural = 'News'

Like most things, easy when you know how!