Create php MVC application. Configuration files and creating routing file
Today we will begin to write code of our application. We’ll write configuration files, database connection class and routing class. Also we’ll create parent controller, model and view classes and controller and template for app main page.
First of all we need to start from index.php file. This file only includes config file (see index.php code).
Code lesson (index.php)
<?php
require_once("conf/config.php");
In the config file we’ll define common constants and include common files of our app (model, controller, view, database connection class and routing) and run method for define route (URL) of application (see conf.php).
Code lesson (conf.php)
<?php
define("ROOT", "/var/www/u0016495/data/www/cabinet.kamil-abzalov.ru");
define("CONTROLLER_PATH", ROOT. "/controllers/");
define("MODEL_PATH", ROOT. "/models/");
define("VIEW_PATH", ROOT. "/views/");
require_once("db.php");
require_once("route.php");
require_once MODEL_PATH. 'Model.php';
require_once VIEW_PATH. 'View.php';
require_once CONTROLLER_PATH. 'Controller.php';
Routing::buildRoute();
Now we need to write class for database connection. This class will be static. For connection establish I will use PDO.
Code lesson (db.php)
<?php
/**
** Класс конфигурации базы данных
*/
class DB{
const USER = "u0016495_cabinet";
const PASS = 123456;
const HOST = "localhost";
const DB = "u0016495_cabinet";
public static function connToDB() {
$user = self::USER;
$pass = self::PASS;
$host = self::HOST;
$db = self::DB;
$conn = new PDO("mysql:dbname=$db;host=$host", $user, $pass);
return $conn;
}
}
Now let’s talk about routing. As already mentioned, we create MVC app. Of course we needn’t to create folders and files for every section and page – it is absolutely wrong and unprofessionally. This task routing will do. In fact, when we watch web site pages, we ask it to do some task – give user list, open form and so on. Furthermore we can get users list and products list in the same page. In our application page will be controller and task will be action. Controller is class, and actions are methods of this class.
First of all we’ll define default controller and action – indexController, and index action. In other situations we will get a part of address, using $_SERVER[‘REQUEST_URI’] and aplit it into two parts. For example, /cabinet/users url implies including CabinetController and running users method.
In our routing file there were defined some rules for files naming. Files must start from capital letter with Controller prefix. For example IndexController, UserController and so on.
First of all we’ll define default controller and action – indexController, and index action. In other situations we will get a part of address, using $_SERVER[‘REQUEST_URI’] and aplit it into two parts. For example, /cabinet/users url implies including CabinetController and running users method.
In our routing file there were defined some rules for files naming. Files must start from capital letter with Controller prefix. For example IndexController, UserController and so on.
Code lesson (route.php)
<?php
/*
** Класс маршрутизации
** Урл http://cabinet.kamil-abzalov.ru/
** Урл http://cabinet.kamil-abzalov.ru/cabinet
** Урл http://cabinet.kamil-abzalov.ru/cabinet/users
** Урл http://cabinet.kamil-abzalov.ru/cabinet/orders/
** Урл http://cabinet.kamil-abzalov.ru/cabinet/orders?orderId=
*/
class Routing {
public static function buildRoute() {
/*Контроллер и action по умолчанию*/
$controllerName = "IndexController";
$modelName = "IndexModel";
$action = "index";
$route = explode("/", $_SERVER['REQUEST_URI']);
/*Определяем контроллер*/
if($route[1] != '') {
$controllerName = ucfirst($route[1]. "Controller");
$modelName = ucfirst($route[1]. "Model");
}
require_once CONTROLLER_PATH . $controllerName . ".php"; //IndexController.php
require_once MODEL_PATH . $modelName . ".php"; //IndexModel.php
if(isset($route[2]) && $route[2] !='') {
$action = $route[2];
}
$controller = new $controllerName();
$controller->$action(); // $controller->index();
}
public function errorPage() {
}
}
After this we need to create common parent controller class, model class and view class (see Controller.php, Model.php, View.php).
Code lesson (Controller.php)
<?php
class Controller {
public $model;
public $view;
protected $pageData = array();
public function __construct() {
$this->view = new View();
$this->model = new Model();
}
}
Code lesson(Model.php)
<?php
class Model {
protected $db = null;
public function __construct() {
$this->db = DB::connToDB();
}
}
Code lesson (View.php)
<?php
class View {
public function render($tpl, $pageData) {
include ROOT. $tpl;
}
}
Now we need to write code for IndexController and create view. For view (template for form authorization) I will use this template. We’ll define index action in IndexController, which calls render method of View class. It draw html in browser, accepting two parameters – html template and array with dynamic page data – page title, messages and so on. IndexModel we will implements in next lesson.
Code lesson (IndexController.php)
<?php
class IndexController extends Controller {
private $pageTpl = '/views/main.tpl.php';
public function __construct() {
$this->model = new IndexModel();
$this->view = new View();
}
public function index() {
$this->pageData['title'] = "Вход в личный кабинет";
$this->view->render($this->pageTpl, $this->pageData);
}
}
Code lesson (main.tpl.php)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><?php echo $pageData['title']; ?></title>
<meta name="vieport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/css/bootstrap.min.css">
<link rel="stylesheet" href="/css/font-awesome.min.css">
<link rel="stylesheet" href="/css/style.css">
</head>
<body>
<header></header>
<div id="content">
<div class="container">
<div class="row">
<div class="col-sm-6 col-md-4 col-md-offset-4">
<h1 class="text-center login-title">Sign in to continue to Bootsnipp</h1>
<div class="account-wall">
<img class="profile-img" src="https://lh5.googleusercontent.com/-b0-k99FZlyE/AAAAAAAAAAI/AAAAAAAAAAA/eu7opA4byxI/photo.jpg?sz=120"
alt="">
<form class="form-signin">
<input type="text" class="form-control" placeholder="Email" required autofocus>
<input type="password" class="form-control" placeholder="Password" required>
<button class="btn btn-lg btn-primary btn-block" type="submit">
Sign in</button>
<label class="checkbox pull-left">
<input type="checkbox" value="remember-me">
Remember me
</label>
<a href="#" class="pull-right need-help">Need help? </a><span class="clearfix"></span>
</form>
</div>
<a href="#" class="text-center new-account">Create an account </a>
</div>
</div>
</div>
</div>
<footer>
</footer>
<script src="/js/jquery.js"></script>
<script src="/js/bootstrap.min.js"></script>
<script src="/js/angular.min.js"></script>
<script src="/js/script.js"></script>
</body>
</html>
Code lesson (IndexModel.php)
<?php
class IndexModel extends Model {
}
0 Comments