Saturday, February 14, 2009

CakePHP Routing With Parameters

Anything you need to know with cakePHP routing can be found here.

Here is an example to illustrate routing with parameters.

/config/routes.php

Router::connect(
'/:controller/:year/:month/:day',
array('action' => 'index', 'day' => null),
array(
'year' => '[12][0-9]{3}',
'month' => '(0[1-9]|1[012])',
'day' => '(0[1-9]|[12][0-9]|3[01])'
)
);


Parameters can be access like this:

/controllers/controller.php

function index(){
// params is stored in $this->params
$year = $this->params['year'];
$month = $this->params['month'];
$day = $this->params['day'];

//
}

Friday, February 13, 2009

Increase Performance of Loop with Large Arrays

In PHP, this is how we usually loop through arrays:


<?php
for ($i=0; $i<count($big_array); $i++){
//
}
?>


Having this approach, program will try to count the $big_array every time it loops and it may cause some performance issues. To make it more efficient, we should code it this way:


<?php
for ($i=0, $n=count($big_array); $i<$n; $i++){
//
}
?>


It does the counting during initialization only.

How to Route Admin Actions in CakePHP 1.2

This is how to setup the routing:

Router::connect('/admin/:controller/:action/*', array('admin'=>'true','prefix'=>'admin', 'controller'=>'controller', 'action'=>'action'));

Thursday, February 12, 2009

Indenting Tree List in Form Input Select using '&nbsp;' as spacer

This is the scenario in cakePHP 1.2.

In your controller, you have an action:


function add() {
...
$categories = $this->Listing->Category->generatetreelist(null, null, null, '&nbsp;');
$this->set(compact('categories','keywords','metros','states'));
}


where '&nbsp;' is your spacer.

Your view will have something like this:


...
echo $form->input('Category');
...


The above combination will display a drop down menu with the '&nsbp;' printed as '&nbsp' and not as a space. So how would you do it in cakePHP 1.2?

The key here is in the view file.

instead of the above statement, you should have this:


...
echo $form->input('Category', array('escape' => false));
...


Hope this one helps.