@@ -6,15 +6,26 @@ class RouterException extends \Exception {}
66class Router {
77 protected $ routes ;
88 protected $ supported_methods ;
9+ protected $ default_handlers ;
910
1011 protected function __construct () {
1112 $ this ->supported_methods = array ('GET ' , 'POST ' , 'PUT ' , 'DELETE ' );
1213 $ this ->routes = array ();
1314 foreach ($ this ->supported_methods as $ method ) {
1415 $ this ->routes [$ method ] = array ();
16+ $ this ->default_handlers [$ method ] = function ($ req , $ res ) {
17+ // All verbs will return a 404 by default
18+ $ res ->send ('Not found ' , 404 );
19+ };
1520 }
1621 }
1722
23+ /**
24+ * Retrieves the shared router instance
25+ *
26+ * @public
27+ * @return {Router}
28+ */
1829 static public function instance () {
1930 static $ instance ;
2031
@@ -25,6 +36,15 @@ static public function instance() {
2536 return $ instance ;
2637 }
2738
39+ /**
40+ * Looks for a matching registered route for the provided method and uri combination.
41+ *
42+ * @protected
43+ * @param {string} $method The HTTP verb of the request
44+ * @param {string} $uri The URI of the request
45+ * @param {array} $params Optional reference for extracted parameters
46+ * @return {function|false}
47+ */
2848 protected function match ($ method , $ uri , &$ params = null ) {
2949 if (isset ($ this ->routes [$ method ])) {
3050 foreach ($ this ->routes [$ method ] as $ route => $ handler ) {
@@ -140,7 +160,7 @@ public function process() {
140160
141161 if (false === ($ handler = $ this ->match ($ request ->method , $ request ->uri , $ params ))) {
142162 // Error case
143- $ response -> send ( ' Not found ' , 404 );
163+ $ this -> default_handlers [ $ request -> method ]( $ request , $ response );
144164 }
145165
146166 // route params applied to the request object
0 commit comments