MVC reading the url for controller and action

2020-05-09 01:49发布

问题:

I wrote my own mvc for php, and it seems to be working fine for me. But i am having trouble with getting the controller and the action:

http://www.example.com/controller/action

this works fine but as soon as there are small changes to the url my code breaks appart. for example:

http://www.example.com/controller? thi breaks, saying the controller? doesn't exist,

http://www.example.com/controller/action? thi breaks, saying the action? doesn't exist,

i can't figure out why it takes the ? in there and if any body know a more robust to get the correct controller and action i would love to know.

here is my code:

all the request are redirected to the same index.php page using .htaccess

class Framework {

   ....

   private function setup() {
     $uri = (isset($_SERVER['REQUEST_URI']))?$_SERVER['REQUEST_URI']: false;
     $query = (isset($_SERVER['QUERY_STRING']))?$_SERVER['QUERY_STRING']: '';
     $url = str_replace($query,'',$uri);
     $arr = explode('/',$url);
     array_shift($arr);
     $this->controller =!empty($arr[0])?$arr[0]:'home';
     $this->action = isset($arr[1]) && !empty($arr[1])?$arr[1]:'index';
   }
}

回答1:

$_SERVER['QUERY_STRING'] does not include the ? so when you do $url = str_replace($query,'',$uri);, you are not replacing the ?. It's therefore looking for a controller named controller?

There are various ways around this

  • replace with '?'.$query
  • Use explode('?', $url) to separate the query string from the URI
  • Get the $_SERVER['REQUEST_URL'] (which doesn't include the query string), rather than getting the whole thing and then splitting out yourself

Personally I would go with the last option, because wherever the code is already written for you, it tends to be quicker and more robust than anything you can write.



回答2:

You should fix the problem by using an / before the ?