Компонент
A component is a kind of Joomla! extension. Components are the main functional units of Joomla!; they can be seen as mini-applications. An easy analogy would be that Joomla! is the operating system and the components are desktop applications. Created by a component, content is usually displayed in the center of the main content area of a template (depending on the template).
Most components have two main parts: an administrator part and a site part. The site part is what is used to render pages of your site when they are requested by your site visitors during normal site operation. The administrator part provides an interface to configure and manage different aspects of the component and is accessible through the Joomla! administrator application.
Joomla! comes with a number of core components, like the content management system, contact forms and Web Links.
Where to get Joomla! components?
A small selection of components is included with the default Joomla! installation but many more are available from the Joomla! Extensions Directory.
Installation of a component
If you want to install a component to your Joomla! installation, read more about Installing an extension here.
Recommended Reading
Developers
There are many articles, tutorials, references and FAQs which focus on component development. If this is your first time developing a component for Joomla, you should start with the Absolute Basics of How a Component Functions. If needed, you can visualise the control flow of a component with these diagrams.
Next, you will want to read our MVC tutorial Developing an MVC Component.
Once you have read the tutorial and/or tried the example component, you can focus more on the specifics of your component with additional articles. These are listed on the Component Development Portal or any of the supporting Portals for Development (Plugins, Modules or Templates).
Absolute Basics of How a Component Functions
This article is designed for Joomlaǃ beginners; it is designed to explain what a Joomlaǃ component is and how it functions. When a specific component example will benefit the tutorial, this article will refer to an example component named Hello Worldǃ.
- 1 What is a Joomlaǃ Component
- 2 Introduction to MVC
- 2.1 Model
- 2.2 View
- 2.3 Controller
- 3.1 Model
What is a Joomlaǃ Component [ править ]
A component is a kind of Joomla! extension. Components are the main functional units of Joomla!; they can be seen as mini-applications. An easy analogy would be that Joomla! is the operating system and the components are desktop applications. Created by a component, content is usually displayed in the center of the main content area of a template (depending on the template).
Most components have two main parts: an administrator part and a site part. The site part is what is used to render pages of your site when they are requested by your site visitors during normal site operation. The administrator part provides an interface to configure and manage different aspects of the component and is accessible through the Joomla! administrator application.
Joomla! comes with a number of core components, like the content management system, contact forms and Web Links.
In the Joomla! framework, components can be designed using a flat model (returns HTML code for the requested page) or Model-View-Controller (herein referred to as MVC) pattern.
Introduction to MVC [ править ]
MVC is a software design pattern that can be used to organize code in such a way that the business logic and data presentation are separate. The premise behind this approach is that if the business logic is grouped into one section, then the interface and user interaction that surrounds the data can be revised and customized without having to reprogram the business logic. MVC was originally developed to map the traditional input, processing, output roles into a logical GUI architecture.
Model [ править ]
The model is the part of the component that encapsulates the application’s data. It will often provide routines to manage and manipulate this data in a meaningful way in addition to routines that retrieve the data from the model. In general, the underlying data access technique should be encapsulated in the model. In this way, if an application is to be moved from a system that utilizes a flat file to store its information to a system that uses a database, the model is the only element that needs to be changed, not the view or the controller.
View [ править ]
The view is the part of the component that is used to render the data from the model in a manner that is suitable for interaction. For a web-based application, the view would generally be an HTML page that is returned to the user. The view pulls data from the model (which is passed to it from the controller) and feeds the data into a template which is populated and presented to the user. The view does not cause the data to be modified in any way, it only displays the data received from the model.
Controller [ править ]
The controller is responsible for responding to user actions. In the case of a web application, a user action is generally a page request. The controller will determine what request is being made by the user and respond appropriately by triggering the model to manipulate the data appropriately and passing the model into the view. The controller does not display the data in the model, it only triggers methods in the model which modify the data, and then pass the model into the view which displays the data.
Joomla! Component Framework Explained [ править ]
Model [ править ]
In the Joomla framework, models are responsible for managing the data. The first function that has to be written for a model is a get function. It returns data to the caller. For this example, the caller will be the HelloWorldViewHelloWorld view. By default, the model named HelloWorldModelHelloWorld residing in site/models/helloworld.php is the main model associated to this view. So let’s have a quick look at the naming conventions with an example, since the naming convention are the actual magic that make everything work: The class HelloWorldViewHelloWorld resides in site/views/helloworld/view.html.php and will make use of the class HelloWorldModelHelloWorld in the file site/models/helloworld.php Let’s just assume we want to use an imaginary view fluffy, you would have to have: The class HelloWorldViewFluffy which resides in site/views/fluffy/view.html.php. The view will make use of HelloWorldModelFluffy in the file site/models/fluffy.php. Note: the actual screen of the view: site/views/fluffy/tmpl/default.php is required as well to make this example work. Breaking any of these bold conventions will lead to errors or a blank page.
Accessing a Joomlaǃ Component [ править ]
First we need to access the Joomla! platform, which is always accessed through a single point of entry. Using your preferred web browser, navigate to the following URL:
1 user access /joomla/index.php 2 administrator access /joomla/administrator/index.php Hello World! example: localhost/joomla/index.php You can use the URL of the component, or a Menu in order to navigate to the component. In this article we will discuss using the URL.
1 user access /joomla/index.php?option=com_ 2 administrator access /joomla/administrator/index.php?option=com_ Hello World! example: localhost/joomla/index.php?option=com_helloworld
MVC Basic Directory Structure [ править ]
Components are stored in a directory within your Joomla! installation, specifically at:
The Hello World! component would be stored in htdocs//components/com_helloworld/. A basic component will contain the following files within its directoryː
- An HTML file that is just a security file with a background colorː index.html
- A PHP file that represents the controller itselfː controller.php
- A PHP file that loads the controller classː .php
- A PHP file that represents the model itselfː models/.php
- Another HTML file for background controlː models/index.html
- A PHP file containing the default viewː views//tmpl/default.php
- An XML file for adding a menu item typeː views//tmpl/default.xml
- Another HTML file for background controlː views//tmpl/index.html
- Another HTML file for background controlː views//index.html
- A PHP file for displaying the viewː views//view.html.php
JEXEC [ править ]
The following line is commonly found at the start of Joomla! PHP files:
This enables a secure entry point into the Joomla! platform. JEXEC contains a detailed explanation.
Tutorials on Designing a MVC Component [ править ]
To learn how to design your own MVC Component, please complete the tutorial for your Joomla! version.
Где находится use joomla component
The section will help you with steps to install the JA Purity IV quickstart or manual installation.
- Quickstart installation: Replicate Template demo to your server.
- Manual installation: install template, plugin manually on your Joomla site
System requirement
Please make sure your system meets the following requirements:
- Software: PHP: 7.4+ (8.1 recommended)
- MySQL(InnoDB support required): 5.61+
- MSSQL 10.50.1600.1 +
Web Servers
- Apache 2.4+
- Microsoft IIS 7
- Nginx 1.10 (1.18+ recommended)
Browser requirement
- Firefox 13+
- Google Chrome XY and the latest
- Opera 11.6+
- Safari 5.1+
Development Environment
During the development process, Localhost is preferred. You can use the following servers on your PC to develop your site.
- wamp server
- XAMPP for Windows
- LAMP Bundle
- XAMPP for Linux
- MAMP & MAMP Pro
- XAMPP for Mac OS
Download packages
JA Purity IV download section includes the following files:
- Quickstart package for Joomla 4
- JA Purity IV template
- T4 Framework plugin
- JA ACM Module
- JA Extension manager component
Quickstart installation
Quickstart installation allows you to replicate the demo site to your server with all extensions installed and demo content
Manual Installation
Installing the JA Purity IV, T4 framework, and other extensions on your existing Joomla website.
From your back-end setting panel, go to: «Extensions > Extension Manager», browse the extension installation files then hit the «Upload and Install»
- T4 Framework plugin
- JA Purity IV template
- JA ACM module
- JA Extension manager component


