Routing in Php and decorator pattern
Posted
by
Joey Salac Hipolito
on Stack Overflow
See other posts from Stack Overflow
or by Joey Salac Hipolito
Published on 2012-12-13T16:53:12Z
Indexed on
2012/12/13
17:03 UTC
Read the original article
Hit count: 297
I do not know if I am using the term 'routing' correctly, but here is the situation:
I created an .htaccess
file to 'process' (dunno if my term is right) the url of my application, like this :
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]
Now I have this :
http://appname/controller/method/parameter
http://appname/$url[0]/$url[1]/$url[2]
What I did is:
- setup a default controller, in case it is not specified in the url
- setup a Controller wrapper
I did it like this
$target = new $url[0]()
$controller = new Controller($target)
The problem with that one is that I can't use the methods in the object I passed in the constructor of the Controller:
I resolved it like this :
class Controller {
protected $target;
protected $view;
public function __construct($target, $view) {
$this->target = $target;
$this->view = $view;
}
public function __call($method, $arguments) {
if (method_exists($this->target, $method)) {
return call_user_func_array(array($this->target, $method), $arguments);
}
}
}
This is working fine, the problem occurs in the index where I did the routing, here it is
if(isset($url[2])){
if(method_exists($controller, $url[1])){
$controller->$url[1]($url[2])
}
} else {
if(method_exists($controller, $url[1])){
$controller->$url[1]()
}
}
where $controller = new Controller($target)
The problem is that the method doesn't exist, although I can use it directly without checking if method exist, how can I resolve this?
© Stack Overflow or respective owner