MVC 读取控制器和动作的 url [英] MVC reading the url for controller and action

查看:20
本文介绍了MVC 读取控制器和动作的 url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为 php 编写了自己的 mvc,它似乎对我来说工作正常.但是我在获取控制器和操作时遇到了麻烦:

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

这工作正常,但只要对 url 进行小的更改,我的代码就会中断.例如:

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?这中断了,说 controller? 不存在,

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

http://www.example.com/controller/action?这中断了,说 action? 不存在,

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.

这是我的代码:

使用 .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';
   }
}

推荐答案

$_SERVER['QUERY_STRING'] 不包括 ? 所以当你做 $url = str_replace($query,'',$uri);,你不是在替换 ?.因此,它正在寻找名为 controller?

$_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

  • 替换为 '?'.$query
  • 使用 explode('?', $url) 将查询字符串与 URI 分开
  • 获取$_SERVER['REQUEST_URL'](不包括查询字符串),而不是获取整个内容然后自己拆分
  • 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.

这篇关于MVC 读取控制器和动作的 url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