Colleagues! How to check in the file Router.php - when entering any wrong link instead of the white screen was a 404 error. At the moment, because of routes like 'category/([a-z]+)' => 'catalog/category/$1', if you enter any incorrect links like site/category/errorlinkkk - displays the category you want. You need to trigger the 404 error. Code training, implement for your project, and train. Sincerely, Alexander!
File Router.phpclass Router { private $routes; //array that will store ranting public function __construct() { $routesPath = ROOT.'/config/routes.php'; //path to ranting $this->routes = include($routesPath); } private function getURI() { if (!empty($_SERVER['REQUEST_URI'])) { return trim($_SERVER['REQUEST_URI'], '/'); } } public function run() { //Get the query string $uri = $this->getUri(); //Check the presence of such a request in routes.php foreach($this->routes as $uriPattern => $path) { //Compare $uriPattern $uri if (preg_match("~^$uriPattern$~", $uri)) { //Get the internal path of the external rule $internalRoute = preg_replace("~$uriPattern~", $path, $uri); //Determine which controller and method to handle the request $segments = explode('/', $internalRoute); //Get the controller name $controllerName = ucfirst(array_shift($segments)).'Controller'; //Get the method name $actionName = 'action'.ucfirst(array_shift($segments)); //Connect the controller class file $controllerFile = ROOT . '/controllers/' . $controllerName . '.php'; if (file_exists($controllerFile)) { include_once($controllerFile); } //Create the object to call the method $parameters = $segments; $controllerObject = new $controllerName; $result = call_user_func_array(array($controllerObject, $actionName), $parameters); if($result != null) { break; } } } } }
Part of the code of routes.phpreturn array( // Item: 'product/([a-z]+)' => 'product/view/$1', // actionView in ProductController // Catalog: 'catalog' => 'catalog/index', // actionIndex in CatalogController // Category of the goods: '([0-9]+)/page-([0-9]+)' => 'catalog/category/$1/$2', // actionCategory in CatalogController 'category/([a-z]+)' => 'catalog/category/$1', // actionCategory in CatalogController );