public function __construct($method, $uri, $controller, $controller_method) { parent::__construct($method, $uri); // Check if the URI is a syntactically correct route URI if ($this->uri_validate() != 1) { throw new \Exception('Invalid route URI'); } $this->set_controller($controller); $this->set_controller_method($controller_method); }
public function __construct($root_directory = '', array $routes) { // Set the default project directory without any trailing slashes $this->root_directory = trim($root_directory, '/'); // Set the default timezone $this->set_timezone(); // Get the HTTP request $http_request = new http_request(); $http_request->fetch(); // Initialize the router $http_router = new http_router(); // Add all the routes to the router foreach ($routes as $route) { $http_router->add_route($route); } // Service the HTTP request and get the HTTP response $http_response = $http_router->service($http_request, $this->root_directory); // Send the HTTP response $http_response->send(); }
public function service(http_request $http_request, $root_directory) { $http_response = null; $route_selected = null; $parameters_path = array(); $parameters_query = array(); $controller_name = null; $controller_method = null; $controller_params = null; foreach ($this->routes as $route) { // Check if there is a method match if ($route->get_method() == $http_request->get_method()) { if ($root_directory) { // Remove the root directory from HTTP request URI $http_request->set_uri(str_replace($root_directory, '', urldecode($http_request->get_uri_canonical()))); } // Check if there is a URI match, and store all the path parameters $route_request_match = preg_match($route->get_uri_pattern(), $http_request->get_uri_canonical(), $parameters_path); // If the HTTP request matches an existing HTTP route... if ($route_request_match) { // Store the matched route $route_selected = $route; // Filter the path parameters array. Remove clutter from the array and only leave the clean, named key value pairs foreach ($parameters_path as $parameters_path_key => $parameters_path_value) { if (is_numeric($parameters_path_key)) { unset($parameters_path[$parameters_path_key]); } } // Store the query parameters $parameters_query_string = parse_url($http_request->get_uri(), PHP_URL_QUERY); parse_str($parameters_query_string, $parameters_query); // Get the controller name and the controller method from the selected route $controller_name = $route_selected->get_controller(); $controller_method = $route_selected->get_controller_method(); // Initialize the controller $controller = new $controller_name($http_request, $parameters_path, $parameters_query); // Run the controller method and get the HTTP response, or null in case of failure $http_response = $controller->{$controller_method}(); if (is_null($http_response)) { $http_response = new http_response(500); } break; } } } if (is_null($http_response)) { $http_response = new http_response(404); } return $http_response; }