J3.x

J3.x:Developing создание/добавление MVC компонента на сайт

From Joomla! Documentation

Revision as of 19:10, 9 January 2016 by Nikitm (talk | contribs) (Created page with "==Файл Детали==")
Joomla! 
3.x
Tutorial
Developing an MVC Component



This is a multiple-article series of tutorials on how to develop a Model-View-Controller Component for Joomla! VersionJoomla 3.x.

Begin with the Introduction, and navigate the articles in this series by using the navigation button at the bottom or the box to the right (the Articles in this series).



Примечания

== Примечания ==!Н!Этот учебник является частью Developing в создание MVC компонента для Joomla! 3.х: Учебное пособие. Вам рекомендуется прочитать предыдущие части учебника перед прочтением этой.

Вы можете следовать ниже, чтобы создать компонент Hello World!, или вы можете напрямую загрузить архив

Добавление визуализации Hello World!

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

Существует несколько способов обновления для Joomla! компонент. В этом уроке мы сосредоточимся на варианте 2.

1 Вручную добавить файлы в <path_to_joomla>/
2 Обновление при помощи Joomla! Менеджер расширений и оригинальный каталог, несжатый, используемые для установки компонента
3 Обновление при помощи Joomla! Менеджер расширений и обновление сервера

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

1 Обновление: helloworld.php <path_to_com_helloworld>/site/helloworld.php
2 Создать: controller.php <path_to_com_helloworld>/site/controller.php
3 Создать: index.html <path_to_com_helloworld>/site/views/index.html
4 Создать: index.html <path_to_com_helloworld>/site/views/helloworld/index.html
5 Создать: view.html.php <path_to_com_helloworld>/site/views/helloworld/view.html.php
6 Создать: default.php <path_to_joomla>/components/com_helloworld/views/helloworld/tmpl/default.php
7 Создать: index.html <path_to_com_helloworld>/site/views/helloworld/tmpl/index.html
8 Обновление: helloworld.xml <path_to_com_helloworld/helloworld.xml

Обновление Компонента Hello World!

Обновить Компонент Hello World! в Joomla! сайт, пожалуйста, выполните те же действия для исходной установки.

Файл Детали

site/helloworld.php

<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_helloworld
 *
 * @copyright   Copyright (C) 2005 - 2015 Open Source Matters, Inc. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

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

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

// Perform the Request task
$input = JFactory::getApplication()->input;
$controller->execute($input->getCmd('task'));

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

site/controller.php

<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_helloworld
 *
 * @copyright   Copyright (C) 2005 - 2015 Open Source Matters, Inc. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
/**
 * Hello World Component Controller
 *
 * @since  0.0.1
 */
class HelloWorldController extends JControllerLegacy
{
}

site/views/helloworld/view.html.php

<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_helloworld
 *
 * @copyright   Copyright (C) 2005 - 2015 Open Source Matters, Inc. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

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

/**
 * HTML View class for the HelloWorld Component
 *
 * @since  0.0.1
 */
class HelloWorldViewHelloWorld extends JViewLegacy
{
	/**
	 * Display the Hello World view
	 *
	 * @param   string  $tpl  The name of the template file to parse; automatically searches through the template paths.
	 *
	 * @return  void
	 */
	function display($tpl = null)
	{
		// Assign data to the view
		$this->msg = 'Hello World';

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

site/views/helloworld/tmpl/default.php

<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_helloworld
 *
 * @copyright   Copyright (C) 2005 - 2015 Open Source Matters, Inc. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */
 
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
?>
<h1><?php echo $this->msg; ?></h1>

index.html Note - the same code is used for all folders

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

helloworld.xml

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

	<name>Hello World!</name>
	<!-- The following elements are optional and free of formatting constraints -->
	<creationDate>December 2013</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 since J2.5 -->
		<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 link='index.php?option=com_helloworld'>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>

Code Explanation

In case you were curious as to why this works the way it does.

helloworld.php

defined('_JEXEC') or die('Restricted access');

This enables for a secure entry point into the Joomla! platform. JEXEC contains a detailed explanation.

$controller = JControllerLegacy::getInstance('HelloWorld');

JControllerLegacy is a base class for a Joomla! Controller. In order for our website to use controllers, we must extend this class in our component. The getInstance static method of the JControllerLegacy class will create a controller. In the code above, it will instantiate a controller object of a class named HelloWorldController. Joomla will look for the declaration of that class in <path_to_joomla>/htdocs/components/com_helloworld/controller.php.

$input = JFactory::getApplication()->input;
$controller->execute($input->getCmd('task'));

After the controller is created, we instruct the controller to execute the task, as defined in the URL: <yoursite>/joomla/index.php?option=com_helloworld&task=<task_name>. If no task is set, the default task 'display' will be assumed. When display is used, the 'view' variable will decide what will be displayed. Other common tasks are save, edit, new, etc.

$controller->redirect();

The controller might decide to redirect the page, usually after a task like 'save' has been completed. This last statement takes care of the actual redirection.

The main entry point, helloworld.php, essentially passes control to the controller, which handles performing the task that was specified in the request. Our component specific controller doesn't do anything more than the parent class already does, which is why our controller class is empty.

controller.php

class HelloWorldController extends JControllerLegacy
{
}

When no task is given in the request variables, the default task will be executed. It's the display task by default. The JControllerLegacy class has such a task. In our example, it will display a view named HelloWorld.

view.html.php

class HelloWorldViewHelloWorld extends JViewLegacy
{
	function display($tpl = null)
	{
		// Assign data to the view
		$this->msg = 'Hello World';
 
		// Display the view
		parent::display($tpl);
	}
}

The view sets up the text to be output and then calls the base display class. JViewLegacy is a base class for a Joomla! View. In our case, this method will display data using the tmpl/default.php file.

default.php

<h1><?php echo $this->msg; ?></h1>

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

helloworld.xml

<version>0.0.2</version>

Updates the version number.

<filename>controller.php</filename>
<folder>views</folder>

Tells installer application to add controller.php and the views/directory

Component Contents

At this point in the tutorial, your component should contain the following files:

1 helloworld.xml this is an XML (manifest) file that tells Joomla! how to install our component.
2 site/helloworld.php this is the site entry point to the Hello World! component
3 site/index.html prevents web server from listing directory content
4 site/controller.php file representing the controller
5 site/views/index.html prevents web server from listing directory content
6 site/views/helloworld/index.html prevents web server from listing directory content
7 site/views/helloworld/view.html.php file representing the view
8 site/views/helloworld/tmpl/index.html prevents web server from listing directory content
9 site/views/helloworld/tmpl/default.php the default view
10 admin/index.html prevents web server from listing directory content
11 admin/helloworld.php this is the administrator entry point to the Hello World! component
12 admin/sql/index.html prevents web server from listing directory content
13 admin/sql/updates/index.html prevents web server from listing directory content
14 admin/sql/updates/mysql/index.html prevents web server from listing directory content
15 admin/sql/updates/mysql/0.0.1.sql file allowing to initialise schema version of the com_helloworld component.
General Information

Please create a pull request or issue at https://github.com/joomla/Joomla-3.2-Hello-World-Component for any code descprepancies or if editing any of the source code on this page.