Как работает Template CMS?

В этой статье будет описано как работает Template CMS, как что подключается и откуда берется. Для начала рассмотрим как выглядит структура каталогов CMS, сразу скажу, она не сложная.

Описание папок:

/admin/ - в этой папке находится шаблон и стили админки. А также главный файл админки index.php.
/data/ - здесь хранятся все данные системы: страницы, новости, настройки, файлы...
/plugins/ - плагины хранятся тут. Плагины по умолчанию (box plugins) находятся /plugins/box/
/template_cms/ - система управления сайтом(движок) Template CMS.
/themes/ - здесь находятся темы оформления.

Рассмотрим как устроен движок Template CMS.

Описание папок:

/config/ - основная конфигурация системы и плагинов хранится тут.
/engine/ - основные модули движка, которые загружаются ядром по умолчанию.
/helpers/ - здесь находятся вспомогательные модули/хелперы движка, подгружаются ядром автоматически.

Движок работает таким образом:

Пользователь/Администратор запрашивает страницу index.php который подключает главный модуль движка — Core.php. Этот модуль подключает все остальные необходимые модули, хелперы, плагины.

Приведу исходный код ядра Core.php



    /**
     *	Template CMS - Content Management System. [template-cms.ru]
     *	Copyright (C) 2011 Romanenko Sergey / Awilum [awilum@msn.com]
     *
     *	Main Template CMS engine module. Core module.
     *	@package TemplateCMS
     *	@author Romanenko Sergey / Awilum
     *	@copyright 2011 Romanenko Sergey / Awilum
     *	@version $Id$
     *	@since 2.0
     *  @license http://opensource.org/licenses/gpl-license.php GNU Public License
     *  TemplateCMS is free software. This version may have been modified pursuant
     *  to the GNU General Public License, and as distributed it includes or
     *  is derivative of works licensed under the GNU General Public License or
     *  other free or open source software licenses.
     *  See COPYING.txt for copyright notices and details.
     */


    // If Admin ask engine then create path for admin
    if(isset($admin)) {
        if($admin) $admin_path = '../'; else $admin_path = ''; 
    } else {
	$admin_path = ''; 
    }

    
    // Include common engine config file
    include 'config/Common.php';   

    // Get php version id
    if(!defined('PHP_VERSION_ID')){
        $version = PHP_VERSION;
        define('PHP_VERSION_ID', ($version{0} * 10000 + $version{2} * 100 + $version{4}));
    }
    
    // Template CMS requires PHP 5.2.0 or greater
    if(PHP_VERSION_ID < 50200) {
        exit("Template CMS requires PHP 5.2.0 or greater.");
    }    

    // Setting error display depending on debug mode or not
    if(TEMPLATE_CMS_DEBUG) {
        // If PHP version >= 5.3.1 then also E_DEPRECATED
        if (PHP_VERSION_ID >= 50300){
            error_reporting(E_ALL | E_NOTICE | E_DEPRECATED);
        } else{
            error_reporting(E_ALL ^ E_NOTICE);
        }
    } else {
        // Turn off all error reporting
        error_reporting(0);    
    }
    

    // Compress HTML with gzip
    if(TEMPLATE_CMS_GZIP) {
        if(!ob_start("ob_gzhandler")) ob_start();
    } else {
        ob_start();
    }

    // Include security module
    include TEMPLATE_CMS_ENGINE_PATH.'Security.php'; 

    // Include filesystem module
    include TEMPLATE_CMS_ENGINE_PATH.'Filesystem.php';

    // Include ZIP module
    if($admin) include TEMPLATE_CMS_ENGINE_PATH.'Zip.php';
    
    // Include XML DB API
    include TEMPLATE_CMS_ENGINE_PATH.'XML.php';    

    // Include system preload module
    include TEMPLATE_CMS_ENGINE_PATH.'Preload.php';

    // Include Helpers module
    include TEMPLATE_CMS_ENGINE_PATH.'Helpers.php';

    // Init helpers
    initHelpers(TEMPLATE_CMS_HELPERS_PATH);

    // Sanitize URL to prevent XSS - Cross-site scripting
    runSanitizeURL();

    // Include Plugin API
    include TEMPLATE_CMS_ENGINE_PATH.'Plugins.php';

    // Include Plugins default filters
    include $admin_path.'template_cms/config/PluginsFilters.php';

    // Include Plugins default hooks
    include $admin_path.'template_cms/config/PluginsHooks.php';

    // Include Uri module
    include TEMPLATE_CMS_ENGINE_PATH.'Uri.php';  

    // Options API module
    include TEMPLATE_CMS_ENGINE_PATH.'Options.php';  

    // Init plugins
    initPlugins($admin_path.TEMPLATE_CMS_DATA_PATH.'plugins/');

    // Include Templates module.
    include TEMPLATE_CMS_ENGINE_PATH.'Templates.php';

Код документирован и думаю проблем с его прочтением у вас не возникнет — все довольно просто. Подключаются модули, инициализируются хелперы и плагины. Код системы написан в процедурном стиле и это нисколько не мешает расширять систему.

Благодаря хорошо организованной структуре движка и Plugin API можно изменить практически любую часть системы. Например админка полностью формируется с помощью Plugin API. Любой плагин по умолчанию (box) можно переписать и заменить. Также Plugin API позволяет добавлять новые возможности движку. Подробнее о разработке плагинов можно прочитать в этой статье.

Вопросы по движку и разработке хелперов и плагинов можете задавать в соответствующем разделе на форуме.


blog comments powered by Disqus