J3.x

Difference between revisions of "Creating a simple module/Developing a Basic Module/ru"

From Joomla! Documentation

< J3.x:Creating a simple module
(Created page with "Единственная строка, которую мы до сих пор не объяснили - это первая строка. Эта строка проверяе...")
Line 67: Line 67:
 
</source>
 
</source>
  
The one line that we haven’t explained so far is the first line. This line checks to make sure that this file is being included from the Joomla! application. This is necessary to prevent variable injection and other potential security concerns.
+
Единственная строка, которую мы до сих пор не объяснили - это первая строка. Эта строка проверяет, чтобы этот файл включался через приложение Joomla!. Это необходимо, чтобы предотвратить инъекции переменных и другие потенциальные проблем безопасности.
  
 
== Creating helper.php ==
 
== Creating helper.php ==

Revision as of 02:00, 26 April 2016

Other languages:
Bahasa Indonesia • ‎Deutsch • ‎English • ‎Nederlands • ‎español • ‎français • ‎português do Brasil • ‎русский • ‎中文(台灣)‎
Joomla! 
3.x
Урок
Создание простого модуля

Данная серия материалов написана о том, как разработать какой-либо модуль для Joomla! в версии Joomla 3.x. Вы можете пройтись по материалам этой серии с помощью выпадающего навигационного меню.

Начните со вступления и пройдитесь по материалам этой серии с помощью либо расположенной внизу навигационной кнопки, либо расположенного справа навигационного текстового блока (Материалы в этой серии).




Модули представляют собой легкие и гибкие расширения. Они используются для малых кусочков страницы, которые, как правило, менее сложные и могут быть замечены вокруг разных компонентов.

Вы можете увидеть много примеров модулей в стандартной установке Joomla!: - Меню - Последние Новости - Форма входа - и многое другое.

Этот учебник объяснит, как создать простой модуль "Привет мир". С помощью данного руководства вы узнаете основную файловую структуру модуля. Затем эта базовая структура может быть расширена, чтобы произвести более сложные модули.

Файловая Структура

Существует четыре основных файла, которые используются в стандартном шаблоне разработки модуля:

  • mod_helloworld.php - этот файл и является основной точкой входа для модуля. Он будет выполнять все необходимые процедуры инициализации, вызова вспомогательных средств для сбора необходимых данных а также шаблон, который будет отображать вывод модуля.
  • mod_helloworld.xml - этот файл содержит информацию о модуле. Он определяет файлы, которые должны быть установлены установщиком Joomla! и задает параметры конфигурации модуля.
  • helper.php - этот файл содержит вспомогательный класс, который используется, чтобы сделать фактическую работу в получении информации, которая будет отображаться в модуле (как правило, из базы данных или другого источника).
  • tmpl/default.php - это шаблон модуля. Этот файл будет принимать данные, собранные mod_helloworld.php и генерирует HTML, который будет отображаться на странице.

Создание mod_helloworld.php

Файл mod_helloworld.php будет выполнить три задачи:

  • включает файл helper.php который содержит класс, который должен быть использован для того чтобы собрать необходимые данные
  • вызывает соответствующий метод вспомогательного класса, чтобы получить данные
  • включает шаблон для отображения результата.

Вспомогательный класс определяется в нашем файле helper.php . Этот файл включается выражением require_once:

require_once dirname(__FILE__) . '/helper.php';

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

Наш вспомогательный класс, пока еще не был определен, но, когда он появится, он будет содержать один метод: getHello(). Для нашего простого примера, это на самом деле не надо этого делать - сообщение “Привет, мир!” , которое этот метод возвращает может быть просто включен в шаблон. Здесь мы используем вспомогательный класс, чтобы продемонстрировать эту базовую технику.

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

Метод вспомогательного класса вызывается следующим образом:

$hello = modHelloWorldHelper::getHello($params);

Полный файл mod_helloworld.php

Полный файл mod_helloworld.php выглядит следующим образом:

<?php
/**
 * Hello World! Module Entry Point
 * 
 * @package    Joomla.Tutorials
 * @subpackage Modules
 * @license    GNU/GPL, see LICENSE.php
 * @link       http://docs.joomla.org/J3.x:Creating_a_simple_module/Developing_a_Basic_Module
 * mod_helloworld 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.
 */

// No direct access
defined('_JEXEC') or die;
// Include the syndicate functions only once
require_once dirname(__FILE__) . '/helper.php';

$hello = modHelloWorldHelper::getHello($params);
require JModuleHelper::getLayoutPath('mod_helloworld');

Единственная строка, которую мы до сих пор не объяснили - это первая строка. Эта строка проверяет, чтобы этот файл включался через приложение Joomla!. Это необходимо, чтобы предотвратить инъекции переменных и другие потенциальные проблем безопасности.

Creating helper.php

The helper.php file contains that helper class that is used to retrieve the data to be displayed in the module output. As stated earlier, our helper class will have one method: getHello(). This method will return the ‘Hello, World’ message.

Here is the code for the helper.php file:

<?php
/**
 * Helper class for Hello World! module
 * 
 * @package    Joomla.Tutorials
 * @subpackage Modules
 * @link http://docs.joomla.org/J3.x:Creating_a_simple_module/Developing_a_Basic_Module
 * @license        GNU/GPL, see LICENSE.php
 * mod_helloworld 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.
 */
class ModHelloWorldHelper
{
    /**
     * Retrieves the hello message
     *
     * @param   array  $params An object containing the module parameters
     *
     * @access public
     */    
    public static function getHello($params)
    {
        return 'Hello, World!';
    }
}

There is no rule stating that we must name our helper class as we have, but it is helpful to do this so that it is easily identifiable and locatable. Note that it is required to be in this format if you plan to use the com_ajax plugin.

More advanced modules might include database requests or other functionality in the helper class method.

Creating tmpl/default.php

The default.php file is the template which displays the module output.

The code for the default.php file is as follows:

<?php 
// No direct access
defined('_JEXEC') or die; ?>
<?php echo $hello; ?>

An important point to note is that the template file has the same scope as the mod_helloworld.php file. What this means is that the variable $hello can be defined in the mod_helloworld.php file and then used in the template file without any extra declarations or function calls.

Creating mod_helloworld.xml

The mod_helloworld.xml is used to specify which files the installer needs to copy and is used by the Module Manager to determine which parameters are used to configure the module. Other information about the module is also specified in this file.

The code for mod_helloworld.xml is as follows:

<?xml version="1.0" encoding="utf-8"?>
<extension type="module" version="3.1.0" client="site" method="upgrade">
    <name>Hello, World!</name>
    <author>John Doe</author>
    <version>1.0.0</version>
    <description>A simple Hello, World! module.</description>
    <files>
        <filename>mod_helloworld.xml</filename>
        <filename module="mod_helloworld">mod_helloworld.php</filename>
        <filename>index.html</filename>
        <filename>helper.php</filename>
        <filename>tmpl/default.php</filename>
        <filename>tmpl/index.html</filename>
    </files>
    <config>
    </config>
</extension>

Manifest files explains the technical details of the elements used in the XML file.

You will notice that there are two additional files that we have not yet mentioned: index.html and tmpl/index.html. These files are included so that these directories cannot be browsed. If a user attempts to point their browser to these folders, the index.html file will be displayed. These files can be left empty or can contain the simple line:

<html><body bgcolor="#FFFFFF"></body></html>

which will display an empty page.

Since our module does not use any form fields, the config section is empty.

Conclusion

Module development for Joomla! is a fairly simple, straightforward process. Using the techniques described in this tutorial, an endless variety of modules can be developed with little hassle.