开发者

Understing URL routing in MVC

开发者 https://www.devze.com 2023-01-14 03:51 出处:网络
I am trying to create a very basic MVC framework to better understand the pattern. I am having trouble understanding the URL routing part.

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'/


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:

 action_user_delete_john()
 action_user_delete('john')
 action_user('delete/john')
 generic_fallback_method('user/delete/john')

In your case, i'd define a set of user_<operation> methods (action_user_delete, action_user_edit etc) and a default action_user method which will be called when no operation param is provided and should handle urls like user/john

I find this technique quite flexible and powerful, but there's no standard, and you're free to invent your own.

0

精彩评论

暂无评论...
验证码 换一张
取 消