Through GET or POST requests from the engine's core, requests are made for certain modules, for example, the news viewing module on the site.

If the URL is http://site.ru/?module=readnews&id=3 , I do it like this:

if ($module=="readnews") { $news = new ReadNews(); $news->Display($id); } 

Etc. through if I go through all the modules. Or switch.

But I read somewhere that you can get rid of such a structure by writing a module connection class, but this class should be written so that such a structure does not occur inside.

How can this be organized?

    2 answers 2

    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.

    • Sorry, but not at all in the topic ... - Yoharny Babai
    • Did you watch the code? - Oleg
    • @exec, please see this [question] [1] [1]: hashcode.ru/questions/90539/… - ReinRaus
    • Why not in the subject? Everything is in the topic .. You will take a closer look at the code. There are many interesting things there. You yourself asked for the implementation of the engine, here everything is concrete and in the classes, not that I have ... - Dobby007
    • By the way @exec ... $ route = empty ($ _ GET ['route'])? '': $ _GET ['route']; you can remove it altogether)) and still read, saw something ... I don't remember where already ... - Dobby007

    Well, you can do it like this. The user enters the URL: http://site.ru/?module=readnews&id=3. We see that he wants to load a module (which one - we do not know). So, we take the value from the variable module and check whether there is such a module on the site. If the module is found, load it. The code will look something like this:

     $modules = array('readnews', 'readarticles', 'watchphotos','404module'); $module = $_GET['module']; if(in_array($module, $modules){ $Module = new $module($_GET); $Module->Display(); }else{ $module = '404module'; $Module = new $module($_GET); $Module->Display(); } 

    Let the module itself think over the parameters that were transferred to it in $ _GET and what it needs to display based on these parameters.

    The code is very rough. But to arrange it in the form of convenient classes - this is already agree ... a matter of technology ... I also recommend reading: Model-View-Controller . It describes a very convenient structural model of any software. Including for sites written in PHP. Called MVC. Voobim here is only yours. How to do it - and you will develop in the future what you did before. Another thing is that later it would be nice to code it yourself ...

    • Well, I just understand the design of MVC, so the question arose how to connect the modules to the model competently. - Fucking Babai
    • Well, this is what I personally do about the last time. Right now, people will pull up, they will say something else or advise you maybe ... - Dobby007