I created an MVC router based on knowledge of an MVC design pattern.
It will simply take a URL as a string (class/method/params...), then it will instantiate a requested class controller and call its method.
In my class, I call a controller method and then include the view at the same time to display data.
My questions are:
- Is this a valid MVC router?
- Is it good practice to make this class call include views for our application?
class FrontController {
//default view
private $view = 'index';
//default methode
private $method = 'indexMethode';
//default controller
private $controller = 'Page';
//this attribute to store data returned
private $data;
//to store methode parameters from url.
private $param;
public function __construct() {
//getting user url request
$url = $this->getUrl();
//checking user input
if (isset($url[0])) {
//getting class name from user input
$this->controller = ucwords($url[0]);
unset($url[0]);
}
//checking if class file exsiste if yes we include it
if(file_exists('controllers/'.$this->controller.'.php')){
require 'controllers/'.$this->controller.'.php';
}
//instantiating the demanded class
$this->controller = new $this->controller;
//getting demanded class method if it is demanded by user
if (isset($url[1])) {
if(method_exists($this->controller, $url[1]))
$this->method = $url[1];
}
//checking if there is a view for our request
if(file_exists('view/'.$url[1].'.php')){
//setting the sutable template for the methode
$this->view = $url[1];
unset($url[1]);
}
//Getting methode parameters from user input if exsist
$this->param = $url ? array_values($url) : [];
//Calling the methode and getting the result
$this->data = call_user_func_array([$this->controller,
$this->method], $this->param);
//Getting the sutable page for the responde to display it.
include 'view/' . $this->view . '.php';
}
//To get any private var in our class
public function __get($name) {
return $this->$name;
}
//Here we are gona take user input and devide it as array element
public function getUrl() {
//checking user input and filtring it for unwanted charecters
if (!empty($_GET['url'])) {
// remove / char from url
$url = rtrim($_GET['url'], '/');
//Checking url for unwanted chars
$url = filter_var($url, FILTER_SANITIZE_URL);
//forming array from url
$url = explode('/', $url);
//Sending back url array
return $url;
}
}
}