【问题标题】:PHP mvc routing issue with links带有链接的PHP mvc路由问题
【发布时间】:2015-03-09 19:50:20
【问题描述】:

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

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

在本教程中,我创建了一个类,该类在未指定时启动默认主控制器和索引操作。所以 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/ 开始,然后单击一个链接时,它会转到 localhost/mvc/public/profile/login 并且一切正常。 但是,如果我写 url localhost/mvc/public/home/index 然后单击一个链接,我会转到 localhost/mvc/public/home/profile/index 这显然不起作用。 所以我的问题是 - 如何解决这个问题?

如果有人有兴趣,我可以发布我的代码。

【问题讨论】:

    标签: php url


    【解决方案1】:

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

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

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

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

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

    您也可以为它创建一个函数来包装设置,而不是一个变量。如果您搜索“CodeIgniter 基本路径”,您会发现很多 CodeIgniter(流行的 MVC 框架)如何处理此问题的示例。

    【讨论】:

    • 哈,不知道。但现在它转到 localhost/profile/register 而不是 localhost/mvc/public/profile/register
    • 好点。我认为解决这个问题的最好方法是添加路径设置。大多数 Web 应用程序都有这样的设置。这是因为相对路径会引起麻烦(正如您所注意到的),如果没有这样的设置,很难确定正确的路径。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-09
    • 1970-01-01
    • 2011-07-31
    相关资源
    最近更新 更多