J3.x

Создание плагина для Joomla

From Joomla! Documentation

Revision as of 01:28, 7 July 2015 by Kanta (talk | contribs) (Created page with "В этом руководстве описаны основы разработки своего плагина. Большинство плагинов состоит из о...")
Other languages:
Bahasa Indonesia • ‎Deutsch • ‎English • ‎Nederlands • ‎español • ‎français • ‎português • ‎русский • ‎中文(台灣)‎
Joomla! 
3.x
series

Система плагинов в Joomla! 1.5 была очень мощной и гибкой. Плагины можно использовать не только для обработки событий, вызванных ядром приложения и его расширениями, но и для того, чтобы сделать сторонние дополнения более мощными и расширяемыми. Изменения в Joomla! 2.5/3.x в отличие от 1.5 в основном касаются имен событий.

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

Создание установочного файла

Как и любые расширения для Joomla, плагины легко устанавливаются в виде .zip файлов (.tar.gz тоже поддерживается), но архив должен содержать правильно составленный XML файл. Вот пример XML файла для плагина поиска по категориям.

<?xml version="1.0" encoding="utf-8"?>
<extension version="3.1" type="plugin" group="search">
	<name>plg_search_categories</name>
	<author>Joomla! Project</author>
	<creationDate>November 2005</creationDate>
	<copyright>Copyright (C) 2005 - 2013 Open Source Matters. All rights reserved.</copyright>
	<license>GNU General Public License version 2 or later; see LICENSE.txt</license>
	<authorEmail>admin@joomla.org</authorEmail>
	<authorUrl>www.joomla.org</authorUrl>
	<version>3.1.0</version>
	<description>PLG_SEARCH_CATEGORIES_XML_DESCRIPTION</description>
	<files>
		<filename plugin="categories">categories.php</filename>
		<filename>index.html</filename>
	</files>
	<languages>
		<language tag="en-GB">en-GB.plg_search_categories.ini</language>
		<language tag="en-GB">en-GB.plg_search_categories.sys.ini</language>
	</languages>
	<config>
		<fields name="params">

			<fieldset name="basic">
				<field name="search_limit" type="text"
					default="50"
					description="JFIELD_PLG_SEARCH_SEARCHLIMIT_DESC"
					label="JFIELD_PLG_SEARCH_SEARCHLIMIT_LABEL"
					size="5"
				/>

				<field name="search_content" type="radio"
					default="0"
					description="JFIELD_PLG_SEARCH_ALL_DESC"
					label="JFIELD_PLG_SEARCH_ALL_LABEL"
				>
					<option value="0">JOFF</option>
					<option value="1">JON</option>
				</field>

				<field name="search_archived" type="radio"
					default="0"
					description="JFIELD_PLG_SEARCH_ARCHIVED_DESC"
					label="JFIELD_PLG_SEARCH_ARCHIVED_LABEL"
				>
					<option value="0">JOFF</option>
					<option value="1">JON</option>
				</field>
			</fieldset>

		</fields>
	</config>
</extension>

Как можно заметить, он похожа на другие инсталляционные XML файлы для Joomla!. Нужно только обратить внимание на запись group="xxx" в разделе <extension>, а также на дополнительную информацию в разделе <filename> . Эта информация сообщает Joomla!, в какую папку копировать файл и в какую группу будет добавлен плагин.

If you are creating a plugin that responds to existing core events, the group="xxx" attribute would be changed to reflect the name of existing plugin folder for the event type you wish to augment. e.g. group="authentication" or group="user". See Plugin/Events for a complete list of existing core event categories. In creating a new plugin to respond to core events it is important that your plugin's name is unique and does not conflict with any of the other plugins that may also be responding to the core event you wish to service as well.

If you are creating a plugin to respond to non-core system events your choice for the group="xxx" tag should be different than any of the existing core categories.

Tip If you add the attribute method="upgrade" to the tag extension, this plugin can be installed without uninstalling an earlier version. All existing files will be overwritten, but old files will not be deleted.

Creating the Plugin

The object-oriented way of writing plugins involves writing a subclass of JPlugin, a base class that implements the basic properties of plugins. In your methods, the following properties are available:

  • $this->params: the parameters set for this plugin by the administrator
  • $this->_name: the name of the plugin
  • $this->_type: the group (type) of the plugin
  • $this->db: the db object (since Joomla 3.1)
  • $this->app: the application object (since Joomla 3.1)

In the following code example, <PluginGroup> represents the group (type) of the plugin, and <PluginName> represents its name. Note that class and function names in PHP are case-insensitive.

<?php
// no direct access
defined( '_JEXEC' ) or die;

class plg<PluginGroup><PluginName> extends JPlugin
{
	/**
	 * Load the language file on instantiation. Note this is only available in Joomla 3.1 and higher.
	 * If you want to support 3.0 series you must override the constructor
	 *
	 * @var    boolean
	 * @since  3.1
	 */
	protected $autoloadLanguage = true;

	/**
	 * Plugin method with the same name as the event will be called automatically.
	 */
	 function <EventName>()
	 {
		/*
		 * Plugin code goes here.
		 * You can access database and application objects and parameters via $this->db,
		 * $this->app and $this->params respectively
		 */
		return true;
	}
}
?>

Using Plugins in Your Code

Now that you've created your plugin, you will probably want to call it in your code. You might not: the Joomla! core has a number of built-in events that you might want your plugin code to be registered to. In that case you don't need to do the following.

If you want to trigger an event then you use code like this:

$dispatcher = JDispatcher::getInstance();
$results = $dispatcher->trigger( '<EventName>', <ParameterArray> );

It is important to note that the parameters have to be in an array. The plugin function itself will get the parameters as single values. The return value will consist of an array of return values from the different plugins (so it can also contain multilevel arrays).

If you are creating a plugin for a new, non-core event, remember to activate your plugin after you install it. Precede any reference to your new plugin with the JPluginHelper::importPlugin() command.