By default, the T4 plugin will be auto-enabled after installation. You can check this by going to «Extensions > Plugin Manager» then find T4 Plugin.
Set JA Purity IV as default template style
Joomla 3: Go to: «Extensions > Template Manager», set JA Purity IV template style as your default template style.
Joomla 4: Go to: «System > Site Template Styles», set JA Purity IV template style as your default template style.


Template folder structure
This section is to help you understand the folder structure of the JA Purity IV template, where to find the files you want.
JA Purity IV template
JA Purity IV template is built on the T4 Framework so its folder structure is almost the same as any other JA Templates that are developed with T4 Framework.
/templates/ja_purity_iv/ +-- scss/ /* all SCSS files */ +-- scss/tpl /* theme tpl SCSS files */ ¦ +-- _acm.scss ¦ +-- _all.scss ¦ +-- _offcanvas.scss ¦ +-- _styles.scss ¦ +-- _type.scss ¦ +-- _utilities.scss ¦ +-- _variables.scss ¦ +-- _vars.scss ¦ +-- jpages.scss ¦ +-- rtl.scss ¦ +-- template.scss ¦ +-- bootstrap.scss ¦ +-- _components.scss ¦ +-- _forms.scss ¦ +-- _global.scss ¦ +-- _joomla.scss ¦ +-- _megamenu.scss ¦ +-- _modules.scss ¦ +-- _navigations.scss +-- scss/tpls +-- css/ /*compiled files from SCSS*/ ¦ +-- template.css ¦ +-- rtl.css ¦ +-- acm.css ¦ +-- jpages.css ¦ +-- off-canvas.css/ ¦ +-- offline.css/ +-- html/ /*override modules and Joomla com_content*/ ¦ +-- com_content/ ¦ ¦ +-- article/ ¦ ¦ +-- category/ ¦ ¦ +-- featured/ ¦ +-- com_contact/ ¦ ¦ +-- contact/ ¦ +-- mod_articles_categories/ ¦ +-- mod_articles_category ¦ +-- layouts/ ¦ +-- . +-- fonts/ +-- js/ ¦ +--owl-carousel/ ¦ +--html5lightbox/ ¦ +-- bootstrap.bundle.js ¦ +-- template.js ¦ +-- imagesloaded.pkgd.js ¦ +-- isotope.pkgd.js +-- images/ +-- language/ +-- templateDetails.xml +-- templateInfo.php/ +-- templateHook.php/
CSS and SCSS customization
Any customization is not recommended in the t4 plugin.
To customize your site style, you can use either CSS or SCSS customization tool.

Template configuration
1. Layout configuration
JA Purity IV supports different layouts by default and you can create more layouts using layout builder.
Assign Layout for a template style
To assign a layout for a JA Purity IV template style, open the template style » Layout setting panel » and assign a layout for the template style.

Set sub-layout
The sub layout is used for child pages. For example, if the Category page is assigned to the main layout, the article detail page is the child page of the Category page, and it will be using the sub-layout, in case the setting is active.
To configure the sub-layout, in the layout setting panel, scroll down and you will find the Sub Layout setting, assign a layout and save the layout setting.

Supported layouts:
Note: You can create multiple template styles with different layouts assigned. Then assign each template style to specific pages.
2. Dark theme settings
JA Purity IV supports dark theme and theme switcher that allows to change theme color in front-end.
To enable, disable theme switcher and set the default theme, access the JA Purity IV template style, in the Site settings > Other settings, you will see 2 settings:
- Dark mode toggle: to enable the theme switcher in front-end
- Default color theme: to set the default theme color for the template style profile.

3. Site settings
Logo settings
The Logo settings are present under Site configuration > Logo Settings.
For the logo, you can select to use an image logo or text logo. You can also select the different logos for mobile view.
Typography settings
The typography includes the global settings for font family, font weight, and line height.
You can enable the custom font setting for heading and navigation (menu).

Local font supported: due to the GDPR issue, you can disable Google font, and use the local font that is already supported at core.
Other settings:
- Page: set page backgroud image and background style attributes
- Author Settings: show, hide the author block and link for the author
- Favicon setting: add custom favicon
4. Navigation configuration
JA Festival supports Megamenu for Desktop layout and dropdown or Off-canvas for Mobile layout.
Megamenu setting
Go to Navigation > Megamenu, select a menu and configure the megamenu. You can build a mega menu with multiple rows, each row can include multiple columns. You can assign menu items, modules or a module position to each column.

Off-canvas Menu setting
Enable Off-canvas (it is enabled by default), select module position, module style and other options.
Next, create a menu module, assign it to the position: off-canvas .

-
centercomics
- Module settings
5. Theme color settings
The theme color allows you to use the color picker to change color for brand colors, base colors, main menu colors, and footer colors.

You can view the changes in the website preview on the right panel.
6. Global settings

JA Purity IV template global settings include:
- T4 edit layout: this is the front-end editor (article, module) layout setting, you can select to use clean layout or full position layout
- CSS & JS optimization: JS and CSS optimization is the process of making your website smaller and faster to load by minifying the JS and CSS codes.
- Custom Code: You can insert any CSS, JS, meta tags, links, and verification codes using the custom code option. With multiple options to add custom to specific tags.
- Add-ons: includes settings to enable or disable font icons like Font Awesome, Iconmoon. When an Addon is disabled, its CSS and JS will not be loaded on your website, this is to help keep your site clean and load faster.
- Open Graph:
7. CSS & SCSS editor tool
Customizing style for your site is even simpler with the inbuilt custom CSS Editor. In the Tools panel, hit the Edit Custom CSS button and you can add your own custom CSS rules to the editor.

You can override the default variables in the Variables customization editor, as well as the adding custom SCSS.

Build Demo Pages
Home — Business
Step 1 — Create menu item
Go to Menu » Main menu, add a new menu item, select Articles » Featured Article menu type, or single article menu type.

Step 2 — Assign content to the Home page
The home page includes multiple sections, each section is a module.
1. [Business] Slideshow: JA ACM Module

Module position: slideshow Module Suffix: NOT USED Layout: Default
- Module settings
- Extra field settings
2. [Business] Features: JA ACM Module

Features Intro : style-2
Module position: section-1 Module Suffix: NOT USED Layout: Default
- Module settings
- Extra field settings
3. [Business] Feature 3: JA ACM Module

Features Intro : style-3
Module position: section-2 Module Suffix: NOT USED Layout: Default
- Module settings
- Extra field settings
4. A perfect starting point: JA ACM Module

Module position: section-3 Module Suffix: NOT USED Layout: Default
- Module settings
- Extra field settings
5. Customer Testimonials: JA ACM Module

Module position: section-4 Module Suffix: NOT USED Layout: Default
- Module settings
- Extra field settings
6. From our blog: Articles — Category Module

Module position: section-5 Module Suffix: NOT USED Layout: grid-layout-3cols
- Module settings
- Filtering settings
- Display settings
- Advanced settings
- Extra field settings
7. Our clients: JA ACM Module

Our Clients : style-1
Module position: section-6 Module Suffix: NOT USED Layout: Default
- Module settings
- Extra field settings
Category blog / article
Category blog page
The template supports 7 layouts for category blog to display your articles flexibily.

Create category blog page
#1. Create Articles » Category Blog menu.

#2. Assign category blog layout

You can additionally configure the layouts such as column, show/hide article content elements and more.
Article layouts
JA Purity IV supports 4 layouts to present your article content.

Configure the article layout for your site.
#1. Global setting: all articles in your site will be using the layout.
Go to System > Global configuration then select Articles.

In the Articles setting, select the layout and save.

#2. Category blog menu: all articles of the menu item will use the layout

#3. Article setting
In the article editing page, open the Options tab and assign layout for the article.

Upgrade Instruction
Take a full backup
Please always make a backup before proceeding to any of the upgrade processes. In case there is any problem, you can always restore the backup files.
The best method to upgrade JoomlArt products is using JA Extension Manager. The FREE extension brings a new way to manage extensions: upgrade, rollback, remote install, internal repository, compare versions, and more.
1. Set up JA Extension Manager Component
Download this free extension from this link. Install the extension to your website.
Go to Components > JA Extension Manager then selects Service Manager, now set JoomlArt as your default service. Next, hit the «Edit» button then add your account.

2. Upgrade JA Purity IV template
Check the new version of the JA Purity IV template. Use the filter to find the JA Seven template then hit the «Check Update» button.
3. Upgrade T4 Framework and other JA extensions
Using the filter to find the extensions you want to upgrade (JoomlArt products only), hit the «Check Update» button to check for a new version then hit Upgrade Now to upgrade the extension to the latest version.

Check out more details about JA Extension manager
Учебное пособие по компонентам Joomla 4: Mywalks, Часть 1 — Код сайта
Будучи опытным разработчиком на Joomla 3.x мне нужно было узнать о Joomla 4.x, и реально было действительно трудно начать работу. Несмотря на опыт, мои знания о внутреннем устройстве Joomla ограничены. Я начал работать с Joomla на стадии версии 1.6, и многие новые функции прошли мимо меня. Таким образом, это руководство может быть примером того, как слепой ведет слепого. Мне потребовалось около 10 дней, чтобы заставить хоть что-то работать, прочитав код, запустив отладчик и прочитав ограниченное количество доступной документации по Joomla 4. Это руководство написано для Joomla 4.x на этапе Alpha 10 и было обновлено для этапа Beta 4. Даже в этом случае оно может слишком скоро устареть.
Текст руководства был подготовлен как статья, написанная с помощью Joomla 4.0 Alpha 10, преобразованная в MediaWiki, а затем в форматы Github Markdown с помощью Pandoc. И вот что в итоге вышло.
Назначение компонента и его схема данных (Data Schema)
Последние несколько лет я гуляю с семьей, иногда один раз в неделю, иногда два раза, но только в хорошую погоду. Я вел список — всего около 50 прогулок, и каждая отличалась от других. Все это было частью попытки поддерживать форму в старости. Поэтому для самообучения я решил разработать компонент на CMS Joomla, который имеет два представления: список прогулок и детали отдельных прогулок. Чтобы не усложнять, я не хочу никаких излишеств: ни ввода данных на стороне сайта, ни оценок, ни счетчиков посещений, ни категорий, ни других плюшек Joomla. Для целей тестирования часть данных была введена непосредственно в базу данных с помощью phpMyAdmin. Компоненту необходимы две таблицы базы данных: список прогулок и список индивидуальных посещений. Я решил назвать компонент com_mywalks и таблицы #__mywalks и #__mywalks_dates .
Весь код для этого учебного компонента можно получить по этой ссылке.
Возможно, вам будет полезно установить компонент или распаковать его без установки и посмотреть рабочие файлы.
Таблица mywalks
На момент написания скрипт установки в папке admin/sql не вызывается. Итак, если вы устанавливаете рабочую версию кода этого руководства, сначала запустите следующие сценарии вручную. Это ошибка в Joomla или в учебном коде? Скрипт удаления работает — таблицы успешно пропадают.
Файлы sql в рабочем примере zip-файла включают образцы данных.
CREATE TABLE IF NOT EXISTS `#__mywalks` ( `id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, `title` varchar(64) NOT NULL, `description` text NOT NULL, `distance` decimal(10,0) NOT NULL, `toilets` tinyint(1) NOT NULL DEFAULT '0', `cafe` tinyint(1) NOT NULL DEFAULT '0', `hills` int(11) NOT NULL DEFAULT '0', `bogs` int(11) NOT NULL DEFAULT '0', `picture` varchar(128) DEFAULT NULL, `width` int(11) DEFAULT NULL, `height` int(11) DEFAULT NULL, `alt` varchar(64) DEFAULT NULL, `state` TINYINT NOT NULL DEFAULT '1' ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 DEFAULT COLLATE utf8mb4_unicode_ci;
Таблица mywalks_dates
CREATE TABLE IF NOT EXISTS `#__mywalk_dates` ( `id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, `walk_id` int(11) NOT NULL, `date` date NOT NULL, `weather` varchar(256) DEFAULT NULL, `state` TINYINT NOT NULL DEFAULT '1', KEY `idx_walk` (`walk_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 DEFAULT COLLATE utf8mb4_unicode_ci;
Если бы это был реальный компонент, было бы очевидно, что до окончания разработки схемы еще далеко! Посмотрите на сайт WalkHighlands, чтобы узнать, как далеко. Однако этого достаточно для учебных целей.
Структура файлов манифеста и компонентов
Zip-файл компонента, используемый для установки, должен содержать файл манифеста с именем mywalks.xml (без уведомления com_ ) вместе с папками администратора и сайта, примерно так:
com_mywalks.zip admin site mywalks.xml
При установке файл манифеста копируется в папку site_root/administrator/components/com_mywalks , где он нужен для удаления. Его не должно быть в исходном коде! Записи также делаются в site_root/administrator/cache/autoload_psr4.php [Это нововведения в Joomla 4].
Файл манифеста
Обратите внимание, что метод настроен на обновление ( upgrade ), поэтому компонент можно устанавливать повторно, например, при обновлении кода. Однако операторы sql не будут выполняться второй раз. Если инструкции install sql не выполняются по какой-либо причине, попробуйте выполнить их вручную, скопировав их из исходного кода в phpMyAdmin.
com_mywalks August 2019 Clifford E Ford [email protected] http://www.fford.me.uk/ Copyright (C) 2019 Clifford E Ford, All rights reserved. GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html 0.2.0 COM_MYWALKS_XML_DESCRIPTION J4xdemos\Component\Mywalks sql/install.mysql.sql sql/uninstall.mysql.sql src tmpl language/en-GB/com_mywalks.ini access.xml config.xml forms services sql src tmpl language/en-GB/com_mywalks.ini language/en-GB/com_mywalks.sys.ini
Пространство имен
Обратите внимание на тег namespace (пространства имен) в файле манифеста. Первым элементом должно быть название компании. У меня его нет, поэтому я использовал J4xdemos . Пространство имен используется в расширении, чтобы отличать его код от кода в других расширениях, которые могут иметь идентичные имена классов. Пространство имен используется для регистрации поставщика услуг — см. Ниже.
Второй элемент — это тип расширения:
- Компонент (Component),
- Модуль (Module),
- Плагин (Plugin),
- Шаблон (Template).
Третий элемент — это имя расширения без добавления com_ , mod_ и т. Д., В данном случае Mywalks .
Атрибут пространства имен path=»src» указывает, что все файлы, содержащие код пространства имен, будут найдены в каталоге src .
Файлы языковых констант
Если вы не знакомы с расширениями Joomla, языковая папка исходного сайта содержит один файл: en-GB.com_mywalks.ini , который содержит переведенные значения фиксированных строк, используемых для перевода с английского на другие языки. Структура папок проста:
site - папка, содержащая файлы сайта language - папка, содержащая файл языкового перевода сайта en-GB - папка с английскими переводами com_mywalks.ini - файл языковых констант
И com_mywalks.ini имеет такое содержание:
COM_MYWALKS_LIST_DESCRIPTION="Description" COM_MYWALKS_LIST_DISTANCE="Distance in Km" COM_MYWALKS_LIST_LAST_VISIT="Last Visit" COM_MYWALKS_LIST_NVISITS="nVisits" COM_MYWALKS_LIST_PAGE_HEADING="List of Walks" COM_MYWALKS_LIST_TABLE_CAPTION="List of Walks" COM_MYWALKS_LIST_TITLE="Title" COM_MYWALKS_ERROR_WALK_NOT_FOUND="Walk not found!" COM_MYWALKS_WALK_DATE="Visit date" COM_MYWALKS_WALK_REPORTS="Walk Reports" COM_MYWALKS_WALK_WEATHER="Weather Report"
Для каждой строки первая часть является ключом, а вторая часть — ее значением, английским переводом. Любой фиксированный текст, требующий перевода в интерфейсе сайта компонента должен быть в этом файле. Например, заголовки столбцов списка обходов должны быть ключами в исходном коде и переведены здесь. Также обратите внимание, что основным языком Joomla является британский английский. Для других языков требуются отдельные файлы перевода. По соглашению ключи следует отсортировать в алфавитном порядке!
Языковые файлы администратора: Смотри в следующей статье!
Файлы фронтенда сайта
Вы можете заметить, что некоторые имена папок и файлов Joomla 4.x начинаются с заглавных букв, а другие начинаются с строчных букв. J4 также имеет отличную от J3 структуру. Возможно, в продакшен версии Joomla 4 все имена будут приведены к единому виду.
Кроме того, имейте в виду, что код, необходимый для отображения представлений сайта, также включает некоторые функции из кода администратора, описанные ниже.
tmpl файлы (Файлы вида)
Файлы tmpl содержат код, отображающий виды страниц. Их должно быть проще всего объяснить и понять. Структура файла tmpl в исходном коде выглядит так:
site tmpl mywalk default.php mywalks default-items.php default.php default.xml
Вид отображения одной прогулки — tmpl/mywalk/default.php :
item->title; ?>
item->description; ?>!
reports as $id => $report) : ?> date; ?> weather; ?>
Для новичков в Joomla: каждый php-файл начинается с DocBlock, используемого в автоматизированной документации; в файлах с пространством имен следующий оператор — это пространство имен, которое не используется в файлах tmpl; первый исполняемый оператор должен быть всегда определён ( ‘_ JEXEC’ ) или дальше скрипт не работает; что гарантирует, что файл загружен Joomla, а не вызывается напрямую через веб-адрес.
Остальные строки выводят название прогулки, описание и список посещений, извлеченных из базы данных. Оператор use Joomla\CMS\Language\Text загружает класс, который преобразует строковые ключи в строковые значения. Оператор use Joomla\CMS\HTML\HTMLHelper; закомментирован, потому что в этом файле не используется ни одно из множества украшений HTML. Посмотрите ради интереса на файл, чтобы узнать, что он делает: site_root/libraries/src/HTML/HTMLHelper.php .
Вид списка прогулок — tmpl/mywalks/default.php
loadTemplate('items'); ?>
Обратите внимание, что операторы use загружают дополнительные файлы php, используя их пространства имен. Joomla\CMS\HTML\HTMLHelper добавляет файлы, используемые при отображении страницы, например файлы Javascript, необходимые для сортировки таблиц. Joomla\CMS\Language\Text добавляет файл, используемый для преобразования фиксированных строковых ключей в их английские значения. Joomla\CMS\Layout\LayoutHelper был скопирован сюда, когда во время разработки использовалось копирование и вставка из другого места. Он оставлен, но закомментирован, чтобы проиллюстрировать, что у меня может быть много случаев случайного кода, который ничего не делает, кроме использования ресурсов сервера.
Этот файл выводит заголовок страницы, а затем загружает другой файл, default-items.php , который отображает список прогулок. $this->loadTemplate(‘items’) использует код библиотеки, чтобы найти файл default_items.php в том же каталоге, в котором он был вызван.
Список items — tmpl/mywalks/default_items.php
Обратите внимание на создание ярлыка путем преобразования заголовка в буквенно-числовые символы в нижнем регистре только с заменой пробелов знаками минус.
items as $id => $item) : $slug = preg_replace('/[^a-z\d]/i', '-', $item->title); $slug = strtolower(str_replace(' ', '-', $slug)); ?> id, $slug)); ?>"> title; ?> description; ?> distance; ?> last_visit //$item->lastvisit; ?> nvisits; ?>
Также обратите внимание на статический вызов Route , который используется для создания URL-адреса для ссылки на отдельное описание прогулки. И обратите внимание на связанный с ним вызов use , который сообщает загрузчику, где найти требуемый класс и функцию. Подробнее о маршрутизации позже.
Это отрывок из функции getWalkRoute :
public static function getWalkRoute($id, $slug, $language = 0, $layout = null) < // Создание URL ссылки $link = 'index.php?option=com_mywalks&view=mywalk&id=' . $id . '&slug=' . $slug; if ($language && $language !== '*' && Multilanguage::isEnabled()) < $link .= '&lang=' . $language; >if ($layout) < $link .= '&layout=' . $layout; >return $link; >
Получение данных — файлы HtmlView
Предполагается, что файлы tmpl имеют дело исключительно с html. Любые данные, необходимые для создания html, такие как список прогулок, должны храниться в переменных в файлах HtmlView, где они становятся доступными в объекте $this .
Файл HtmlView.php для просмотра одиночной прогулки
get('State'); $item = $this->get('Item'); $reports = $this->get('Reports'); $this->state = &$state; $this->item = &$item; $this->reports = &$reports; // Проверка на ошибки. if (count($errors = $this->get('Errors'))) < throw new GenericDataException(implode("\n", $errors), 500); >return parent::display($tpl); > >
Функция display очень проста. Он извлекает из модели данные о состоянии, одиночной прогулке и отчетах об этой прогулке. Если какой-либо из шагов извлечения данных возвращает ошибку, он генерирует исключение, что обычно приводит к появлению какой-либо страницы с сообщением об ошибке. В противном случае управление передается через Joomla в файл tmpl для создания вывода html. Файлы HtmlView могут быть довольно сложными.
Файл HtmlView для списка прогулок
getParams(); // Get some data from the models $state = $this->get('State'); $items = $this->get('Items'); $pagination = $this->get('Pagination'); // Флаг указывает на то, что не следует добавлять limitstart=0 в URL $pagination->hideEmptyLimitstart = true; // Проверка на ошибки. if (count($errors = $this->get('Errors'))) < throw new GenericDataException(implode("\n", $errors), 500); >$this->state = &$state; $this->items = &$items; $this->params = &$params; $this->pagination = &$pagination; return parent::display($tpl); > >
Готовы к моделям?
Получение данных — файлы модели
Для модели одиночной прогулки нам нужен файл модели, который реализует populateState , getItem и getVisits . Для списка прогулок нам нужны populateState , getListQuery , getItems и некоторые другие для сортировки по столбцам и разбивки на страницы длинных списков, ни один из которых не реализован в этом руководстве.
Файл модели: MywalkModel
input->getInt('id'); $this->setState('mywalk.id', $pk); $offset = $app->input->getUInt('limitstart'); $this->setState('list.offset', $offset); // Загрузка параметров. $params = $app->getParams(); $this->setState('params', $params); > /** * Метод получения данных о прогулке. * * @param integer $pk Идентификатор прогулки. * * @return object|boolean Объект данных пункта меню в случае успеха, false */ public function getItem($pk = null) < $pk = (!empty($pk)) ? $pk : (int) $this->getState('mywalk.id'); try < $db = $this->getDbo(); $query = $db->getQuery(true) ->select( $this->getState( 'item.select', 'a.*' ) ); $query->from('#__mywalks AS a') ->where('a.id = ' . (int) $pk); $db->setQuery($query); $data = $db->loadObject(); if (empty($data)) < throw new \Exception(Text::_('COM_MYWALKS_ERROR_WALK_NOT_FOUND'), 404); >> catch (\Exception $e) < if ($e->getCode() == 404) < // Чтобы перенаправление отработало, необходимо пройти через обработчик ошибок. throw new \Exception($e->getMessage(), 404); > else < $this->setError($e); $this->_item[$pk] = false; > > return $data; > /** * Метод получения данных о посещениях с прогулкой. * * @param integer $pk The id of the walk. * * @return object|boolean Объект данных пункта меню в случае успеха, false */ public function getReports($pk = null) < $pk = (!empty($pk)) ? $pk : (int) $this->getState('mywalk.id'); try < $db = $this->getDbo(); $query = $db->getQuery(true) ->select('b.*'); $query->from('#__mywalk_dates AS b') ->where('b.walk_id = ' . (int) $pk); $query->order('`date` DESC'); $db->setQuery($query); $data = $db->loadObjectList(); // Совершенно нормально прогуляться без данных о посещениях - обработка вид. > catch (\Exception $e) < if ($e->getCode() == 404) < // Чтобы перенаправление работало, необходимо пройти через обработчик ошибок. throw new \Exception($e->getMessage(), 404); > else < $this->setError($e); $this->_item[$pk] = false; > > return $data; > >
Файл модели: MywalksModel
parent::__construct($config); > /** * Метод автоматического заполнения состояния модели. * * Этот метод следует вызывать только один раз для каждого экземпляра и * предназначен для вызова при первом вызове метода getState(), * если не установлен флаг конфигурации модели для игнорирования запроса. * * Примечание. Вызов getState в этом методе приведет к рекурсии. * * @param string $ordering Необязательное поле для сортировки. * @param string $direction Необязательное направление сортировки (asc | desc). * * @return void * * @since 3.0.1 */ protected function populateState($ordering = 'ordering', $direction = 'ASC') < $app = Factory::getApplication(); // Информация о состоянии списка $value = $app->input->get('limit', $app->get('list_limit', 0), 'uint'); $this->setState('list.limit', $value); $value = $app->input->get('limitstart', 0, 'uint'); $this->setState('list.start', $value); $orderCol = $app->input->get('filter_order', 'a.id'); if (!in_array($orderCol, $this->filter_fields)) < $orderCol = 'a.id'; >$this->setState('list.ordering', $orderCol); $listOrder = $app->input->get('filter_order_Dir', 'ASC'); if (!in_array(strtoupper($listOrder), array('ASC', 'DESC', ''))) < $listOrder = 'ASC'; >$this->setState('list.direction', $listOrder); $params = $app->getParams(); $this->setState('params', $params); //$this->setState('layout', $app->input->getString('layout')); > /** * Метод получения идентификатора на основе состояния конфигурации модели. * * Это необходимо, потому что модель используется компонентом * и разными модулями, которым могут потребоваться * разные наборы данных или разные требования к порядку. * * @param string $id Префикс для идентификатора id. * * @return string Идентификатор id. * * @since 1.6 */ protected function getStoreId($id = '') < // Получение id. return parent::getStoreId($id); >/** * Получить главный запрос для получения списка прогулок в зависимости от состояния модели. * * @return \JDatabaseQuery * * @since 1.6 */ protected function getListQuery() < // Получить текущего пользователя для проверки авторизации $user = Factory::getUser(); // Создать новый объект запроса. $db = $this->getDbo(); $query = $db->getQuery(true); // Выберать необходимые поля из таблицы. $query->select( $this->getState( 'list.select', 'a.*, (SELECT MAX(`date`) from #__mywalk_dates WHERE walk_id = a.id) AS last_visit, (SELECT count(`date`) from #__mywalk_dates WHERE walk_id = a.id) AS nvisits ') ); $query->from('#__mywalks AS a'); $params = $this->getState('params'); // Добавить данные о порядке списка. $query->order($this->getState('list.ordering', 'a.id') . ' ' . $this->getState('list.direction', 'ASC')); return $query; > /** * Метод получения списка прогулок. * * Переопределение для вставки преобразования поля attribs в объект \JParameter. * * @return mixed Массив объектов в случае успеха, false в случае неудачи. * * @since 1.6 */ public function getItems() < $items = parent::getItems(); return $items; >/** * Метод получения начального количества элементов для набора данных. * * @return integer Начальное количество элементов, доступных в наборе данных. * * @since 3.0.1 */ public function getStart() < return $this->getState('list.start'); > >
Control Flow
Запуск компонента — Контроллер
Стоит помнить, что URL-адрес страницы со списком прогулок, не относящийся к SEF, — это index.php?option=com_mywalks&task=display&view=mywalks . Часть task часто не учитывается, и в этом случае устанавливается task по умолчанию для вида. Если часть вида не указана, компонент должен установить вид по умолчанию.
Каждый запрос страницы начинается с последовательности инициализации. После этого точки входа в компонент находятся через их файлы контроллеров. Вид компонентов по умолчанию отображается, поэтому неудивительно, что контроллером по умолчанию является DisplayController . Этот контроллер не делает ничего, кроме вызова своего родительского контроллера. Однако для начальной обработки можно использовать контроллеры. Например, если форма отправляется, обычно проверяют токен формы и отменяют дальнейшие действия, если он недействителен.
DisplayController
. * * @return static Этот объект поддерживает chaining. * * @since 1.5 */ public function display($cachable = false, $urlparams = array()) < return parent::display(); >>
Основные файлы администратора
Хотя мы все еще разрабатываем код для отображения сайта, необходим некоторый код администратора. Файл services/provider.php используется для загрузки компонента, либо для отображения его собственных представлений сайта, либо для использования модулем меню для создания пунктов меню.
The services provider file: administrator/components/com_mywalks/services/provider.php
Обратите особое внимание на строки, начинающиеся с $container->registerServiceProvider , поскольку именно здесь ваш код регистрируется в контейнере для использования позже.
registerServiceProvider(new CategoryFactory('\\J4xdemos\\Component\\Mywalks')); $container->registerServiceProvider(new MVCFactory('\\J4xdemos\\Component\\Mywalks')); $container->registerServiceProvider(new ComponentDispatcherFactory('\\J4xdemos\\Component\\Mywalks')); $container->registerServiceProvider(new RouterFactory('\\J4xdemos\\Component\\Mywalks')); $container->set( ComponentInterface::class, function (Container $container) < $component = new MywalksComponent($container->get(ComponentDispatcherFactoryInterface::class)); $component->setRegistry($container->get(Registry::class)); $component->setMVCFactory($container->get(MVCFactoryInterface::class)); // $component->setCategoryFactory($container->get(CategoryFactoryInterface::class)); $component->setRouterFactory($container->get(RouterFactoryInterface::class)); return $component; > ); > >;
The component boot file: administrator/components/com_mywalks/src/Extension/MywalksComponent.php
getRegistry()->register('mywalksadministrator', new AdministratorService); > >
На данный момент обращение вызова к регистрации Administrator Service закомментирован. Это приводит к ошибке времени выполнения при вызове компонента Mywalks из интерфейса администратора. См. часть 2.
The Component Router
На этом этапе работает компонент com_mywalks . Для перехода к списку прогулок нужен один пункт меню. Есть загвоздка: в списке прогулок ссылки на отдельные прогулки примерно такие:
/site-root/my-walks.html?view=mywalk&id=1
(где корень сайта мой или не может быть деревом вложенных папок). Пришло время сделать собственный роутер SEF? И сделайте перерыв, чтобы прочитать Поддержка URL-адресов SEF в вашем компоненте. У меня есть другой пакет Joomla, который использует URL-адреса SEF в форме [domain]/XXX/YY/page-title.html , где XXX — это код филиала организации, а YY — код языка. Некоторые ветки используют несколько языков. Нестандартно! Да, но именно об этом и просил заказчик.
Для компонента mywalks я хочу использовать отдельные URL-адреса прогулки, например:
/site-root/mywalks/walk-n/walk-title.html
Где n — индивидуальный идентификатор прогулки, а название прогулки автоматически генерируется из фактического названия. На самом деле ни walk-title , ни .html не нужны. Первое — за дружелюбие, второе — за то, что я старомоден.
Нет пунктов меню для индивидуальных прогулок. Они никому не нужны, и их невозможно создать. Требуется настраиваемый маршрутизатор, состоящий из двух файлов: Router.php и MywalksNomenuRules.php .
The Router File: component/com_mywalks/src/Service/Router.php
categoryFactory = $categoryFactory; $this->db = $db; $params = ComponentHelper::getParams('com_mywalks'); $this->noIDs = (bool) $params->get('sef_ids'); $mywalks = new RouterViewConfiguration('mywalks'); $mywalks->setKey('id'); $this->registerView($mywalks); $mywalk = new RouterViewConfiguration('mywalk'); $mywalk->setKey('id'); $this->registerView($mywalk); parent::__construct($app, $menu); $this->attachRule(new MenuRules($this)); $this->attachRule(new StandardRules($this)); $this->attachRule(new NomenuRules($this)); > >
Обратите внимание на строки, которые определяют и используют настраиваемые правила:
use Joomla\Component\Mywalks\Site\Service\MywalksNomenuRules as NomenuRules; . $this->attachRule(new NomenuRules($this));
Правила включают функцию build для создания ссылок на отдельные прогулки и функцию синтаксического анализа для преобразования входящего URL-адреса SEF во внутренний маршрут Joomla. Не нужно беспокоиться о ссылке в пункте меню, так как это регулируется правилами MenuRules.
The Router Rules file: components/my_walks/src/Service/MywalksNomenuRules.php
router = $router; > /** * Dummymethod для выполнения требований интерфейса * * @param array &$query Массив запросов для обработки * * @return void * * @since 3.4 * @codeCoverageIgnore */ public function preprocess(&$query) < $test = 'Test'; >/** * Parse a menu-less URL * * @param array &$segments Сегменты URL для анализа * @param array &$vars Части, полученные в результате сегментации * * @return void * * @since 3.4 */ public function parse(&$segments, &$vars) < //with this url: http://localhost/j4x/my-walks/mywalk-n/walk-title.html // segments: [[0] =>mywalk-n, [1] => walk-title] // vars: [[option] => com_mywalks, [view] => mywalks, [id] => 0] $vars['view'] = 'mywalk'; $vars['id'] = substr($segments[0], strpos($segments[0], '-') + 1); array_shift($segments); array_shift($segments); return; > /** * Создание URL-адреса без меню * * @param array &$query Части, которые нужно преобразовать * @param array &$segments Сегменты URL для сборки * * @return void * * @since 3.4 */ public function build(&$query, &$segments) < // content of $query ($segments is empty or [[0] =>mywalk-3]) // when called by the menu: [[option] => com_mywalks, [Itemid] => 126] // when called by the component: [[option] => com_mywalks, [view] => mywalk, [id] => 1, [Itemid] => 126] // when called from a module: [[option] => com_mywalks, [view] => mywalks, [format] => html, [Itemid] => 126] // when called from breadcrumbs: [[option] => com_mywalks, [view] => mywalks, [Itemid] => 126] // the url should look like this: /site-root/mywalks/walk-n/walk-title.html // if the view is not mywalk - the single walk view if (!isset($query['view']) || (isset($query['view']) && $query['view'] !== 'mywalk') || isset($query['format'])) < return; >$segments[] = $query['view'] . '-' . $query['id']; // последняя часть URL-адреса может отсутствовать if (isset($query['slug'])) < $segments[] = $query['slug']; unset($query['slug']); >unset($query['view']); unset($query['id']); > >
Когда есть пункт меню для страницы списка mywalks, функция сборки MywalksNomenuRules будет вызываться для каждой внутренней ссылки на странице: в модулях, меню и даже статьях с контентом. Так что следите за сообщениями об ошибках во время выполнения.
И наконец
То есть он — рабочий компонент, но работает пока только на стороне фронтенда сайта!

Заберите ссылку на статью к себе, чтобы потом легко её найти!
Раз уж досюда дочитали, то может может есть желание рассказать об этом месте своим друзьям, знакомым и просто мимо проходящим?
Не надо себя сдерживать! 😉