Tuesday, December 28, 2010

Re: Help on Routes, should we use it ?

On Tue, Dec 28, 2010 at 10:14 AM, John Maxim <googol6@gmail.com> wrote:
> Refer to link below:
> http://book.cakephp.org/view/1541/Routes
>
> I don't understand. What does it accomplish ??
>
> Do we normally change the route as shown from the link above ?


Cake's routes default to:

/controller/action/param

So, if you had a BookController, to view a specific Book, you'd have
something like:

/books/view/42

... where 42 is the $id of this Book. However, you might instead want
to have URLs like:

/books/alice-in-wonderland

... in which case, you'd want a route like so:

Router::connect(
'/books/:slug',
array(
'controller' => 'books',
'action' => 'view',
),
array(
'slug' => '[-a-z0-9]+',
'pass' => array('slug')
)
);

So, Book.slug must be contain only lowercase alpha chars, integers, or
hyphens. And your Book model would have:

public $actsAs = array(
'Sluggable' => array(
'translation' => 'utf-8',
'separator' => '-',
'label' => 'title',
'length' => 64,
'overwrite' => true
)
);

Note the separator is a hyphen. It can also be an underscore, or
whatever. Just ensure the route regexp is set up for that.

Your action would then be defined as:

public function view($slug = null) {

Meanwhile, to create a link in a view (other mark-up aside):

foreach ($data as $d)
{
echo $this->Html->link(
$d['Book']['title'],
array(
'controller' => 'books',
'action' => 'view',
'slug' => $d['Book']['slug']
),
array('title' => 'read this book')
);
}

Note that 'slug' is passed in the first array, whereas it's in the
second array in the route definition. If it's an admin route, you pass
'admin' => 1 in the first array for both link and route, and the URL
would be '/admin/...' inthe route.

Check out the new CakePHP Questions site http://cakeqs.org and help others with their CakePHP related questions.

You received this message because you are subscribed to the Google Groups "CakePHP" group.
To post to this group, send email to cake-php@googlegroups.com
To unsubscribe from this group, send email to
cake-php+unsubscribe@googlegroups.com For more options, visit this group at http://groups.google.com/group/cake-php?hl=en

No comments: