简体   繁体   English

在PHP mvc中路由URL的最有效方法?

[英]Most efficient way to route urls in a PHP mvc?

I'm developing a simple php mvc that'll do the bare minimum but work how I need it too, it's my first time using an mvc approach over prodcedural so I'm learning as I go .. 我正在开发一个简单的 php mvc,它可以做到最低限度,但也是我需要它的工作方式,这是我第一次使用mvc方法而不是prodcedural所以我正在学习,因为我去...

While developing I've accidentally created it in a strange sort of style, currently the main .htaccess contains pretty much all of the physical rewrites, for example the forum is: 在开发过程中我偶然以一种奇怪的方式创建它,目前主要的.htaccess包含几乎所有的物理重写,例如论坛是:

RewriteRule ^forum/([a-zA-Z0-9_]+)_([0-9]+)/$                    index.php?controller=forum&method=showThread&urlTitle=$1&threadId=$2 [L] 
RewriteRule ^forum/([a-zA-Z0-9_]+)_([0-9]+)/all/([0-9]+)$        index.php?controller=forum&action=showThread&urlTitle=$1&threadId=$2&page=$3 [L]

How it works at the moment is that all urls are directed to index.php and it then takes which controller and method to use from the url using: 目前的工作原理是所有网址都指向index.php,然后使用以下网址从网址中使用哪个控制器和方法:

index.php 的index.php

$actionName = $_GET['action'];
$controllerName = ucfirst(strtolower($_GET['type'])).'controller';

$controller = new $controllerName;
$controller->$actionName();

controller/forumcontroller.php 控制器/ forumcontroller.php

class forumcontroller{

    function showThread() {

        $thread = new Thread($_GET['threadId'], $_GET['uriTitle']); 
        require "templates/thread.php";
    }

but this means it's possible for users to go to locations I don't want them to have access too, such as: 但这意味着用户可以前往我不希望他们也可以访问的位置,例如:

/public_html/templates/index.php

What I think I need? 我认为我需要什么?

I think instead the main .htaccess should look something like this? 我认为主要的.htaccess看起来应该是这样的?

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ index.php?url=$1 [L,QSA]

and then in index.php you'd use something like: 然后在index.php中你会使用类似的东西:

$url = explode("/", `$_SERVER['QUERY_STRING']);`

$controller = $url[0];   //Returns "forum"
$data = $url[1];         //Returns the forum title and id

but with this approach I don't understand how you call the action inside the controller with just the data? 但是用这种方法我不明白你如何用数据调用控制器内的动作?

wouldn't you have to do something like: 你不需要做类似的事情:

 if(!$data)
     $controller->loadForum();
 elseif($data)
     $controller->loadForumThread($data);

Conclusion 结论

I'm just not understanding how to best do the routing for a site that has a lot of seo friendly urls in different formats, I understand how an mvc should work but I'm struggling to grasp the routing part and all the examples I come across seem extremely complex! 我只是不明白如何最好地为具有许多不同格式的seo友好网址的网站做路由,我理解mvc应该如何工作但是我很难掌握路由部分和我来的所有例子对面似乎非常复杂!

I'm really struggling to see how to code the .htaccess and controllers to handle lots of urls in different formats, like this: 我真的很难看到如何编码.htaccess和控制器来处理不同格式的大量网址,如下所示:

domain.com
domain.com/uploads
domain.com/profiles/username
domain.com/messages/inbox
domain.com/messages/createnew/userId
domain.com/forum/all/2
domain.com/forum/title_1/
domain.com/forum/title_1/all/3

Here is an approach that is similar to your second .htaccess example. 这是一种类似于第二个.htaccess示例的方法。

$request = explode('/', substr($_SERVER['REQUEST_URI'], 1));
// Clean request array of empty elements
foreach($request as $k => $v)
    // Clear any empty elements
    if(!$v) unset($request[$k]);
$request = array_values($request);  // Renumber array keys

This gives a numerically indexed array representing the requested URI. 这给出了一个表示请求的URI的数字索引数组。 The application can assume that the first value in the request is the name of the controller: 应用程序可以假设请求中的第一个值是控制器的名称:

if(count($this->request) == 0) 
    $request[] = 'DefaultController';  // Responsible for homepage
$this->controller = new $request[0]( $request );

I also pass a $context variable to the controller constructor, but that's out of scope for this question (it is responsible for database connection, current user data and session data). 我还将$context变量传递给控制器​​构造函数,但这超出了这个问题的范围(它负责数据库连接,当前用户数据和会话数据)。

After that, it simply dispatches the request: $this->controller->dispatch() 之后,它只是调度请求: $this->controller->dispatch()

Inside of the dispatch method, the controllers themselves are aware of the request array. 在调度方法内部,控制器本身知道请求数组。 In your URL list, for instance, let's look at the third example: domain.com/profiles/username : 例如,在您的URL列表中,我们来看第三个示例: domain.com/profiles/username

The controller would be named 'Profiles': 控制器将命名为“配置文件”:

class Profiles {
    private $request, $context;
    public function __construct($request, $context) {
        $this->request = $request;
        $this->context = $context;
    }

    public function dispatch() {
        if(count($this->request) == 2 && $this->request[1] == 'username') {
            // Load data from model for the requested username ($this->request[1])

            // Show View
        }
    }
}

There's better ways that you can map request vectors to actions, but hopefully you get the jist. 有更好的方法可以将请求向量映射到操作,但希望你得到了这个jist。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM