J3.x:Developing создание/добавление MVC компонента на сайт
From Joomla! Documentation
Articles in This Series
- Introduction
- Developing a Basic Component
- Adding a View to the Site Part
- Adding a Menu Type to the Site Part
- Adding a Model to the Site Part
- Adding a Variable Request in the Menu Type
- Using the Database
- Basic Backend
- Adding Language Management
- Adding Backend Actions
- Adding Decorations to the Backend
- Adding Verifications
- Adding Categories
- Adding Configuration
- Adding ACL
- Adding an Install/Uninstall/Update Script File
- Adding a Frontend Form
- Adding an Image
- Adding a Map
- Adding AJAX
- Adding an Alias
- Using the Language Filter Facility
- Adding a Modal
- Adding Associations
- Adding Checkout
- Adding Ordering
- Adding Levels
- Adding Versioning
- Adding Tags
- Adding Access
- Adding a Batch Process
- Adding Cache
- Adding a Feed
- Adding an Update Server
- Adding Custom Fields
- Upgrading to Joomla4
This is a multiple-article series of tutorials on how to develop a Model-View-Controller Component for Joomla! Version.
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!, или вы можете напрямую загрузить архив
- As you follow through the steps of the tutorial you may find problems. In this case you may find it useful to read the Joomla page on How to debug your code.
- You can watch a video associated with this step in the tutorial at Step 2, Adding a View.
Добавление визуализации 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_com_helloworld>/site/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 (Note that some browsers may not copy and paste highlighted text correctly into a text editor. If you find this, then please try a different browser).
<?php
/**
* @package Joomla.Administrator
* @subpackage com_helloworld
*
* @copyright Copyright (C) 2005 - 2018 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 - 2018 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 - 2018 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 - 2018 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 Примечание - один и тот же код используется для всех папок
<html><body bgcolor="#FFFFFF"></body></html>
helloworld.xml
<?xml version="1.0" encoding="utf-8"?>
<extension type="component" version="3.0" method="upgrade">
<name>Hello World!</name>
<!-- The following elements are optional and free of formatting constraints -->
<creationDate>January 2018</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>
Код Пояснения
В случае, если вам любопытно, почему это работает так, как он делает.
helloworld.php
defined('_JEXEC') or die('Restricted access');
Это позволяет для безопасной точки входа в интерфейс Joomla! Платформа. JEXEC содержится подробное объяснение.
$controller = JControllerLegacy::getInstance('HelloWorld');
"JControllerLegacy" является базовым классом для Joomla! Контроллер. Для того, чтобы наш сайт использовал контроллеры, мы должны расширить этот класс в нашем компоненте. В "getInstance" статический метод "JControllerLegacy" класса создадим контроллер. В коде, приведенном выше, это будет инстанцировать объект класса контроллера по имени "HelloWorldController". Joomla будет искать объявление этого класса в <path_to_joomla>/htdocs/components/com_helloworld/controller.php.
$input = JFactory::getApplication()->input;
$controller->execute($input->getCmd('task'));
После того, как контроллер создан, мы инструктируем контроллер для выполнения задачи, как определено в URL: <yoursite>/joomla/index.php?option=com_helloworld&task=<task_name>. Если задача поставлена, задача по умолчанию 'display' будет принято. Когда дисплей не используется, 'view' переменная будет решать, что будет отображаться. Другими распространенными задачами являются save, edit, new и т. д.
$controller->redirect();
Контроллер может принять решение перенаправить страницу, обычно после того, как задание 'save' было завершено. Это последнее заявление заботится о фактическом перенаправлении.
Основные точки входа, helloworld.php, по сути, передает управление контроллеру, который обрабатывает задачу, которая была указана в запросе. Наш компонент конкретного контроллера больше ничего не делает, чем то, что делает родительский класс, потому наш класс контроллера пуст.
controller.php
class HelloWorldController extends JControllerLegacy
{
}
Когда ни одна задача не подается в запрос переменным, то будет выполнена задача по умолчанию. Сейчас это задача отображения по умолчанию. В JControllerLegacy классе есть такая задача. В нашем примере она будет показывать надпись с именем 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);
}
}
Представление задает текст для вывода и затем вызывает базовый класс дисплея.!Н!"JViewLegacy" является базовым классом для Joomla! View. В нашем случае этот метод будет отображать данные с использованием tmpl/default.php файла.
Caveat: If your view needs to load or otherwise embed individual JavaScript code, do not do that in the view, as the code might not get included when caching is enabled. Load those scripts in the controller instead. See the related issue on the issue tracker.
default.php
<h1><?php echo $this->msg; ?></h1>
Этот файл шаблона будет включен в JViewLegacy класс. Поэтому, здесь переменная $this имеет ввиду HelloWorldViewHelloWorld класса.
helloworld.xml
<version>0.0.2</version>
Обновляет номер версии.
<filename>controller.php</filename>
<folder>views</folder>
Рассказывает установщик приложения добавить controller.php и мнения/каталог
Содержание Компонента
В этот момент ваш компонент должен содержать следующие файлы:
1 | helloworld.xml | это XML-файл (манифест) файл, который говорит Joomla! как установить наш компонент. |
2 | site/helloworld.php | это сайт точка входа для компонента Hello World! |
3 | site/index.html | предотвращает листинг из веб-сервера содержимого директории |
4 | site/controller.php | файл, представляющий контроллер |
5 | site/views/index.html | предотвращает листинг из веб-сервера содержимого директории |
6 | site/views/helloworld/index.html | предотвращает листинг из веб-сервера содержимого директории |
7 | site/views/helloworld/view.html.php | файл определяющий вид |
8 | site/views/helloworld/tmpl/index.html | предотвращает листинг из веб-сервера содержимого директории |
9 | site/views/helloworld/tmpl/default.php | представление по умолчанию |
10 | admin/index.html | предотвращает листинг из веб-сервера содержимого директории |
11 | admin/helloworld.php | это точка входа администратора в компонент Hello World! |
12 | admin/sql/index.html | предотвращает листинг из веб-сервера содержимого директории |
13 | admin/sql/updates/index.html | предотвращает листинг из веб-сервера содержимого директории |
14 | admin/sql/updates/mysql/index.html | предотвращает листинг из веб-сервера содержимого директории |
15 | admin/sql/updates/mysql/0.0.1.sql | файл, позволяющий инициализировать версию схемы компонента com_helloworld. |
Пожалуйста, задавайте вопросы в https://github.com/joomla/Joomla-3.2-Hello-World-Component для создания любого кода или редактируйте исходный код на этой странице.