如何进行 MVC 表单 url 格式化?

发布于 2024-10-11 01:59:00 字数 353 浏览 4 评论 0原文

我正在使用 PHP。我想从头开始创建 MVC 设置,以了解有关 MVC 工作原理的更多信息。我想使用带有斜杠的干净网址作为参数的分隔符。当涉及到 GET 方法表单时,人们如何做到这一点?或者人们会避免使用 GET 方法形式吗?

截至目前,我可以想象的方法是:

  1. 不要使用 GET 方法表单(尽管这使得在某些情况下更难让用户添加书签/链接)。
  2. 使用 AJAX 而不是表单提交(尽管您对 SEO 和 JS 禁用程序做了什么?)。
  3. 让页面使用 post 方法提交给自身,然后将 post vars 重组为 url,然后使用标头重新路由到该 url(似乎浪费资源)。

欢迎任何建议或推荐阅读。

I am using PHP. I want to create an MVC setup from scratch to learn more about how MVC works. I want to use clean urls with slashes as delimiters for the arguments. How do people do this when it comes to GET method forms? Or do people avoid GET method forms all together?

As of right now the ways I can imagine are:

  1. Don't use GET method forms (although this makes it harder to let users bookmark/link in some cases).
  2. Use AJAX instead of form submission (although what do you do for SEO and JS disablers?).
  3. Have page submit to itself with post method, then reform the post vars into an url, then rerout to that url using headers (seems like wasted resources).

Any suggestions or suggested reading welcome.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

娜些时光,永不杰束 2024-10-18 01:59:00

您可以使用像这样的 .htaccess 文件

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
</IfModule>

所以...如果 url 是

http://example.com/controller/action/param1/

您可以指定控制器和操作的路径,index.php 接收 var url [string]
你可以拆分它们来加载控制器...就像

$params = explode('/', $_GET['url']);
$controller = new $params[0];//load the controller
$controller->$params[1]($params[2]);//ejecute the method, and pass the param

You can use a .htaccess file like this

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
</IfModule>

So... if the url is

http://example.com/controller/action/param1/

you can path the controller and the action, the index.php receive the var url [string]
and you can split them to load the controller...like

$params = explode('/', $_GET['url']);
$controller = new $params[0];//load the controller
$controller->$params[1]($params[2]);//ejecute the method, and pass the param
儭儭莪哋寶赑 2024-10-18 01:59:00

获取变量和干净的 URL 并不相互矛盾。您始终可以拥有类似以下的网址

http://example.com/controller/action?value1=foo& value2=栏

另一种 URL 样式也可能类似于

http://example.com/controller/action/value1/foo/值2/条
或者
http://example.com/controller/action/foo/bar

在这两种情况下如果您想通过表单 GET 提交创建这些 URL,则必须使用 JavaScript 来组合正确的 URL,因此第一个解决方案可能更容易实现。

另一个问题是 POST 和 GET 表单提交之间的决定。 POST 更安全,但正如您所说,用户无法为其添加书签。

Get variables and clean URLs don't contradict each other. You can always have URLs like

http://example.com/controller/action?value1=foo&value2=bar

An alternative URL style could also look like

http://example.com/controller/action/value1/foo/value2/bar
or
http://example.com/controller/action/foo/bar

In these 2 cases if you want to create these URLs via a form GET submit you will have to use JavaScript to assemble the correct URL therefore the very first solution might be easier to implement.

Another question is the decision between POST and GET form submission. POST is more secure but as you said, users can't bookmark it.

因为看清所以看轻 2024-10-18 01:59:00

据我了解和我个人的经验,您的 3 点都不适用于如何处理 MVC 模式:

  1. 这是关于该主题的一个很好且经典的http://www.w3.org/2001/tag/doc/whenToUseGet.html ,基本上,如果生成的 URL 与内容相对应,例如,不要使用 GET 来传递要保存的信息,不要使用 POST 来传输要向用户显示的内容的 ID。这都是关于 Url Patterns 和重写的,您可能可以从 zend Framework router http://framework.zend.com/manual/en/zend.controller.router.html 基本上与 /?id=123 不同/weird-article-slug-123 当你知道你的 URL 模式是 ^[\w\d-]+([\d]+)$?

  2. 不,抱歉,AJAX 最多只是一种使用 JS 的方式,所以你的 AJAX 函数只能利用你的 MVC 后端应用程序,同样的方式......好吧,你的“正常”HTML 交互也是如此。不

  3. 这确实是“浪费资源”

As what i understand and my personal experience, none of your 3 points apply to how to handle a MVC Pattern:

  1. thats a good and classy one about the subject http://www.w3.org/2001/tag/doc/whenToUseGet.html , basically, get is the way to go if the resulting URL coresponds with content, for an Example, don't use GET to pass information you want to save, don't use POST do transmit a ID of content you want to show the User. Its all about Url Patterns, and rewrites, you can probably draw some inspiration from the zend framework router http://framework.zend.com/manual/en/zend.controller.router.html basically isn't /?id=123 the same as /weird-article-slug-123 when you know your URL Pattern is ^[\w\d-]+([\d]+)$?

  2. Nope, sorry, AJAX is at the very most, a way to use JS,so your AJAX Functions can only take advantage of your MVC Backend Application, the same way ... well, your "normal" HTML Interaction does.

  3. That would be "wasted resources" indeed

秋凉 2024-10-18 01:59:00

Cfreak 回答这个问题的最佳方法是深入研究各种 PHP 框架的源代码,看看他们是如何实现 MVC 方法的。我使用的 PHP 框架通常不包括 GET 数据,而仅依赖于 POST 数据。但是,可以通过查询字符串传递信息,请参见下面的示例。

通常,PHP MVC 框架中的 URL 看起来像这样:example.com/index.php/controller/action/arguments。通常使用 .htaccess 文件删除 index.php 部分。您的控制器是一个类,很可能继承自某种父控制器类。您的控制器具有您喜欢的接下来调用的任何操作/方法。您可以传递这些方法参数,通常是通过将它们附加到您的 URL 上来传递无限数量的参数。我希望这有助于让您对该结构有一个基本的了解。一切都从 index.php 开始,其中包括所有必需的配置文件,以及您可能需要的加载和必需的类:)

Cfreak the best way to answer this question would be for you digg into the various PHP frameworks source code to see how they've implemented an MVC approach. The PHP frameworks I've used typically exclude GET data and rely soly on POST data. However information can be passed via a query string see example below.

Typically URL's in PHP MVC frameworks look something like this: example.com/index.php/controller/action/arguments. The index.php part is usually removed by using an .htaccess file. You controller is a class, that most likely inherits from some sort of parent controller class. You controller has actions/methods whatever you prefer that are called next. You can pass these methods arguments, typically an unlimitied number of arguments by tacking them onto your URL. I hope that helps to give you a basic idea of the structure. Everything starts in index.php, which will include all your necessary config files, and load and required classes you may need :)

孤凫 2024-10-18 01:59:00

