Skip to content

Instantly share code, notes, and snippets.

@BrockReece
Created November 1, 2015 12:00
Show Gist options
  • Save BrockReece/7b0919ec9a6fdfb29759 to your computer and use it in GitHub Desktop.
Save BrockReece/7b0919ec9a6fdfb29759 to your computer and use it in GitHub Desktop.
CakePHP custom Article routes with article title instead of Id
<?php
App::uses('CakeRoute', 'Routing/Route');
App::uses('ClassRegistry', 'Utility');
class ArticleRoute extends CakeRoute {
/**
* Default model to load for the Article routes
*
* @var string
*/
protected $_modelName = 'Articles.Article';
/**
* Plugin name
*
* @var string
*/
protected $_plugin = 'articles';
/**
* The find method used for slug lookups
*
* @var string
*/
protected $_findMethod = 'routingArticleId';
/**
* Parses a string URL into an array.
*
* @param string $url The URL to parse
* @return mixed false on failure, or an array of request parameters
*/
public function parse($url) {
$this->_Model = ClassRegistry::init($this->_modelName);
$params = parent::parse($url);
if (!$params) {
return false;
}
try {
$params['pass'][0] = $this->_Model->find('routingArticleSlug', array(
'slug' => $params['slug'],
));
} catch (NotFoundException $e) {
return false;
}
return $params;
}
/**
* Reverse route plugin shortcut URLs. If the plugin and controller
* are not the same the match is an auto fail.
*
* @param array $url Array of parameters to convert to a string.
* @return mixed either false or a string URL.
*/
public function match($url) {
if (!is_array($url) || empty($url['plugin']) || $url['plugin'] != $this->_plugin || $url['controller'] != 'articles') {
return false;
}
switch ($url['action']) {
case 'view':
$url['pass'] = array();
try {
$url += $url['named'] = (array)$this->_Model()->find($this->_findMethod, !empty($url[0]) ? $url[0] : null);
unset($url[0]);
} catch (NotFoundException $e) {
return false;
} catch (NotFoundException $e) {
return false;
}
if (!$this->compiled()) {
$this->compile();
}
return $this->_writeUrl($url);
}
return parent::match($url);
}
/**
* Get a Article Model instance for doing lookups
*
* @return Article
*
* @throws PitchcareInvalidArgumentException if the model is not configured
*/
protected function _Model() {
return ClassRegistry::init($this->_modelName);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment