Добавление компонента на сайт

Материал из Викиверситета
Эта статья является частью курса «Разработка MVC-компонента под Джумла 1.6».


В среде Joomla!1.6 авторы компонентов разделяют код на три основные части:

  • модели управляет данными,
  • контроллеры выполняют задачи, устанавливают и получают состояния моделей и запрашивают представления на экран,
  • представления отображают содержание в зависимости от типа (error, feed, html, json, raw, xml) и слой выбранный контроллерами.

Setting the controller[править]

В ядре кода Джумла для управления контроллером есть класс: JController. Этот класс должен быть наследован для использования в нашем компоненте.В файле site/helloworld.php (входная точка нашегокомпонентаHello World), введите эти строчки:

site/helloworld.php

<?php
// Заппретить прямой доступ к файлу
defined('_JEXEC') or die('Restricted access');

// импортировать библиотеку контроллера Джумлы
jimport('joomla.application.component.controller');

// Get an instance of the controller prefixed by HelloWorld
$controller = JController::getInstance('HelloWorld');

// Perform the Request task
$controller->execute(JRequest::getCmd('task'));

// Redirect if set by the controller
$controller->redirect();

getInstanceстатический метод класса JControllerсоздаст контроллер. В вышеуказанном коде он создаст контролер с именемHelloWorldController используя файл controller.php (это поведение по умолчанию)

С помощью Вашего любимого файл-менеджера или редактора создайте файл site/controller.php содержащий

site/controller.php

<?php
// Запретить прямой доступ к файлу
defined('_JEXEC') or die('Restricted access');

// импортировать библиотеку контроллера Джумлы
jimport('joomla.application.component.controller');

/**
 * Контроллер компонента Hellow Word
 */
class HelloWorldController extends JController
{
}

Если в переменной запроса не передано никаких заданий, будет выполнено задание по умолчанию.Это метод "отобразить" display.Класс JController имеет подобный метод. В нашем примере будет отоброжен просмотр с именем HelloWorld.

Setting the view[править]

With your favorite file manager and editor, create a file site/views/helloworld/view.html.php able to display the default view and containing

site/views/helloworld/view.html.php

<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');

// import Joomla view library
jimport('joomla.application.component.view');

/**
 * HTML View class for the HelloWorld Component
 */
class HelloWorldViewHelloWorld extends JView
{
	// Overwriting JView display method
	function display($tpl = null) 
	{
		// Assign data to the view
		$this->msg = 'Hello World';

		// Display the view
		parent::display($tpl);
	}
}

The display method of the JView class is called with the display task of the JController class. In our case, this method will display data using the tmpl/default.php file. With your favorite file manager and editor, create a file site/views/helloworld/tmpl/default.php able to display the default view and containing

site/views/helloworld/tmpl/default.php

<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
?>
<h1><?php echo $this->msg; ?></h1>

This template file will be included by the JView class. Therefore, here, $this refers to the HelloWorldViewHelloWorld class.

Packaging the component[править]

Content of your code directory

Create a compressed file of this directory or directly download the archive and install it using the extension manager of Joomla!1.6. You can test this basic component by putting index.php?option=com_helloworld in your browser address.

helloworld.xml

<?xml version="1.0" encoding="utf-8"?>
<extension type="component" version="1.6.0" method="upgrade">

	<name>Hello World!</name>
	<!-- The following elements are optional and free of formatting conttraints -->
	<creationDate>November 2009</creationDate>
	<author>John Doe</author>
	<authorEmail>john.doe@example.org</authorEmail>
	<authorUrl>http://www.example.org</authorUrl>
	<copyright>Copyright Info</copyright>
	<license>License Info</license>
	<!--  The version string is recorded in the components table -->
	<version>0.0.2</version>
	<!-- The description is optional and defaults to the name -->
	<description>Description of the Hello World component ...</description>

	<update> <!-- Runs on update; New in 1.6 -->
		<schemas>
			<schemapath type="mysql">sql/updates/mysql</schemapath>
		</schemas>
	</update>

	<!-- Site Main File Copy Section -->
	<!-- Note the folder attribute: This attribute describes the folder
		to copy FROM in the package to install therefore files copied
		in this section are copied from /site/ in the package -->
	<files folder="site">
		<filename>index.html</filename>
		<filename>helloworld.php</filename>
		<filename>controller.php</filename>
		<folder>views</folder>
	</files>

	<administration>
		<!-- Administration Menu Section -->
		<menu>Hello World!</menu>
		<!-- Administration Main File Copy Section -->
		<!-- Note the folder attribute: This attribute describes the folder
			to copy FROM in the package to install therefore files copied
			in this section are copied from /admin/ in the package -->
		<files folder="admin">
			<!-- Admin Main File Copy Section -->
			<filename>index.html</filename>
			<filename>helloworld.php</filename>
			<!-- SQL files section -->
			<folder>sql</folder>
		</files>
	</administration>

</extension>

Result: You will see by default the message contained in the variable $this->msg in the view.html.php file.

Навигация[править]

Предыдущий урок: Создание базового компонента.

Следующий урок: Добавление компонента в меню сайта.

Автор[править]

Разрешения[править]

При создании этой страницы использовались материалы страницы http://docs.joomla.org/Developing_a_Model-View-Controller_(MVC)_Component_for_Joomla!1.6_-_Part_02 согласно лицензии JEDL