In my php project I use simple mvc created with this tutorial.
This is my Bootstrap.php file
<?php
class Bootstrap {
private $_url = null;
private $_controller = null;
private $_controllerPath = 'controllers/';
private $_modelPath = 'models/';
private $_errorFile = 'error.php';
private $_defaultFile = 'home.php';
public function init(){
$this->_getUrl();
if(empty($this->_url[0])){
$this->_loadDefaultController();
return false;
}
$this->_loadExistingController();
$this->_callControllerMethod();
}
private function _getUrl(){
$url = isset($_GET['url']) ? $_GET['url'] : null;
$url = rtrim($url, '/');
$url = filter_var($url, FILTER_SANITIZE_URL);
$this->_url = explode('/', $url);
}
private function _loadDefaultController() {
require $this->_controllerPath . $this->_defaultFile;
$this->_controller = new Home();
$this->_controller->index();
}
private function _loadExistingController() {
$file = $this->_controllerPath . $this->_url[0] . '.php';
if(file_exists($file)) {
require $file;
$this->_controller = new $this->_url[0];
$this->_controller->loadModel($this->_url[0], $this->_modelPath);
} else {
$this->_error();
return false;
}
}
private function _callControllerMethod() {
if(isset($this->_url[2])) {
if(method_exists($this->_controller, $this->_url[1])) {
$this->_controller->{$this->_url[1]}($this->_url[2]);
} else {
$this->_error();
}
} else {
if(isset($this->_url[1])) {
if(method_exists($this->_controller, $this->_url[1])) {
$this->_controller->{$this->_url[1]}();
} else {
$this->_error();
}
} else {
$this->_controller->index();
}
}
}
private function _error() {
require $this->_controllerPath . $this->_errorFile;
$this->_controller = new Error();
$this->_controller->index();
exit;
}
}
Controller
<?php
class Controller {
function __construct() {
$this->view = new View();
}
public function loadModel($name, $modelPath = 'models/') {
$path = $modelPath . $name .'_model.php';
if(file_exists($path)) {
require $modelPath . $name .'_model.php';
$modelName = $name . '_Model';
$this->model = new $modelName();
}
}
}
and user controller
<?php
class User extends Controller {
function __construct(){
parent::__construct();
}
public function registration() {
$this->view->render('user/registration');
}
public function enter() {
$this->view->render('user/enter');
}
public function create() {
$data = array();
$data['name'] = $_POST['name'];
$data['password'] = $_POST['password'];
$data['role'] = 2;
$this->model->create($data);
header('location: ' . URL);
}
}
I added client-side validation (name and password fields must not be empty) but I also would like to add server-side validation, but I don't understand how here return data if errors would be found back to view? I guess, I need to return errors and data from right filled fields.
$_GET? Not sure what you've tried so far.