如何通过 MVC 中的 URL 访问控制器


How to access controller via URL in an MVC

我还没有找到一个非常简单的MVC框架。框架如何使仅通过 URL 访问控制器成为可能?我认为这与QUERY_STRING有关,但不是应该有?吗?

http://localhost/public/controllername

localhost/public位于:

C:'wamp'www'public'

其中包含一个索引.php

通常,这是通过使用.htaccess重写(Apache mod_rewrite)来完成的:

  1. 您可以使用.htaccess重写将每个不是静态文件的查询定向到您的主入口点,例如index.php,假设您使用 PHP 作为服务器端语言。
  2. 然后,从index.php中分析 URI,并在应用程序中建立一些路由。

快速示例:

.htaccess文件:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]

index.php文件:

$uri = $_SERVER['REQUEST_URI'];
$parts = explode('/', $uri);
// assuming you want /controller/action/* mapping
$controller = 'index'; // default
$action = 'index'; // default
if (isset($parts[0])) $controller = $parts[0];
if (isset($parts[1])) $action = $parts[1];
// now, you'd try to establish some logic to test wether this controller/action
// actually exists, and load it. I'll leave this up to you.

当然,这只是一个快速而粗略的示例,但应该让您了解如何执行此操作。

它可以解析 $_SERVER['REQUEST_URI']