Market PRO is a module for CMF Cotonti that implements e-commerce and multi-vendor marketplace functionality. Fully compatible with PHP 8.5+, MySQL 8.4+, uses strict typing and namespaces.
- 1. General description
- 2. Key features
- 3. Requirements
- 4. Installation
- 5. File structure
- 6. Architecture
- 7. Database
- 8. API functions
- 9. Hooks list
- 10. Integration with ItemService
- 11. Extra fields (extrafields)
- 12. Templates
- 13. Caching
- 14. Multilingual support
- 15. Extending functionality
- 16. Plugin compatibility
- 17. Links
- 18. License
Market PRO is a Cotonti module that implements e-commerce (single seller) and multi-vendor marketplace (multiple sellers) functionality. The module is written in modern PHP using:
- Strict typing (
declare(strict_types=1)). - Namespaces (
cot\modules\market\inc\...). - Services (Singleton, Repository, DTO).
- Hooks (full compatibility with the Cotonti plugin system).
- Class autoloading via namespace paths.
The module integrates with the general Cotonti mechanisms: extra fields system, authentication, cache, language files, and the ItemService service for participating in universal selections (search, cart, favorites).
- Product catalog with unlimited category hierarchy.
- Product card with full description, gallery, comments.
- Search by title, description, SKU.
- Filtering and sorting by any fields.
- AJAX list loading ("Load more").
- Personal seller showcase in the user profile.
- Product publishing: draft, moderation, publish.
- Product cloning.
- Manage all products with status filters.
- Bulk operations: approve, delete.
- Publication moderation.
- Per-category permission configuration.
- Extra fields management.
- Sorting and pagination configuration per category.
- SEO: meta title, meta description, H1, aliases, canonical URLs.
- Caching: static, disk, first-level repository cache.
- Multilingual: language files +
i18n4marketprosupport. - Security: CSRF protection, prepared SQL queries, permission separation.
- Extensibility via hooks and extra fields.
| Component | Minimum version |
|---|---|
| PHP | 8.5 |
| MySQL | 8.4 |
| Cotonti | Siena and above |
| Required Cotonti modules | extrafields, forms, users |
| Optional plugins | comments, attacher, tgm4market, i18n4marketpro, aliasmarketpro |
Additional dependencies (composer packages) are not required.
- Copy the
marketdirectory tomodules/of your Cotonti site. - Go to Administration → Extensions and install the Market module.
- During installation:
- the
cot_markettable is created automatically (if it doesn't exist); - the
markettable is registered inCot::$db; - the extrafields table is connected for
market.
- the
- Configure the module in Administration → Configuration → Market.
- Create the category structure in Administration → Structure → Market.
- Optionally install additional plugins (comments, attacher, etc.).
modules/market/
├── market.php # main module file (entry point)
├── market.admin.php # admin hook handler (admin panel)
├── market.item.getItems.php # item.getItems hook handler
├── market.itemService.getItems.php # itemService.getItems hook handler
├── market.header.php # header.main hook handler (notices)
├── market.header.first.php # header.first hook handler (location)
├── market.header.tags.php # header.tags hook handler (title)
├── market.footer.first.php # footer.first hook handler (location)
├── market.userdetails.php # users.details.tags hook handler
├── inc/
│ ├── market.functions.php # main module API
│ ├── market.add.php # add item
│ ├── market.edit.php # edit item
│ ├── market.list.php # item list
│ ├── market.main.php # item page
│ ├── market.preview.php # preview page
│ ├── market.counter.php # AJAX view counter
│ ├── MarketControlService.php # item management service
│ ├── MarketDictionary.php # constants dictionary
│ ├── MarketRepository.php # item repository
│ └── market.setup.php # module settings
├── lang/
│ ├── market.ru.lang.php # Russian
│ ├── market.en.lang.php # English
│ └── market.uk.lang.php # Ukrainian
└── tpl/
├── market.add.tpl # add form template
├── market.edit.tpl # edit form template
├── market.list.tpl # item list template
├── market.main.tpl # item page template
├── market.enum.tpl # list widget template
├── market.tree.tpl # category tree template
├── market.userdetails.tpl # seller showcase template
└── market.pagination.tpl # pagination template
The module uses a modern approach to code organization. All classes are located in the cot\modules\market\inc namespace.
Module constants dictionary.
namespace cot\modules\market\inc;
class MarketDictionary
{
public const SOURCE_MARKET = 'market';
public const STATE_PUBLISHED = 0; // Published
public const STATE_PENDING = 1; // Pending moderation
public const STATE_DRAFT = 2; // Draft
}Repository for working with the cot_market table. Inherits BaseRepository. Contains a first-level cache (within a single HTTP request).
namespace cot\modules\market\inc;
class MarketRepository extends BaseRepository
{
private static $cacheById = [];
public static function getTableName(): string;
public function getById(int $id, bool $useCache = true): ?array;
protected function afterFetch(array $item): array;
}The getById($id) method returns an item data array or null.
Item management service. Implements Singleton via the GetInstanceTrait. Responsible for operations that require transactions (e.g., deletion).
namespace cot\modules\market\inc;
class MarketControlService
{
use GetInstanceTrait;
public function delete(int $id, array $itemData = []): bool|string;
}The delete() method returns a success message or false on error. Internally:
- opens a transaction;
- deletes related extrafields files;
- calls the
market.delete.firstandmarket.delete.donehooks; - deletes the record from the DB;
- updates structure counters;
- notifies
ItemService::onDelete(); - clears the static cache of item and category pages.
Core Cotonti DTO used for integration with ItemService. Contains fields: source, sourceId, type, title, description, url, ownerId, categoryCode, categoryTitle, categoryUrl, data.
These files are connected automatically via the [BEGIN_COT_EXT] block:
| File | Hook | Purpose |
|---|---|---|
market.admin.php |
admin |
Admin panel for item management |
market.item.getItems.php |
item.getItems |
Providing item data through the common Cotonti API |
market.itemService.getItems.php |
itemService.getItems |
Providing item data through ItemService |
market.header.php |
header.main |
Notices about items in the site header |
market.header.first.php |
header.first |
Setting Cot::$env['location'] for header templates |
market.header.tags.php |
header.tags |
Overriding HEADER_TITLE for categories |
market.footer.first.php |
footer.first |
Setting Cot::$env['location'] for footer templates |
market.userdetails.php |
users.details.tags |
"Items" tab in the user profile |
All inc files are called via market.php:
Parameter m |
File |
|---|---|
list |
inc/market.list.php |
main |
inc/market.main.php |
add |
inc/market.add.php |
edit |
inc/market.edit.php |
preview |
inc/market.preview.php |
counter |
inc/market.counter.php (AJAX) |
| Field | Type | Description |
|---|---|---|
fieldmrkt_id |
INT AUTO_INCREMENT | Primary key |
fieldmrkt_cat |
VARCHAR(255) | Category code |
fieldmrkt_alias |
VARCHAR(255) | Alias (SEO URL) |
fieldmrkt_title |
VARCHAR(255) | Item title |
fieldmrkt_desc |
VARCHAR(255) | Short description |
fieldmrkt_text |
TEXT | Full text |
fieldmrkt_parser |
VARCHAR(64) | Text parser |
fieldmrkt_pcod |
VARCHAR(64) | SKU / product code |
fieldmrkt_costdflt |
DECIMAL | Default price |
fieldmrkt_cost_usd |
DECIMAL | Price in USD |
fieldmrkt_date |
INT | Publication date (timestamp) |
fieldmrkt_begin |
INT | Activity start date |
fieldmrkt_expire |
INT | Activity end date |
fieldmrkt_updated |
INT | Update date |
fieldmrkt_ownerid |
INT | Owner ID |
fieldmrkt_count |
INT | View counter |
fieldmrkt_state |
TINYINT | Status (0/1/2) |
fieldmrkt_metah1 |
VARCHAR(255) | SEO H1 |
fieldmrkt_metatitle |
VARCHAR(255) | Meta title |
fieldmrkt_metadesc |
VARCHAR(255) | Meta description |
Any additional fields can be added to the table via the extrafields system.
All functions are located in inc/market.functions.php.
Imports item data from the request (GET/POST) into an array.
$source— request type ('POST','GET','PATCH','D'for direct).$ritem— initial data array (for editing).$auth— permissions array.
Returns an array with fieldmrkt_* fields.
Validates item data. Checks:
- category presence;
- title length;
- alias correctness;
- non-empty description (considering category settings).
Returns true/false.
Adds an item to the DB. Returns the new item ID or null.
Automatically:
- checks alias uniqueness;
- downgrades status to
STATE_PENDINGif the author is not an admin; - updates structure counters;
- calls the
market.add.add.query,market.add.add.donehooks; - clears the cache.
Updates an item. Returns true/false.
Similar to cot_market_add(), but for an existing record.
Returns the string status: 'published', 'draft', 'pending'.
Builds the item URL. Considers alias or ID, category, and additional parameters.
Returns the permissions array for a category: auth_read, auth_write, isadmin, auth_download.
Returns an array of tags for the template. All tags receive the specified prefix (e.g., LIST_ROW_ or MARKET_).
Main tags:
TITLE,DESCRIPTION,TEXT,TEXT_SHORT,TEXT_CUT,TEXT_IS_CUTURL,ID,ALIAS,PCODSTATE,STATUS,LOCAL_STATUSCAT,CAT_URL,CAT_TITLE,CAT_ICON,CAT_ICON_SRCCOSTDFLT,COST_USD,COST_USD_FORMATTEDCREATED,UPDATED,HITSMETA_H1,META_TITLEADMIN,ADMIN_EDIT,ADMIN_DELETE,ADMIN_UNVALIDATEBREADCRUMBS,BREADCRUMBS_ITEM
Main widget generator for the item list. All parameters are described in section 8.5.
Returns the number of items in a category.
Recalculates and updates the structure counter for a category. Clears the structure cache.
Updates the category code for all items. Used when renaming categories.
Returns the number of active items (state=0) in a category and all its subcategories.
Returns the number of active items in a specific category.
Builds a hierarchical category tree. Returns HTML.
Full signature:
function cot_market_enum(
$categories = '', // string or array of category codes, '' = all
$count = 0, // count, 0 = all
$template = '', // template part name or path
$order = '', // SQL sorting
$condition = '', // additional SQL condition
$active_only = true, // only published and active
$use_subcat = true, // include subcategories
$exclude_current = false,// exclude current item
$blacklist = '', // category blacklist
$pagination = '', // pagination GET parameter name
$cache_ttl = null // cache TTL in seconds
)Example usage in a template:
{PHP|cot_market_enum('', 5, '', 'fieldmrkt_date DESC')}
{PHP|cot_market_enum('electronics', 10, 'sidebar')}
{PHP|cot_market_enum('', 5, '', '', '', true, true, false, '', 'p', 3600)}
Simpler widget for displaying an item list on the home page. Returns HTML.
Truncates text by the <!--more-->, [more], or <hr class="more"> tag.
Reads file contents with directory traversal protection.
Returns an array of available fields for item sorting.
Callback for configuring home page sorting. Returns a list of options.
Checks the existence of the header.market.<cat>.tpl template.
Checks the existence of the header.market.<cat>.pagehasid.tpl template.
Checks the existence of the footer.market.<cat>.tpl template.
Checks the existence of the footer.market.<cat>.pagehasid.tpl template.
Renders a <select> with Select2 support and indentation for nested categories.
Specialized category select for the search form.
The module provides the following hooks for plugins:
market.first— at the beginning of the item page.market.main— after loading item data.market.tags— before the final parsing of the item template.market.add.first— start of the add page.market.add.add.first— before importing POST data.market.add.add.import— after import, before validation.market.add.add.error— after validation.market.add.main— before creating the XTemplate object.market.add.tags— before final parsing.market.edit.first— start of the edit page.market.edit.update.first— before POST processing.market.edit.update.import— after import.market.edit.update.error— after validation.market.edit.main— after template preparation.market.edit.tags— before final parsing.market.list.first— at the beginning of the list.market.list.query— before building the SQL.market.list.main— after data preparation.market.list.rowcat.first— before rendering subcategories.market.list.rowcat.loop— inside the subcategory loop.market.list.before_loop— before the item loop.market.list.loop— inside the item loop.market.list.tags— before final parsing.
market.admin.first— at the beginning of the admin panel.market.admin.validate— before approval.market.admin.validate.done— after approval.market.admin.unvalidate— before unpublication.market.admin.delete— before deletion.market.admin.delete.done— after deletion.market.admin.checked_validate— during bulk approval.market.admin.checked_delete— during bulk deletion.market.admin.loop— inside the admin list loop.market.admin.tags— before final parsing of the admin template.
market.delete.first— before item deletion (in the service).market.delete.done— after deletion.market.enum.query— in the cot_market_enum widget, before building the query.market.enum.loop— inside the widget loop.market.enum.tags— before final parsing of the widget.market.tree.first— at the beginning of tree building.market.tree.main— before rendering the tree.market.tree.loop— inside the tree loop.markettags.first— before item tag generation.markettags.main— at the end of tag generation.market.item.getItems— in the item.getItems handler.market.itemService.getItems— in the itemService.getItems handler.market.userdetails.query— in the seller showcase, before the query.market.userdetails.loop— inside the showcase loop.market.userdetails.tags— before final parsing of the showcase.
The module automatically registers itself in the Cotonti ItemService. This allows items to participate in universal mechanisms:
- search;
- favorites;
- cart (if the corresponding plugin is installed);
- notifications;
- and other services working with abstract items.
Two files provide this integration:
market.item.getItems.php— handler for theitem.getItemshook.market.itemService.getItems.php— handler for theitemService.getItemshook.
Both files:
- Check that the request source is
market. - Normalize the list of item IDs.
- Load data via
MarketRepository. - Build
ItemDtoobjects. - Add them to the common result array.
- Call the corresponding hooks for extensions.
The module fully supports the Cotonti extrafields system. Registration is automatic:
Cot::$db->registerTable('market');
cot_extrafields_register_table('market');All extra fields are automatically displayed in the add and edit forms. The EXTRAFLD block is provided in the template for this:
<!-- BEGIN: EXTRAFLD -->
<div class="form-group">
<label>{MARKETADD_FORM_EXTRAFLD_TITLE}</label>
<div>{MARKETADD_FORM_EXTRAFLD}</div>
<small>{MARKETADD_FORM_EXTRAFLD_CODENAME}</small>
</div>
<!-- END: EXTRAFLD -->The MARKETADD_HAS_EXTRAFIELDS flag allows conditionally displaying a message about the presence or absence of fields.
All standard Cotonti types are supported:
input— text field;textarea— multiline text;select— dropdown (with value localization via language keys);checkbox— checkbox;radio— radio buttons;file— file;datetime— date/time.
All module templates are located in modules/market/tpl/. They can be overridden in the theme:
themes/<your_theme>/modules/market/<tpl_name>.tpl
Standard templates:
| Template | Purpose |
|---|---|
market.list.tpl |
Item list in the catalog |
market.main.tpl |
Item page |
market.add.tpl |
Add form |
market.edit.tpl |
Edit form |
market.enum.tpl |
Item list widget |
market.tree.tpl |
Category tree |
market.userdetails.tpl |
Seller showcase in the profile |
market.pagination.tpl |
Pagination |
Each category can have its own template via the tpl field in the structure. The module will then look for:
market.list.<tpl>.tplmarket.main.<tpl>.tplmarket.add.<tpl>.tplmarket.edit.<tpl>.tpl
For each category, you can create custom templates:
header.market.<cat>.tpl— common header for category pages;header.market.<cat>.pagehasid.tpl— header for the item page in the category;footer.market.<cat>.tpl— common footer;footer.market.<cat>.pagehasid.tpl— footer for the item page.
The module automatically determines the needed location through the market.header.first.php and market.footer.first.php handlers.
The module supports three cache levels:
MarketRepository::getById() saves the result in the static array $cacheById. Repeated requests for the same item within one HTTP request do not hit the DB.
Via the $cache_ttl parameter in cot_market_enum(), the widget rendering result is saved to the Cotonti disk cache. The cache key depends on the template, language, and SQL query.
The module supports the Cotonti static cache:
- Automatically clears item and category pages on edit.
- Clears the home page when a new item is published.
- Uses the AJAX view counter so that cached pages still track statistics.
if (Cot::$cache) {
if (Cot::$cfg['cache_market']) {
Cot::$cache->static->clearByUri(cot_market_url($itemData));
Cot::$cache->static->clearByUri(cot_url('market', ['c' => $itemData['fieldmrkt_cat']]));
}
if (Cot::$cfg['cache_index']) {
Cot::$cache->static->clear('index');
}
}The module supports the standard Cotonti language file mechanism. For each language, a file market.<lang>.lang.php is created. Currently available:
market.ru.lang.php— Russian;market.en.lang.php— English;market.uk.lang.php— Ukrainian.
Via the cot_langfile_custom() function, you can connect your own files:
if (function_exists('cot_langfile_custom')) {
cot_langfile_custom('market', 'module');
}This allows you to store custom strings in a separate file market.custom.<lang>.lang.php and keep them safe during module updates.
The i18n4marketpro plugin is used to translate category and item titles and descriptions. The module automatically picks up translations via the function:
cot_i18n4marketpro_get_cat($code, $locale)If a translation is not found, the default value is displayed.
Creating a plugin that extends Market PRO:
- Register your plugin in
plugins/<your_plugin>/. - Specify the needed hooks in the
[BEGIN_COT_EXT]block:
[BEGIN_COT_EXT]
Hooks=market.list.loop,market.add.main
[END_COT_EXT]
- In the handlers, access the environment variables and modify them.
The module calls hooks at almost every stage of operation. For example, to add an extra block to the item card:
/* === Hook === */
foreach (cot_getextplugins('market.main') as $pl) {
include $pl;
}
/* ===== */Your plugin can add its own variables to $t before parsing.
Adding a new field to an item:
- Go to Administration → Other → Extrafields.
- Select the
cot_markettable. - Create a field (e.g.,
fieldmrkt_brand). - The field automatically appears in the add and edit forms.
- In templates it will be available as
{MARKET_BRAND}(with the corresponding block prefix).
Create a file in your theme with a name matching the module template. For example:
themes/mytheme/modules/market/market.list.tpl
Cotonti will automatically pick it up instead of the standard one.
extrafields— working with extra fields.forms— forms and validation.users— users and profiles.
- comments — item comments.
- attacher — image and file uploads.
- tgm4market — Telegram bot integration.
- i18n4marketpro — multilingual translations.
- aliasmarketpro — advanced SEO URL handling.
- xtradbrowmarket-cotonti — extended extrafields output.
The module is compatible with the Cotonti payment system. The store currency is automatically substituted from the payment settings or configured manually.
- Source code and updates: https://github.com/webitproff/marketpro-cotonti
- Documentation and description: https://abuyfile.com/ru/market/cotonti/plugs/marketpro
- Support forum: https://abuyfile.com/ru/forums/cotonti/custom/marketpro
- Cotonti Extrafields API: https://github.com/Cotonti/Cotonti/blob/master/system/extrafields.php
- Cotonti official site: https://www.cotonti.com/
BSD License
Copyright (c) webitproff, 2026
Free use, modification, and distribution of the module is permitted provided that the copyright notice and license are preserved. The module is provided "as is", without any warranties.
Full license text — in the LICENSE file.
Document version: 1.0 Last updated: September 2026
РУССКИЙ
Market PRO — модуль для CMF Cotonti, реализующий функциональность интернет-магазина и мультивендорной торговой площадки. Полностью совместим с PHP 8.5+, MySQL 8.4+, использует строгую типизацию и namespace-пространства.
- 1. Общее описание
- 2. Ключевые возможности
- 3. Требования
- 4. Установка
- 5. Структура файлов
- 6. Архитектура
- 7. База данных
- 8. Функции API
- 9. Список хуков
- 10. Интеграция с ItemService
- 11. Дополнительные поля (extrafields)
- 12. Шаблоны
- 13. Кэширование
- 14. Мультиязычность
- 15. Расширение функционала
- 16. Совместимость с плагинами
- 17. Ссылки
- 18. Лицензия
Market PRO — модуль для Cotonti, реализующий функциональность интернет-магазина (один продавец) и мультивендорной торговой площадки (множество продавцов). Модуль написан на современном PHP с использованием:
- Строгой типизации (
declare(strict_types=1)). - Пространств имён (
cot\modules\market\inc\...). - Сервисов (Singleton, Repository, DTO).
- Хуков (полная совместимость с системой плагинов Cotonti).
- Автозагрузки классов через namespace-пути.
Модуль интегрируется с общими механизмами Cotonti: системой дополнительных полей, авторизацией, кэшем, языковыми файлами, а также с сервисом ItemService для участия в универсальных выборках (поиск, корзина, избранное).
- Каталог товаров с иерархией категорий неограниченной вложенности.
- Карточка товара с полным описанием, галереей, комментариями.
- Поиск по названию, описанию, артикулу.
- Фильтрация и сортировка по любым полям.
- AJAX-подгрузка списков («Загрузить ещё»).
- Личная витрина продавца в профиле.
- Публикация товаров: черновик, модерация, публикация.
- Клонирование товаров.
- Управление всеми товарами с фильтрами по статусу.
- Массовые операции: утверждение, удаление.
- Модерация публикаций.
- Настройка прав по категориям.
- Управление дополнительными полями.
- Настройка сортировки и пагинации для каждой категории.
- SEO: meta title, meta description, H1, алиасы, канонические URL.
- Кэширование: статическое, дисковое, кэш первого уровня в репозитории.
- Мультиязычность: языковые файлы + поддержка
i18n4marketpro. - Безопасность: CSRF-защита, подготовленные SQL-запросы, разграничение прав.
- Расширяемость через хуки и дополнительные поля.
| Компонент | Минимальная версия |
|---|---|
| PHP | 8.5 |
| MySQL | 8.4 |
| Cotonti | Siena и выше |
| Обязательные модули Cotonti | extrafields, forms, users |
| Опциональные плагины | comments, attacher, tgm4market, i18n4marketpro, aliasmarketpro |
Дополнительные зависимости (composer-пакеты) не требуются.
- Скопировать каталог
marketвmodules/вашего сайта на Cotonti. - Зайти в Администрирование → Расширения и установить модуль Market.
- При установке:
- автоматически создаётся таблица
cot_market(если её нет); - регистрируется таблица
marketвCot::$db; - подключается таблица extrafields для
market.
- автоматически создаётся таблица
- Настроить модуль в Администрирование → Конфигурация → Market.
- Создать структуру категорий в Администрирование → Структура → Market.
- При необходимости установить дополнительные плагины (комментарии, attacher и др.).
modules/market/
├── market.php # главный файл модуля (точка входа)
├── market.admin.php # обработчик хука admin (админ-панель)
├── market.item.getItems.php # обработчик хука item.getItems
├── market.itemService.getItems.php # обработчик хука itemService.getItems
├── market.header.php # обработчик хука header.main (уведомления)
├── market.header.first.php # обработчик хука header.first (location)
├── market.header.tags.php # обработчик хука header.tags (title)
├── market.footer.first.php # обработчик хука footer.first (location)
├── market.userdetails.php # обработчик хука users.details.tags
├── inc/
│ ├── market.functions.php # основной API модуля
│ ├── market.add.php # добавление товара
│ ├── market.edit.php # редактирование товара
│ ├── market.list.php # список товаров
│ ├── market.main.php # страница товара
│ ├── market.preview.php # страница предпросмотра
│ ├── market.counter.php # AJAX-счётчик просмотров
│ ├── MarketControlService.php # сервис управления товарами
│ ├── MarketDictionary.php # словарь констант
│ ├── MarketRepository.php # репозиторий товаров
│ └── market.setup.php # настройки модуля
├── lang/
│ ├── market.ru.lang.php # русский
│ ├── market.en.lang.php # английский
│ └── market.uk.lang.php # украинский
└── tpl/
├── market.add.tpl # шаблон формы добавления
├── market.edit.tpl # шаблон формы редактирования
├── market.list.tpl # шаблон списка товаров
├── market.main.tpl # шаблон страницы товара
├── market.enum.tpl # шаблон виджета списка
├── market.tree.tpl # шаблон дерева категорий
├── market.userdetails.tpl # шаблон витрины продавца
└── market.pagination.tpl # шаблон пагинации
Модуль использует современный подход к организации кода. Все классы находятся в namespace cot\modules\market\inc.
Словарь констант модуля.
namespace cot\modules\market\inc;
class MarketDictionary
{
public const SOURCE_MARKET = 'market';
public const STATE_PUBLISHED = 0; // Опубликован
public const STATE_PENDING = 1; // На модерации
public const STATE_DRAFT = 2; // Черновик
}Репозиторий для работы с таблицей cot_market. Наследует BaseRepository. Содержит кэш первого уровня (в пределах одного HTTP-запроса).
namespace cot\modules\market\inc;
class MarketRepository extends BaseRepository
{
private static $cacheById = [];
public static function getTableName(): string;
public function getById(int $id, bool $useCache = true): ?array;
protected function afterFetch(array $item): array;
}Метод getById($id) возвращает массив данных товара или null.
Сервис управления товарами. Реализует Singleton через трейт GetInstanceTrait. Отвечает за операции, требующие транзакций (например, удаление).
namespace cot\modules\market\inc;
class MarketControlService
{
use GetInstanceTrait;
public function delete(int $id, array $itemData = []): bool|string;
}Метод delete() возвращает сообщение об успехе или false при ошибке. Внутри:
- открывает транзакцию;
- удаляет связанные файлы extrafields;
- вызывает хуки
market.delete.firstиmarket.delete.done; - удаляет запись из БД;
- обновляет счётчики структуры;
- уведомляет
ItemService::onDelete(); - очищает статический кэш страниц товара и категории.
DTO из ядра Cotonti, используется для интеграции с ItemService. Содержит поля: source, sourceId, type, title, description, url, ownerId, categoryCode, categoryTitle, categoryUrl, data.
Эти файлы подключаются автоматически через блок [BEGIN_COT_EXT]:
| Файл | Хук | Назначение |
|---|---|---|
market.admin.php |
admin |
Админ-панель управления товарами |
market.item.getItems.php |
item.getItems |
Отдача данных товаров через общий API Cotonti |
market.itemService.getItems.php |
itemService.getItems |
Отдача данных товаров через ItemService |
market.header.php |
header.main |
Уведомления о товарах в шапке сайта |
market.header.first.php |
header.first |
Установка Cot::$env['location'] для header-шаблонов |
market.header.tags.php |
header.tags |
Переопределение HEADER_TITLE для категорий |
market.footer.first.php |
footer.first |
Установка Cot::$env['location'] для footer-шаблонов |
market.userdetails.php |
users.details.tags |
Вкладка «Товары» в профиле пользователя |
Все inc-файлы вызываются через market.php:
Параметр m |
Файл |
|---|---|
list |
inc/market.list.php |
main |
inc/market.main.php |
add |
inc/market.add.php |
edit |
inc/market.edit.php |
preview |
inc/market.preview.php |
counter |
inc/market.counter.php (AJAX) |
| Поле | Тип | Описание |
|---|---|---|
fieldmrkt_id |
INT AUTO_INCREMENT | Первичный ключ |
fieldmrkt_cat |
VARCHAR(255) | Код категории |
fieldmrkt_alias |
VARCHAR(255) | Алиас (ЧПУ) |
fieldmrkt_title |
VARCHAR(255) | Название товара |
fieldmrkt_desc |
VARCHAR(255) | Краткое описание |
fieldmrkt_text |
TEXT | Полный текст |
fieldmrkt_parser |
VARCHAR(64) | Парсер текста |
fieldmrkt_pcod |
VARCHAR(64) | Артикул |
fieldmrkt_costdflt |
DECIMAL | Цена по умолчанию |
fieldmrkt_cost_usd |
DECIMAL | Цена в USD |
fieldmrkt_date |
INT | Дата публикации (timestamp) |
fieldmrkt_begin |
INT | Дата начала активности |
fieldmrkt_expire |
INT | Дата окончания активности |
fieldmrkt_updated |
INT | Дата обновления |
fieldmrkt_ownerid |
INT | ID владельца |
fieldmrkt_count |
INT | Счётчик просмотров |
fieldmrkt_state |
TINYINT | Статус (0/1/2) |
fieldmrkt_metah1 |
VARCHAR(255) | SEO H1 |
fieldmrkt_metatitle |
VARCHAR(255) | Meta title |
fieldmrkt_metadesc |
VARCHAR(255) | Meta description |
Также к таблице можно добавить любые поля через систему extrafields.
Все функции находятся в inc/market.functions.php.
Импортирует данные товара из запроса (GET/POST) в массив.
$source— тип запроса ('POST','GET','PATCH','D'для direct).$ritem— массив исходных данных (для редактирования).$auth— массив прав.
Возвращает массив с полями fieldmrkt_*.
Валидирует данные товара. Проверяет:
- наличие категории;
- длину названия;
- корректность алиаса;
- непустое описание (с учётом настройки категории).
Возвращает true/false.
Добавляет товар в БД. Возвращает ID нового товара или null.
Автоматически:
- проверяет уникальность алиаса;
- понижает статус до
STATE_PENDING, если автор не админ; - обновляет счётчики структуры;
- вызывает хуки
market.add.add.query,market.add.add.done; - очищает кэш.
Обновляет товар. Возвращает true/false.
Аналогично cot_market_add(), только для существующей записи.
Возвращает строковый статус: 'published', 'draft', 'pending'.
Формирует URL товара. Учитывает алиас или ID, категорию и дополнительные параметры.
Возвращает массив прав для категории: auth_read, auth_write, isadmin, auth_download.
Возвращает массив тегов для шаблона. Все теги получают указанный префикс (например, LIST_ROW_ или MARKET_).
Основные теги:
TITLE,DESCRIPTION,TEXT,TEXT_SHORT,TEXT_CUT,TEXT_IS_CUTURL,ID,ALIAS,PCODSTATE,STATUS,LOCAL_STATUSCAT,CAT_URL,CAT_TITLE,CAT_ICON,CAT_ICON_SRCCOSTDFLT,COST_USD,COST_USD_FORMATTEDCREATED,UPDATED,HITSMETA_H1,META_TITLEADMIN,ADMIN_EDIT,ADMIN_DELETE,ADMIN_UNVALIDATEBREADCRUMBS,BREADCRUMBS_ITEM
Основной генератор виджета списка товаров. Все параметры описаны в разделе 8.5.
Возвращает количество товаров в категории.
Пересчитывает и обновляет счётчик структуры для категории. Очищает кэш структуры.
Обновляет код категории у всех товаров. Используется при переименовании категорий.
Возвращает количество активных товаров (state=0) в категории и всех её подкатегориях.
Возвращает количество активных товаров в конкретной категории.
Строит иерархическое дерево категорий. Возвращает HTML.
Полная сигнатура:
function cot_market_enum(
$categories = '', // строка или массив кодов категорий, '' = все
$count = 0, // количество, 0 = все
$template = '', // имя части или путь к шаблону
$order = '', // SQL-сортировка
$condition = '', // дополнительное SQL-условие
$active_only = true, // только опубликованные и активные
$use_subcat = true, // включать подкатегории
$exclude_current = false,// исключить текущий товар
$blacklist = '', // чёрный список категорий
$pagination = '', // имя GET-параметра пагинации
$cache_ttl = null // TTL кэша в секундах
)Пример использования в шаблоне:
{PHP|cot_market_enum('', 5, '', 'fieldmrkt_date DESC')}
{PHP|cot_market_enum('electronics', 10, 'sidebar')}
{PHP|cot_market_enum('', 5, '', '', '', true, true, false, '', 'p', 3600)}
Более простой виджет для вывода списка товаров на главной. Возвращает HTML.
Обрезает текст по тегу <!--more-->, [more] или <hr class="more">.
Читает содержимое файла с защитой от обхода директорий.
Возвращает массив доступных полей для сортировки товаров.
Callback для настройки сортировки на главной. Возвращает список вариантов.
Проверяет существование шаблона header.market.<cat>.tpl.
Проверяет существование шаблона header.market.<cat>.pagehasid.tpl.
Проверяет существование шаблона footer.market.<cat>.tpl.
Проверяет существование шаблона footer.market.<cat>.pagehasid.tpl.
Рендерит <select> с поддержкой Select2 и отступами для вложенных категорий.
Специализированный селект категорий для формы поиска.
Модуль предоставляет следующие хуки для плагинов:
market.first— в начале страницы товара.market.main— после загрузки данных товара.market.tags— перед финальным парсингом шаблона товара.market.add.first— начало страницы добавления.market.add.add.first— перед импортом данных POST.market.add.add.import— после импорта, до валидации.market.add.add.error— после валидации.market.add.main— перед созданием объекта XTemplate.market.add.tags— перед финальным парсингом.market.edit.first— начало страницы редактирования.market.edit.update.first— перед обработкой POST.market.edit.update.import— после импорта.market.edit.update.error— после валидации.market.edit.main— после подготовки шаблона.market.edit.tags— перед финальным парсингом.market.list.first— в начале списка.market.list.query— перед формированием SQL.market.list.main— после подготовки данных.market.list.rowcat.first— перед выводом подкатегорий.market.list.rowcat.loop— внутри цикла подкатегорий.market.list.before_loop— перед циклом товаров.market.list.loop— внутри цикла товаров.market.list.tags— перед финальным парсингом.
market.admin.first— в начале админ-панели.market.admin.validate— перед утверждением.market.admin.validate.done— после утверждения.market.admin.unvalidate— перед снятием с публикации.market.admin.delete— перед удалением.market.admin.delete.done— после удаления.market.admin.checked_validate— при массовом утверждении.market.admin.checked_delete— при массовом удалении.market.admin.loop— внутри цикла списка в админке.market.admin.tags— перед финальным парсингом админ-шаблона.
market.delete.first— перед удалением товара (в сервисе).market.delete.done— после удаления.market.enum.query— в виджете cot_market_enum, перед формированием запроса.market.enum.loop— внутри цикла виджета.market.enum.tags— перед финальным парсингом виджета.market.tree.first— в начале построения дерева.market.tree.main— перед выводом дерева.market.tree.loop— внутри цикла дерева.markettags.first— перед генерацией тегов товара.markettags.main— в конце генерации тегов.market.item.getItems— в файле-обработчике item.getItems.market.itemService.getItems— в файле-обработчике itemService.getItems.market.userdetails.query— в витрине продавца, перед запросом.market.userdetails.loop— внутри цикла витрины.market.userdetails.tags— перед финальным парсингом витрины.
Модуль автоматически регистрируется в системе ItemService Cotonti. Это позволяет товарам участвовать в универсальных механизмах:
- поиск;
- избранное;
- корзина (при наличии соответствующего плагина);
- уведомления;
- и другие сервисы, работающие с абстрактными элементами.
Два файла обеспечивают эту интеграцию:
market.item.getItems.php— обработчик хукаitem.getItems.market.itemService.getItems.php— обработчик хукаitemService.getItems.
Оба файла:
- Проверяют, что источник запроса —
market. - Нормализуют список ID товаров.
- Загружают данные через
MarketRepository. - Формируют объекты
ItemDto. - Добавляют их в общий результирующий массив.
- Вызывают соответствующие хуки для расширений.
Модуль полностью поддерживает систему extrafields Cotonti. Регистрация происходит автоматически:
Cot::$db->registerTable('market');
cot_extrafields_register_table('market');В формах добавления и редактирования автоматически выводятся все дополнительные поля. Для этого в шаблоне предусмотрен блок EXTRAFLD:
<!-- BEGIN: EXTRAFLD -->
<div class="form-group">
<label>{MARKETADD_FORM_EXTRAFLD_TITLE}</label>
<div>{MARKETADD_FORM_EXTRAFLD}</div>
<small>{MARKETADD_FORM_EXTRAFLD_CODENAME}</small>
</div>
<!-- END: EXTRAFLD -->Флаг MARKETADD_HAS_EXTRAFIELDS позволяет условно показать сообщение о наличии или отсутствии полей.
Поддерживаются все стандартные типы Cotonti:
input— текстовое поле;textarea— многострочный текст;select— выпадающий список (с локализацией значений через языковые ключи);checkbox— флажок;radio— переключатели;file— файл;datetime— дата/время.
Все шаблоны модуля находятся в modules/market/tpl/. Их можно переопределить в теме:
themes/<your_theme>/modules/market/<tpl_name>.tpl
Стандартные шаблоны:
| Шаблон | Назначение |
|---|---|
market.list.tpl |
Список товаров в каталоге |
market.main.tpl |
Страница товара |
market.add.tpl |
Форма добавления |
market.edit.tpl |
Форма редактирования |
market.enum.tpl |
Виджет списка товаров |
market.tree.tpl |
Дерево категорий |
market.userdetails.tpl |
Витрина продавца в профиле |
market.pagination.tpl |
Пагинация |
Для каждой категории можно задать собственный шаблон через поле tpl в структуре. Тогда модуль будет искать:
market.list.<tpl>.tplmarket.main.<tpl>.tplmarket.add.<tpl>.tplmarket.edit.<tpl>.tpl
Для каждой категории можно создать собственные шаблоны:
header.market.<cat>.tpl— общий header для страниц категории;header.market.<cat>.pagehasid.tpl— header для страницы товара в категории;footer.market.<cat>.tpl— общий footer;footer.market.<cat>.pagehasid.tpl— footer страницы товара.
Модуль автоматически определяет нужный location через обработчики market.header.first.php и market.footer.first.php.
Модуль поддерживает три уровня кэша:
MarketRepository::getById() сохраняет результат в статическом массиве $cacheById. Повторные запросы одного и того же товара в рамках одного HTTP-запроса не идут в БД.
Через параметр $cache_ttl в cot_market_enum() результат рендеринга виджета сохраняется в дисковый кэш Cotonti. Ключ кэша зависит от шаблона, языка и SQL-запроса.
Модуль поддерживает статический кэш Cotonti:
- Автоматически очищает страницы товара и категории при редактировании.
- Очищает главную страницу при публикации нового товара.
- Использует AJAX-счётчик просмотров, чтобы кэшированные страницы всё равно учитывали статистику.
if (Cot::$cache) {
if (Cot::$cfg['cache_market']) {
Cot::$cache->static->clearByUri(cot_market_url($itemData));
Cot::$cache->static->clearByUri(cot_url('market', ['c' => $itemData['fieldmrkt_cat']]));
}
if (Cot::$cfg['cache_index']) {
Cot::$cache->static->clear('index');
}
}Модуль поддерживает стандартный механизм языковых файлов Cotonti. Для каждого языка создаётся файл market.<lang>.lang.php. На данный момент доступны:
market.ru.lang.php— русский;market.en.lang.php— английский;market.uk.lang.php— украинский.
Через функцию cot_langfile_custom() можно подключать свои файлы:
if (function_exists('cot_langfile_custom')) {
cot_langfile_custom('market', 'module');
}Это позволяет хранить пользовательские строки в отдельном файле market.custom.<lang>.lang.php и не терять их при обновлении модуля.
Для перевода названий и описаний категорий и товаров используется плагин i18n4marketpro. Модуль автоматически подхватывает переводы через функцию:
cot_i18n4marketpro_get_cat($code, $locale)Если перевод не найден, отображается значение по умолчанию.
Создание плагина, расширяющего Market PRO:
- Регистрируете свой плагин в
plugins/<your_plugin>/. - Указываете в блоке
[BEGIN_COT_EXT]нужные хуки:
[BEGIN_COT_EXT]
Hooks=market.list.loop,market.add.main
[END_COT_EXT]
- В обработчиках получаете доступ к переменным окружения и модифицируете их.
Практически на каждом этапе работы модуль вызывает хуки. Например, чтобы добавить дополнительный блок в карточку товара:
/* === Hook === */
foreach (cot_getextplugins('market.main') as $pl) {
include $pl;
}
/* ===== */Ваш плагин может добавить свои переменные в $t перед парсингом.
Добавление нового поля к товару:
- Зайти в Администрирование → Прочее → Экстраполя.
- Выбрать таблицу
cot_market. - Создать поле (например,
fieldmrkt_brand). - Поле автоматически появится в формах добавления и редактирования.
- В шаблонах оно будет доступно как
{MARKET_BRAND}(с префиксом соответствующего блока).
Создайте в своей теме файл с именем, соответствующим шаблону модуля. Например:
themes/mytheme/modules/market/market.list.tpl
Cotonti автоматически подхватит его вместо стандартного.
extrafields— работа с дополнительными полями.forms— формы и валидация.users— пользователи и профили.
- comments — комментарии к товарам.
- attacher — загрузка изображений и файлов.
- tgm4market — интеграция с Telegram-ботами.
- i18n4marketpro — мультиязычные переводы.
- aliasmarketpro — расширенная работа с ЧПУ.
- xtradbrowmarket-cotonti — расширенный вывод extrafields.
Модуль совместим с системой платежей Cotonti. Валюта магазина автоматически подставляется из настроек платежей или настраивается вручную (зависит от плагина).
- Исходный код и обновления: https://github.com/webitproff/marketpro-cotonti
- Документация и описание: https://abuyfile.com/ru/market/cotonti/plugs/marketpro
- Форум поддержки: https://abuyfile.com/ru/forums/cotonti/custom/marketpro
- API Extrafields в Cotonti: https://github.com/Cotonti/Cotonti/blob/master/system/extrafields.php
- Официальный сайт Cotonti: https://www.cotonti.com/
BSD License
Copyright (c) webitproff, 2026
Разрешается свободное использование, модификация и распространение модуля при условии сохранения уведомления об авторских правах и лицензии. Модуль предоставляется «как есть», без каких-либо гарантий.
Полный текст лицензии — в файле LICENSE.
Версия документа: 1.0 Последнее обновление: Сентябрь 2026