J3.x

Criar um «Plug-in» para o Joomla!

From Joomla! Documentation

The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.
This page is a translated version of the page J3.x:Creating a Plugin for Joomla and the translation is 59% complete.
Other languages:
Bahasa Indonesia • ‎Deutsch • ‎English • ‎Nederlands • ‎español • ‎français • ‎português • ‎русский • ‎中文(台灣)‎
Joomla! 
3.x
série

A estrutura do plug-in para o Joomla! 1.5 era muito flexível e poderoso. Os plug-ins não podem ser utilizados apenas ​​para manipular os eventos acionados pela aplicação e pelas extensões principais, como também podem ser utilizados ​​para tornar as extensões de terceiros extensíveis e poderosas. A alteração principal do Joomla! 1,5 para a série 2.5 / 3.x foi a alteração nos nomes de eventos.

This How-To should provide you with the basics of what you need to know to develop your own plugin. Most plugins consist of just a single code file but to correctly install the plugin code it must be packaged into an installation file which can be processed by the Joomla! installer.

Criação do Ficheiro de Instalação

Como todas as extensões do Joomla, os plug-ins são facilmente instaldos como um ficheiro .zip (também são suportados .tar e .gz) mas deve ser incluído um ficheiro XML formatado corretamente. Como um exemplo, tem aqui um ficheiro de instalação XML para o plug-in da procura de categorias.

<?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>

As you can see, the system is similar to other Joomla! XML installation files. You only have to look out for the group="xxx" entry in the <extension> tag and the extended information in the <filename> tag. This information tells Joomla! into which folder to copy the file and to which group the plugin should be added.

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.

Criação do Plug-in

A maneira orientada a objetos de escrever plug-ins envolve escrever uma subclasse de JPlugin, uma classe base que implementa as propriedades básicas dos plug-ins. Nos seus métodos, estão disponíveis as seguintes propriedades:

  • $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)

Tip To use $this->db and $this->app, JPlugin tests if the property exists and is not private. If it is desired for the default objects to be used, create un-instantiated properties in the plugin class (i.e. protected $db; protected $app; in the same area as protected $autoloadLanguage = true;). The properties will not exist unless explicitly created.

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. The name must correspond with the plugin attribute of the filename element in the XML configuration that points at the plugin php file.

<?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;
	}
}
?>

Utilização de Plug-ins no Seu Código

Agora que criou o seu plug-in, provavelmente desejará chamá-lo no seu código. Poderá não: o Joomla! núcleo possui vários eventos integrados nos quais pode querer que o seu código de plug-in seja registado. Neste caso, não precisa de fazer o seguinte.

Se deseja acionar um evento, utilize um código como este:

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

É importante observar que os parâmetros precisam de estar numa matriz. A própria função do plug-in obterá os parâmetros como valores únicos. O valor de retorno consistirá numa matriz de valores de retorno dos diferentes plug-ins (para que também possa conter matrizes multiníveis).

Se estiver a criar um plug-in para um evento não essencial, lembre-se de ativar o seu plug-in depois de o instalar. Preceda qualquer referência ao seu novo plug-in com o comando JPluginHelper::importPlugin().