Created
May 13, 2009 13:25
-
-
Save speedmax/111010 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
<? | |
/** | |
$r = new ResourceRoute('Person'); | |
$r->people_path() => array('controller'=>'people', 'action' => 'index') | |
$r->new_person_path() => array('controller'=>'people', 'action' => 'add') | |
$r->person_path(1) => array('controller'=>'people', 'action' => 'read', 'id' => 1) | |
$r->edit_person_path(1) => array('controller'=>'people', 'action' => 'edit', 'id' => '1') | |
$r->delete_person_path(1) => array('controller'=>'people', 'action' => 'edit', 'id' => '1') | |
alternitively | |
url_for($person) | |
*/ | |
class ResourceRoute{ | |
protected $collection; | |
protected $element; | |
protected $routes = array(); | |
function __initialize($class) { | |
$this->element = strtolower(get_class($class)); | |
$this->collection = Inflector::pluralize($this->element);`` | |
} | |
function compile() { | |
$this->routes['read'] = "{$this->element}_path"; | |
$this->routes['index'] = "{$this->collection}_path"; | |
$this->routes['create'] = "new_{$this->element}_path"; | |
$this->routes['update'] = "edit_{$this->element}_path"; | |
$this->routes['delete'] = "delete_{$this->element}_path"; | |
} | |
function __call($method, $args) { | |
$routes = array_flip($this->routes); | |
$first = array_shift($args); | |
$second = array_shift($args); | |
if (is_int($first)) | |
$params = array('id' => $first); | |
elseif (is_object($params)) | |
$params = array('id' => $first->id); | |
$params = array_merge($params, $second); | |
if (isset($routes[$method])) | |
$action = $routes[$method]; | |
else throw new Exception('Unknow methods'); | |
return Router::url(array_merge(array( | |
'controller' => $this->collection, | |
'action' => $action | |
), $params)); | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment