1

I need a way to quickly Route url's to a Class->Method() call using a configuration syntax not programming every case.

I have a web tool that takes a url and uses it to determine the class of object the url refers to, what class method to use, and the parameters of that method. I'm using .htaccess to channel all requests to index.php, so I read the path from $_SERVER['PATH_INFO'] and from there filter and explode it to get the individual components.

So www.example.com/user/view/12345 would create a user controller and call the view function which would show the user profile. In effect it would do the following:

$url = explode("/",trim($_SERVER['PATH_INFO'],"/");
$class = $url[0] . "_Controller";
$page = new $class;
echo call_user_func_array(array($page, $url[1]), $url);

Now this is an oversimplification of course, there are a lot of other moving parts not shown here, the __autoload(), the Page template system, etc, but you get the idea. The url is domain_name/class/function/[arg1]/[arg2]/[arg3]/... and the code quickly can determine what is needed to render the page.

Unfortunately, the site needs to match api rules dictated by policy. According the policy the url should be either:

domain_name/class/entityid/function_alias/[arg1]/[arg2]/[arg3]/... For tools that effect a specific entity

domain_name/class/function_alias/[arg1]/[arg2]/[arg3]/... For tools not tied to an individual entity

I have solved this but it is messy. Instead of calling the function in $url[1] for the class in $url[0] and passing it the remaining arguments, I determine the object class from the $url[0], instantiate it, then pass the url to the object's route($url) method. From there I have a messy combination of switch and if statements that translates the url to the proper class method.

What I need is some sort of configuration file or routing table where I could define what the url would look like. I know there are CMS's that do this sort of thing.

"user/$1"           => user/view/$1
"user/add"          => user/add
"user/$1/edit"      => user/edit/$1
"user/$1/key/$2"    => user/edit_key/$1/$2

What I need is a syntax and algorithm that will quickly determine the what the actual target class and method of a url is, instantiate it, and pass it the necessarily url values.

Tyson of the Northwest
  • 2,086
  • 2
  • 21
  • 34

1 Answers1

1

There probably do exist routing classes that will read a config file of some kind, but I couldn't easily find any.

Here are a couple of examples, though, or people creating relatively elegant solutions in pure PHP:
PHP Application URL Routing
http://blog.sosedoff.com/2009/07/04/simpe-php-url-routing-controller/

Do either of these suit your needs?

Of course you could also do these redirects purely with apache rewrites.

Community
  • 1
  • 1
Robin Winslow
  • 10,908
  • 8
  • 62
  • 91