I'll tell you how I made my CMS, which is used on many of my sites.
Requests go through a router (I do not know, but maybe this is not the correct name for this method).
I must say that my system is not perfect and it will not suit everyone, but my sites work fine on it.
The structure of the engine:
/ - root
- - classes - classes
- - - engine.php - main class
- - - route.php - router (request handler)
- - controllers - controllers
- List item
- - - controller_index.php - the main module, will be launched at this call - site.ru/
- - - controller_messages.php - test module
- - index.php - the main file, it accepts all requests
- - .htaccess - well, it's understandable
I'll start in order, perhaps.
htaccess
RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-l RewriteRule ^(.*)$ index.php?route=$1 [L,QSA]
index.php
/* разные настройки (вкл. ошибок и т.п.) */ function __autoload($class_name) { // авто подключение классов и модулей $file = $_SERVER['DOCUMENT_ROOT'] . '/' . (substr_count($filename, 'controller') ? 'controllers' : 'classes') . '/' . strtolower($class_name) . '.php'; if ( file_exists($file) ) include_once($file); } /* безопасное соединение с базой данных, файл лежит перед корнем сайта если вдруг упадет php, логин и пароль к базе данных никто не сможешь увидеть */ include_once('../db-site.php'); route::delegate(); // обрабатываем запросы, подключаем и запускаем необходимый модуль engine::run(); // стартуем движок
engine.php - / classes /
class engine { /** * переменные движка * */ public static $alias, $content ; /** * Вывод 404 ошибки * */ public static function away() { header('HTTP/1.0 404 Not Found'); exit('404 Not Found'); } /** * Обработка запроса * * @param array $alias массив с параметрами */ public static function alias($alias) { foreach($alias as $k => $v) if ( !empty($v) ) $alias[$k] = $v; else unset($alias[$k]); self::$alias = $alias; } /** * Стартер движка * */ public static function run($alias) { echo self::$content; } }
route.php - / classes /
class route { public static function delegate() { $route = empty($_GET['route']) ? '' : $_GET['route']; // проверка запроса if ( empty($route) ) $route = 'index'; // если запрос пуст, то есть - http://site.ru/ engine::alias(explode('/', $route)); // разбираем запрос на массив, site.ru/one/two -> array('one', 'two') $route = engine::$alias[0]; // достаем первый, он будет модулем - one $file = '/controllers/controller_' . $route . '.php'; if ( !is_file($file) ) engine::away(); // если модуль не найден - 404 Not Found $route = 'controller_' . $route; if ( !class_exists($route) ) engine::away(); // если модуль найден, а класс не найден - 404 Not Found $controller = new $route(); // создаем экземпляр класса $controller->delegate(engine::$alias); // запускаем модуль и передаем параметры запроса } }
controller_messages.php - / controllers /
class controller_messages { function delegate($alias) { return self::$alias[0](); // [0] - это первый параметр. Например, site.ru/messages } function messages() { switch(engine::$alias[1]) { case 'add' : $ex = 'add message'; break; case 'edit' : $ex = 'edit message'; break; default : $ex = 'all messages'; break; } core::$content = $ex; } }
controller_index.php - / controllers /
class controller_index { function delegate($alias) { core::$content = 'index page.. engine ok!'; } }
Everything, the system is ready!
Now, when opening the main page, the module controller_index.php will be launched and the text index page.. engine ok! is displayed index page.. engine ok! .
On this system, I have to handle AJAX and ordinary POST requests, a mobile version , as well as a cool parser with conditions that simplifies the work at times.
Questions in the comments.