了解 MVC 中的 URL 路由
我正在尝试创建一个非常基本的 MVC 框架以更好地理解该模式。
我无法理解 URL 路由部分。 到目前为止,我已经了解到该 url 以这种格式携带 3 条基本信息: www.site.com/controller/method/querystring
因此,给出以下 URL:
www.site.com/user/delete/john
'user' is the controller
'delete' is the method of said controller
'john' is the query string
在我的框架中,我有它,因此如果 URL 中未指定控制器,则它默认为“index”。 如果 URL 中未指定方法,则默认为“show”(仅输出 html)。
这样我就可以访问 www.site.com,因为它的 url 中没有控制器或方法, 控制器变为“index”,方法变为“show”,因此仅加载索引视图。
但是,如果我不想在 url 中提供方法,而只想提供 www.site.com/controller/querystring 怎么办? 像这样: www.site.com/user/john
这将理想地加载约翰的个人资料。 但是,框架认为 url 中的“john”是要调用的方法,而不是查询字符串。
区分两者的标准、实用方法是什么?
ps:
我的 .htaccess 中有这个
RewriteRule ^(.*)$ index.php?$1 [L,QSA]
将 $_SERVER['QUERY_STRING'] 回显到 http://site/profile/john 给出“个人资料/约翰”/
I am trying to create a very basic MVC framework to better understand the pattern.
I am having trouble understanding the URL routing part.
So far i've understood that the url carries 3 basic pieces of information in this format:
www.site.com/controller/method/querystring
So given the following URL:
www.site.com/user/delete/john
'user' is the controller
'delete' is the method of said controller
'john' is the query string
In my framework, i have it so if a controller is not specified in the URL, it defaults to 'index'.
If a method if not specified in the URL, it defaults to 'show'(which just outputs the html).
this way i can go to www.site.com and since it doesn't have a controller or method in the url, the
controller becomes 'index' and method 'show', thus just loading the index view.
But what if i don't want to provide a method in the url, but just www.site.com/controller/querystring
like so:
www.site.com/user/john
This would ideally load the profile for John.
But, the framework thinks 'john' in the url is the method to invoke, and not the query string.
What is the standard, a practical way to distinguish between the two?
ps:
I have this in my .htaccess
RewriteRule ^(.*)$ index.php?$1 [L,QSA]
echoing $_SERVER['QUERY_STRING'] in to http://site/profile/john gives 'profile/john'/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我的控制器通常会找到一个处理程序方法,从更具体到不太具体进行搜索。如果找到一个方法,则会使用传递给它的参数“尾部”来调用它。例如,如果给出了
user/delete/john
,它会尝试按顺序调用:在您的情况下,我将定义一组
user_
方法(action_user_delete
、action_user_edit
等)和默认的action_user
方法,当未提供operation
参数时将调用该方法,并且应该处理像user/john
这样的 url我发现这种技术非常灵活和强大,但没有标准,你可以自由地发明自己的标准。
My controllers usually locate a handler method searching from more to less specific. If a method is found, it's called with the "tail" of parameters passed to it. For example, if
user/delete/john
is given, it attempts to call, in order:In your case, i'd define a set of
user_<operation>
methods (action_user_delete
,action_user_edit
etc) and a defaultaction_user
method which will be called when nooperation
param is provided and should handle urls likeuser/john
I find this technique quite flexible and powerful, but there's no standard, and you're free to invent your own.