Custom PHP URL to Controller mapping similar to Symfony2
I wanna make a simple URL to Controller mapping very much like what Symfony2 does. But that's all I want from Symfony2, rest of it is just too much for me.
For those who don't know what Symfony2 does:
blog_home:
pattern: /blog
defaults: { _开发者_JAVA百科controller: BlogBundle:Blog:index }
blog_show:
pattern: /blog/{slug}
defaults: { _controller: BlogBundle:Blog:show }
in a YAML config file.
YAML doesn't matter to me at all. I just wanna achieve the same functionality. To be able to map custom URLs to controller functions.
Maybe an open source mapping class or routing framework? Maybe some tutorials? Ideas to make my own? Any suggestions would be helpful.
I should mention I'm no PHP whiz, I know just enough or maybe a little less than enough. Which is why I don't wanna get into a full featured framework.
This is my url routing framework:
function route($url, $map) {
foreach($map as $re => $fn) {
if(preg_match("~^$re$~", $url, $args)) {
list($class, $method) = explode(".", $fn);
return call_user_func_array(
array(new $class, $method),
array_slice($args, 1));
}
}
error_404();
}
The $map is an array whose keys are regular expressions to match the url against and the values are strings "ClassName.method", like
$map = array(
"/blog/(.+)" => "BlogController.show",
"/blog" => "BlogController.blog",
"/foobar/(\d+)/(\w+)" => "Foobar.stuff",
);
The routing function finds the first matching pattern, instantiates a class and calls a method passing regexp subgroups as arguments. So, an url "/foobar/123/hello" will be routed to Foobar->stuff(123, 'hello')
.
精彩评论