Skip to content

Pollenizer/CakePHP-Route-Plugin

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

19 Commits
 
 
 
 
 
 
 
 

Repository files navigation

CakePHP Route Plugin

A CakePHP Plugin for handling all your database-driven routing needs.

Many applications have the need to use "friendly" URLs like example.com/posts/a-tale-of-two-cities instead of the default "system" URLs like example.com/posts/view/123. Many developers have tended towards storing a slug field in the table itself. For example:

id title body slug created modified
123 A Tale of Two Cities It was the best of times, it was the worst of times... a-tale-of-two-cities 1859-04-30 09:00:00 1859-11-26 09:00:00

The problem with this approach is that the friendly URL is intrinsically tied to the model. What happens if you then want friendly URLs for Users, or Tags, or anything else? The answer is you'll need to add slug fields to all these models and adjust your routes configuration accordingly.

The CakePHP Route Plugin abstracts this functionality by providing a handy collection of classes to automate the creation, storage and use of custom routes. It lets you create links the "Cake" way:

$this->Html->link($post['Post']['title'], array(
    'controller' => 'posts',
    'action' => 'view',
    $post['Post']['id']
));

Sitting quietly and cleverly off to the side whilst it automatically handles both forward and reverse routing of your URLs.

Installation

  1. Copy the plugin to app/Plugin/Route
  2. Create the routes table by executing the schema generation SQL in app/Plugin/Route/Config/Schema/db_route.sql
  3. Enable the plugin in app/Config/bootstrap.php
CakePlugin::loadAll(array(
    'Route' => array(
        'routes' => true
    )
));

Usage

Automatically creating routes using the RoutableBehavior

Attach the Routable Behavior to the models for which you want to automatically create routes.

public $actsAs = array(
    'Route.Routable' => array(
        'template' => 'posts/:title'
    )
);

The template setting tells the behavior how to format the route. In the above example, if a new post is created with a title of "A Tale of Two Cities", the resulting route would be posts/a-tale-of-two-cities

About

A CakePHP Plugin for handling all your database-driven routing needs

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 3

  •  
  •  
  •  

Languages