Reputation: 1805
I'm doing a router, well with routes, part of my learning and wanted to see if my approach worked. Yet this been bothering me recently, see right now I'm adding the routes in an array, then adding them to a main "manager".
So I got (pseudo sample) to this approach
<?php
$paths = array();
$paths[] = new routes_object('PATH',
array(
'controller'=> 'controllerName',
'action' => 'actionName'));
$router = new router_manager()->add($paths);
After adding all the routes, means it would more than 10 or so. Then to see if they match I've to iterate through them and check the match() function to start the extract process to get variables.
Is it okay to take this approach? Having a collection of objects in a array and iterating?
Upvotes: 1
Views: 348
Reputation: 117417
After adding all the routes, means it would more than 10 or so. Then to see if they match I've to iterate through them and check the match() function to start the extract process to get variables.
This leads me to think that you're concerned about performance. Don't.
This is a perfectly valid way of doing object oriented code. A loop with 10 items shouldn't impact noticeably on your applications performance. An object is not an expensive element in object oriented code. The more, the merrier.
Upvotes: 2
Reputation: 8496
I use regex in my routes.
So I get the query string and just loop through the array of routes trying find a match :)
$acs_routerTable = array(
'/^$/' => 'index_Controller', //default controller
'/^(authteste|modelteste|formsteste|scafftest|test)/' => 'index_Controller/$1',
);
And in the router class I have this:
private function getRoutes($givenroute) {
require($this->configData->pathroutes);
$newroute = null;
foreach ($acs_routerTable as $pattern => $value) {
if (preg_match($pattern,$givenroute,$match)) {
$newroute = preg_replace($pattern,$value,$givenroute);
return $newroute;
}
}
return $givenroute;
}
As you can see if it matches a route it will return that new route if not it will just return the route given :)
Upvotes: 2