Created
May 27, 2011 22:59
-
-
Save redoPop/996358 to your computer and use it in GitHub Desktop.
CakePHP custom Route class that restricts a route to a single extension.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Custom Route class that restricts a route to a single extension. | |
* Enables you to build controller actions that are only applied to specific | |
* extensions, e.g., '/posts.json' goes to PostsController::index_json while | |
* '/posts' goes to PostsController::index. | |
* | |
* To use, drop this into app/libs/routes/extension_specific_route.php and add | |
* the following to the top of app/config/routes.php: | |
* | |
* App::import('Lib', 'routes/ExtensionSpecificRoute'); | |
* | |
* To trigger it, specify the routeClass in the route's options array, along | |
* with the extension to match in the new key 'ext': | |
* | |
* Router::connect( | |
* '/posts', | |
* array('controller' => 'posts', 'action' => 'index_json'), | |
* array('routeClass' => 'ExtensionSpecificRoute', 'ext' => 'json') | |
* ); | |
* | |
* The 'ext' option can also be an array of multiple extensions (e.g., if you | |
* want to use the same controller action for .json and .xml requests.) | |
* | |
* @author joe bartlett (xo@jdbartlett.com) | |
* @license http://www.opensource.org/licenses/mit-license.php MIT License | |
* @see CakeRoute | |
*/ | |
class ExtensionSpecificRoute extends CakeRoute { | |
/** | |
* Checks to see if the given URL can be parsed by this route. | |
* If the route can be parsed an array of parameters will be returned; if not, | |
* false will be returned. String urls are parsed if they match the 'ext' | |
* option specified for this route. | |
* | |
* @param string $url The url to attempt to parse. | |
* @return mixed Boolean false on failure, otherwise an array or parameters | |
* @access public | |
*/ | |
function parse($url) { | |
$params = parent::parse($url); | |
// Determine the extension to be matched | |
if (empty($this->options['ext'])) { | |
$ext = array('html'); | |
} else { | |
$ext = (array)$this->options['ext']; | |
$ext = array_map('strtolower', $ext); | |
} | |
// Only match URL's using the extension $ext | |
if (preg_match('/\\.([\\w]+)$/', $_GET['url'], $matches)) { | |
if (!in_array(strtolower($matches[1]), $ext)) { | |
return FALSE; | |
} | |
} elseif (!in_array('html', $ext)) { | |
return FALSE; | |
} | |
return parent::parse($url); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Why don't you create a full github repository for this?