turn URL route into funciton arguments php mvc

会有一股神秘感。 提交于 2019-11-29 12:10:38

The easiest way to handle this is to use the call_user_func_array() function. You would use it as follows:

call_user_func_array(array($controller, $method), $params);

$controller would be the controller object you have already created, and $method would be the controller's method. Then $params is an array of the parameters collected from the URI. You would just need to take out the controller/method portion of the URI.

You could also do this using Reflection, but this typically is slower than using the above method.

For anyone who wants to know what I ended up doing, the final code is below... (this is from my router.class.php)

<?php

$route = (empty($_GET['rt'])) ? '' : $_GET['rt'];
$this->route = explode('/', $route);

/*** a new controller class instance ***/
$class = $this->controller . 'Controller';
$controller = new $class($this->registry);

/*** load arguments for action ***/
$arguments = array();
foreach ($this->route as $key => $val) 
{
    if ($key == 0 || $key == 1)
    {
    }
    else
    {
        $arguments[$key] = $val;
    }
}

/*** execute controller action w/ parameters ***/
call_user_func_array(array($controller, $action), $arguments);

?>

if my URL was

http://mysite.com/documentation/article/3

my controller looks like this...

<?php

Class documentationController Extends baseController 
{

    public function article($article_ID = '')
    {
        echo $article_ID; //shows 3
    }

}

?>

Thanks for the help.

Simply put, RewriteRules handle this. However within each framework is more complex routing code that directs requests and data to the specific Controller.

My suggestion would be to look at the code within these other frameworks and research how they solve these problems. Those you mentioned are open source.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!