您所指的 URL 实际上与 MVC 没有什么关系。它是 REST 架构的实现。 (Wiki 文章

基本上,每个 URL 应该包含服务器所需的所有信息,而不是使用会话为了创建一个请求。

有几种方法可以做到这一点:

您可以使用 Apache 的 mod_rewrite 将 PATH 重写为正确的 GET 参数。例如,假设您有一个通常通过以下方式访问的用户管理模块:

http://your.domain/users.php?request=edit&id=<some id>

您可以放入 Apache:

RewriteRule ^users\/edit\/(\d+) /users.php?request=edit&id=$1

然后您可以使用以下方式处理相同的请求:(

http://your.domain/users/edit/<some id>

假设 ID 是一个数字)

如果所有这些都可以,那么这很容易您期望发出的请求非常简单。如果它们更具活力,那么设置起来就会变得更加困难。另一个缺点是,如果您想发布新框架,它要求您的用户至少能够通过 .htaccess 文件修改 Apache 配置。情况可能并非总是如此。

另一种方法是在代码中编写可以解析 URL 的逻辑。在这种情况下,您通常需要一个用于整个站点的控制脚本。 URL 类似于:

http://your.domain/users.php/edit/<some_id>

<?php

// get the part that appears after the script name
$parts = explode("/", $_SERVER['PATH_INFO'] );

$request = $parts[1];
$id = $parts[2];

// do somethign with the $request and the $id 

?>

如您所见,我的示例很简单,但使用选项 2,可以更轻松地使用更复杂的逻辑来完成各种操作。

希望有帮助。

What you're referring to with the URLs really has little to do with MVC. It is an implementation of REST architecture. ( Wiki Article )

Basically instead of using sessions, each URL should contain all of the information the server needs in order to create a request.

There are a couple of ways of doing this:

You can use Apache's mod_rewrite to rewrite a PATH to the proper GET parameters. For example say you have a user management module that is normally accessed with:

http://your.domain/users.php?request=edit&id=<some id>

You could put in Apache:

RewriteRule ^users\/edit\/(\d+) /users.php?request=edit&id=$1

Which would then allow you to address the same request with:

http://your.domain/users/edit/<some id>

(this is assuming ID is a number)

This is pretty easy to if all of the requests you expect to issue are pretty simple. If they are more dynamic then it gets harder to set it all up. The other drawback, if you were wanting to release your new framework, would be that it requires your user to have at least the ability to modify the Apache config through .htaccess files. That may not always be the case.

The alternative is write logic in the code that can parse the URL. In this case you usually need a controlling script for your entire site. The URL would be something like:

http://your.domain/users.php/edit/<some_id>

<?php

// get the part that appears after the script name
$parts = explode("/", $_SERVER['PATH_INFO'] );

$request = $parts[1];
$id = $parts[2];

// do somethign with the $request and the $id 

?>

As you can see, my example is simplistic but with option 2, it's easier to put much more complex logic to do all sorts of things.

Hope that helps.

奢望 2024-10-18 01:59:00

如果您有兴趣了解 MVC 框架/原则如何工作,有时最好的方法是首先了解如何实现它们(例如 CodeIgniter),然后您可以深入研究源代码/文档并了解其工作原理。

如果您想深入了解,请阅读 MOD_REWRITE 来解决您的 URL 问题。 GET 是可用的 - 您只需重写 URL 组件。

If you are interested in understanding how MVC frameworks / principles work sometimes the best way is first to understand how to implement them (something like CodeIgniter) you can then delve into the source code / documentation and understand how it works.

If you want to jump in at the deep end look into reading up on MOD_REWRITE to solve your URL concerns. GET is usable - you will just rewrite the URL components.

苯莒 2024-10-18 01:59:00

这个问题的答案取决于最终页面的类型。如果您要为用户提供一个包含单个项目的页面,我会将他们重定向到该页面,并带有一个漂亮的 URL。这对系统的需求并不大。

如果我要显示搜索查询的结果列表,我很可能会选择未格式化的 GET 查询。毕竟,这可能是一个有用的 URL,人们可能会传递它:

http://www.example.com/search?name=lonesomeday&site=stackoverflow

另一方面,如果只有一个字段,我可能会重定向到更简单的形式:

http://www.example.com/search/lonesomeday

当然是 YMMV。

The answer to this depends on what kind of page the resulting page will be. If you are going to give the user a page with a single item on it, I would redirect them to that page, with a pretty URL. That's not a huge demand on the system.

If I was going to show a list of results for a search query, I might well go for an unformatted GET query. This, after all, could be a useful URL, which people might pass around:

http://www.example.com/search?name=lonesomeday&site=stackoverflow

On the other hand, if there was only one field, I might well redirect to a more simple form:

http://www.example.com/search/lonesomeday

YMMV, of course.

来日方长 2024-10-18 01:59:00

忘记第二种方法——这是一个可怕的想法。

  1. 通常您可以在“GET 表单”中使用标准查询字符串 (...?a=b&c=d),因为它们的 URL 并不重要。
  2. 但是,如果您确实希望始终拥有漂亮的 URL,则必须发送表单(GET/POST - 无关紧要)并重定向用户:

    if (/* 表单已提交 */) {
        $data = array_map("urlencode", $_GET);
        $url = sprintf('/%s/%s/%s', $data['a'], $data['b'], $data['c']);
    
        header("位置:$url");
        echo "重定向:$url";
        出口;
    }
    
  3. 最终,如果您'如果担心服务器资源,您可以使用 JavaScript 来做到这一点:

    formReference.addEventListener("提交", function() {
        /* 与上面的 PHP 代码完全相同 */
    
        返回假;
    }, 错误的);
    

    当然,应该保留服务器端重定向,以防有人禁用了 JS。

Forget about second approach - it's an horrible idea.

  1. Usually you can use standard QueryString (...?a=b&c=d) in "GET forms" as their URLs aren't important.
  2. However, if you really want to have nice URLs all the time you'll have to send a form (GET/POST - doesn't matter) and redirect user:

    if (/* form has been submitted */) {
        $data = array_map("urlencode", $_GET);
        $url = sprintf('/%s/%s/%s', $data['a'], $data['b'], $data['c']);
    
        header("Location: $url");
        echo "Redirection: <a href='$url'>$url</a>";
        exit;
    }
    
  3. Eventually if you're worried about server resources you could use JavaScript to do that:

    formReference.addEventListener("submit", function() {
        /* do exactly the same as above PHP code */
    
        return false;
    }, false);
    

    Of course server-side redirection should be left in case somebody has disabled JS.

