url 使用 PHP 和 .htaccess 进行路由

url routing with PHP and .htaccess

我想使用 MVC 模式将我的逻辑从表示和数据中分离出来。

好吧,我一直在寻找我。但事实是,我什至不知道要搜索什么。

我正在尝试在 php 中设置 MVC 框架。我正在关注 youtube 上的教程,但我被困在路由点。

我读了很多指南,每一个指南都以不同的方式教授东西,只会造成更多的混乱。

重点是:

我有一个包含一些指令的 .htaccess 文件(但问题是我不知道所有这些指令的含义。我从来不理解 htaccess 逻辑)

Options -MultiViews
RewriteEngine On

#I think this sets the base url of the site?
RewriteBase /~caiuscitiriga/mvc/public

#What does this mean??
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f

#AND THIS?!
RewriteRule ^(.+)$ index.php?url= [QSA,L]

然后我有这些 php 脚本:

Index.php

<?php

require_once '../app/init.php';

$app = new App();

init.php

<?php

require_once 'core/App.php';
require_once 'core/Controller.php';

App.php

别问我为什么用filter_varrtrim 。因为这正是我想要弄清楚的。正如我之前所说,这段代码不是我的。我确定技巧完全在 .htacess 和 App.php 中,但我不明白其中的逻辑

class App{


    protected $controller = 'home';
    protected $method = 'index';
    protected $params = [];


    public function __construct()
    {
        print_r($this->parseUrl());
    }

    public function parseUrl()
    {
        if(isset($_GET['url']))
        {
            return $url = explode('/', filter_var(rtrim($_GET['url'], '/'), FILTER_SANITIZE_URL));
        }
    }
}

Controller.php

<?php

class Controller{

}

home.php

<?php

class Home extends Controller{

    public function index()
    {
        echo 'home/index';
    }
}

如果我通过这个 url: localhost/~caiuscitiriga/mvc/public/home/index/maxine
我得到这个:Array ( [0] => home [1] => index [2] => maxine )

为什么?!!?我的意思是,这是正确的。但是为什么??

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ index.php?url= [QSA,L]

我读上面的内容是,如果请求不是目录,也不是文件,则获取路径并将其传递给 index.php 内部,并使用 url 属性作为路径。

所以现在

//example.com/big/bad/mamma

映射到

 //example.com/index.php?url=big/bad/mamma

如果你愿意,你可以调用上面的脚本。

然后您的解析 url 将采用 url ('big/bad/mamma') 的值,如果有一个尾部斜杠,则将其删除。然后在遇到正斜杠的任何地方拆分字符串。所以你最终得到了三个部分。这就是你的数组中的内容。

来自manual

FILTER_SANITIZE_URL 过滤器将删除除字母、数字和 $-_.+!*'(),{}|\^~[]`<>#%";/? 之外的所有字符: @&=.

但如果你想理解其中的部分,请将其分解:

$url = $_GET['url'];
var_dump($url);
$url = rtrim($url, '/');
var_dump($url);
$url = filter_var($url, FILTER_SANITIZE_URL);
var_dump($url);
$url = explode('/', $url);
var_dump($url);