Create php mvc app. Routing refactoring

Home » Tutorials » PHP+MySQL » Create php mvc app. Routing refactoring
After a long timeout I recorded a new tutorial in which we would make routnig refactoring. The reason of it is our application url structure. After refactoring our routing will be more flexible, will to handle url paths and GET parameters.

Code lesson (routing)

<?php

class Routing
{

    public static function buildRoute() {

        /* Контроллер и action по умолчанию */
        $controllerName = "IndexController";
        $modelName = "IndexModel";
        $action = "index";

        $route = explode("/", parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));

        $i = count($route)-1;

        while($i>0) {
            if($route[$i] != '') {
                if(is_file(CONTROLLER_PATH . ucfirst($route[$i]) . "Controller.php") || !empty($_GET)) {
                    $controllerName = ucfirst($route[$i]) . "Controller";
                    $modelName =  ucfirst($route[$i]) . "Model";
                    break;
                } else {
                     $action = $route[$i];
                }
            }
            $i--;
        }

        require_once CONTROLLER_PATH . $controllerName . ".php";
        require_once MODEL_PATH . $modelName . ".php";

        $controller = new $controllerName();
		$controller->$action();

    }

    public function errorPage() {

    }

}

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.

Pin It on Pinterest

Share This