も星光 2024-10-18 01:59:00

您基本上要问的问题是如何实现 SEO 友好(搜索引擎优化友好)URL,格式为“www.site.com/controller/action/params”。这是通过使用 MOD_REWRITE 在几个关键文件夹中编辑 .htaccess 文件将服务器重定向到指定文件夹以获得 Web 应用程序的公共访问点来实现的。我会看一下这个 教程。前几段解释了如何获得您正在寻找的 URL。

The question you are basically asking is how to achieve SEO-friendly(Search Engine Optimization Friendly) URLs, in the format "www.site.com/controller/action/params". This is achieved through editing your .htaccess file in a few key folders to redirect server to specified folders to gain a common access point for your web application, using MOD_REWRITE. I would take a look at this tutorial. The first few paragraphs explain how to achieve the URLs you are looking for.

謸气贵蔟 2024-10-18 01:59:00

嘿,dqhendricks,
我正在做一些你正在做的事情——通过研究其他框架并从头开始创建一个框架来学习 MVC。

首先,您不应该使用 GET 来处理任何表单数据。请改用 POST 或 PUT。 POST 仅用于从 Web 服务检索信息。您几乎可以使用 GET 中的操作来操纵要检索的信息(例如排序顺序、页面等)。

关于您的观点:

1) 不要使用 GET 方法表单

正确。为了获得某种视图,您必须使用表单,这听起来是不正确的。

2) 使用 AJAX 而不是表单提交

没错。您的表单和 URL 应该可以在使用或不使用 JS 的情况下工作。

3) 让页面使用 post 方法提交给自身, 然后将 post vars 重组为 url,然后使用标头重新路由到该 url(似乎浪费资源)。

我不会说这是浪费资源。您的应用程序只需几毫秒。事实上,这正是我最终要做的。当前端控制器检测到 POST 的使用时,它将其分派给控制器,控制器对提交的数据执行必要的操作。根据结果​​,应用程序要么重定向客户端,要么呈现请求的页面(无重定向)。是的,它对任何 URL 的工作方式都是相同的。

同时,如果在 URL 中找到某个参数,前端控制器就会分派到相应的控制器。但这从未用于以任何方式处理数据。例如,当您在移动浏览器中浏览时想要使用 www 时,这用于记住首选域(www 或 mobile)。

另外,在我看来,浪费的资源是 APP 决定重定向到哪里(或者在 HTTP 查询或 PHP 会话中传递重定向 URL)。无论如何,实现替代方法都需要开发时间和服务器资源。

所以我认为#3 是可行的方法。

Hey dqhendricks,
I am doing somewhat what you are doing -- learning MVC by studying other frameworks and creating one from scratch.

First of all, you shouldn't use GET to handle any form data. Use POST or PUT instead. POST is used only for retrieving information from web service. You can use actions in GET pretty much to manipulate what information to retrieve (e.g. sort order, page, etc).

Regarding your points:

1) Don't use GET method forms

Correct. It sounds incorrect in the first place that in order to get a certain view you have to use a form.

2) Use AJAX instead of form submission

Exactly. Your forms and URL's should work both with and without JS.

3) Have page submit to itself with post method, then reform the post vars into an url, then rerout to that url using headers (seems like wasted resources).

I would not say this is wasted resources. It will take only milliseconds for your app. In fact this is exactly what I end up doing. When front controller detects use of POST, it dispatches it to the Controller which performs necessary actions on submitted data. Based on result, app either redirects client, or renders requested page (no redirect). And yes, it works the same way for ANY URL.

At the same time, if a certain param was found in the URL, Front controller dispatches to respective controller. But this is never used to process data in any way. For example, this is used to remember preferred domain (www or mobile) when you want to use www when you browse in mobile browser.

Also, IMO you could say that wasted resources would be APP deciding where to redirect (or passing redirect URL in HTTP query or PHP session). In any case, it takes both development time and server resources to implement alternative methods.

So #3 is the way to go, in my opinion.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文