speedmax (owner)

Revisions

gist: 111010 Download_button fork
public
Public Clone URL: git://gist.github.com/111010.git
Embed All Files: show embed
named routes for cakephp, concept .php #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?
/**
$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));
  }
}
?>