CakePHPCakePHP works very well if you only use the id to retrieve records in database. The problem is when you want to use more than one method to retrieve the same record, for example both the id and the slug.

Yes, you can use two different actions (for example, viewBySlug() for slugs), you can also give the same url using the routing (look here, route elements with regular expressions), but why not use a single action and make your life easier?

The same action, the same logic, the same view: just understand what is the parameter received from the (user) request and shape the search condition.
You can implement a callback function to determine the correct database field. If the choice is between id and slug simply use is_numeric() function (documentation)!

Just an example:

// app/Controller/YourModelNameController.php
public function view($param = null) {
	//There is a parameter?
	if(empty($param))
		throw new NotFoundException(__('Object does not exist'));

	$data = $this->Post->find('first', array(
		'conditions' => is_numeric($param) ? array('id' => $param) : array('slug' => $param),
		'fields' => array('title', 'text', 'created', 'modified'),
	));

	//Found at least one record?
	if(empty($data))
		throw new NotFoundException(__('Object does not exist'));

	$this->set('data', $data);
}

All this is possible thanks to the line 10:

'conditions' => is_numeric($param) ? array('id' => $param) : array('slug' => $param)

If $param is a number or a numeric string and then if it’s an id, then the search condition will be:

'conditions' => array('id' => '1')

Alternatively, if $param is a string (non-numeric string), the search condition will be:

'conditions' => array('slug' => 'your-post-title')

If you do not understand what happens, I advise you to review the ternary operator. As described in the documentation:

The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE.

Is this clear?

Note: please do not confuse is_numeric() with is_int() or is_integer() (documentation). The is_int() and the is_integer() function find whether the type of a variable is integer and not a numeric string, as in this case. If you’ll use is_int() or is_integer(), integers passed as parameters (get or post) will be always seen as strings, because they are numeric strings and not integer.

XHTML - Puoi usare questi tag: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>