Skip to content

Instantly share code, notes, and snippets.

@paulredmond
Created September 13, 2010 17:30
Show Gist options
  • Save paulredmond/577685 to your computer and use it in GitHub Desktop.
Save paulredmond/577685 to your computer and use it in GitHub Desktop.
<?php
/**
* PluginRoute class.
*
* Route class for plugins that allows you to clean up urls for plugins
* without tons of calls to Router::connect() to shorten controller names in urls.
*/
class PluginRoute extends CakeRoute
{
/**
* match function.
*
* - Replaces underscores with dashes in action
* - Shortens controller names in urls.
*
* @access public
* @param array $url
* @return mixed
*/
public function match($url) {
if(empty($url['plugin'])) {
return parent::match($url);
}
# Ignore controller with the same name as plugin.
if(!self::isDefault($url['controller'], $url['plugin'])) {
$cases = array(
Inflector::singularize($url['plugin']) . '_',
Inflector::pluralize($url['plugin']) . '_',
);
$url['controller'] = str_replace($cases, '', $url['controller']);
# replace underscores with dashes (not allowed in function)
$url['action'] = str_replace('_', '-', $url['action']);
}
return parent::match($url);
}
/**
* Parses plugin routes.
* Makes sure that incoming urls match controller names in the plugin
* by adding the plugin name as a prefix.
*/
public function parse($url) {
$params = parent::parse($url);
if(empty($params)) { return false; }
if(!self::isDefault($params['controller'], $params['plugin']) && !self::hasPrefix($params['controller'], $params['plugin'])) {
$params['controller'] = $params['plugin'] . '_' . $params['controller'];
# Replace dashes with underscores to make a legitimate function.
$params['action'] = str_replace('-', '_', $params['action']);
}
return $params;
}
/**
* Checks to see if a controller has the plugin name as a prefix.
*/
private static function hasPrefix($controller, $plugin)
{
return (boolean) preg_match('/^'.$plugin.'_/', $controller);
}
/**
* Checks to see if the controller value equals plugin name (both singular and plural versions)
*/
private static function isDefault($controller, $plugin) {
if($controller == Inflector::singularize($plugin) || $controller == Inflector::pluralize($plugin)) {
return true;
}
return false;
}
}
<?php
App::import('Lib', array('routes/PluginRoute'));
Router::connect('/pluginname/:controller/:action/*', array('plugin' => 'pluginname'), array('routeClass' => 'PluginRoute'));
Router::connect('/pluginname/:controller', array('plugin' => 'pluginname', 'action' => 'index'), array('routeClass' => 'PluginRoute'));
@paulredmond
Copy link
Author

I'm sure this needs more testing, I haven't extensively tested the match method yet.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment