PHP 链接的 mvc 路由问题

PHP mvc routing issue with links

我刚刚开始使用 PHP,并从关于 mvc 的 YouTube 教程开始。 一切顺利,但是当我开始开发自己的应用程序时,我遇到了路由问题(我认为)。

我的基础应用程序有 URL:localhost/mvc/public/。

在本教程中,我创建了一个 class,它在未指定时启动默认的家庭控制器和索引操作。所以 localhost/mvc/public/ 等同于 localhost/mvc/public/home/index.

在我看来我有:

<p>You need to <a href="profile/login">log in</a> or <a href="profile/register">register</a></p>

因此,当我从 url localhost/mvc/public/ 开始,然后单击 link,它会转到 localhost/mvc/public/profile/login,一切正常。 但是如果我写 url localhost/mvc/public/home/index 然后单击 link 我会转到 localhost/mvc/public/home/profile/index 这显然不起作用。 所以我的问题是 - 如何解决这个问题?

如果有人感兴趣,我可以post我的代码。

profile/register 是一个相对路径,所以它被添加到你已有的路径中。因为 /home/index 没有尾随 /,浏览器假定 home 是路径,index 是文件或资源名称,所以 home 被保留profile/register 添加到它。

解决方案:将链接中的路径更改为 /profile/register(前导 /)。开头的/告诉浏览器在裸域名后面加上路径,而不是选择相对于当前的路径。

可能更好:向您的应用程序添加一个 'basepath' 设置,通过该设置它知道基本路径是什么。在您的代码中,您可以在生成路径时使用此基本路径,例如:

<a href="<?=$basepath?>profile/register">

如果您将应用程序安装在根目录下,您可以将基本路径设置为/。在您的情况下,您可以将其设置为 /mvc/public/.

您也可以为其创建一个函数来包装设置,而不是变量。如果您搜索 "CodeIgniter base path",您会发现大量有关 CodeIgniter(一种流行的 MVC 框架)如何处理此问题的示例。