Development of Custom Module for Craft CMS
Modules in Craft CMS are Yii2 modules embedded in the application without publishing to Plugin Store. They are used for custom business logic of a particular project: unique elements, services, Twig extensions, console commands.
Difference between Module and Plugin
Module — code in modules/ of the current project. Not distributed, has no version for Plugin Store, does not require license. Suitable for logic specific to one site.
Plugin — Composer package with composer.json, CHANGELOG.md, icon. Can be published and sold. Suitable for reusable functionality.
Module Structure
modules/
└── sitecustom/
├── SiteCustomModule.php # main class
├── services/
│ ├── ProductService.php
│ └── SearchService.php
├── controllers/
│ └── ApiController.php
├── variables/
│ └── SiteVariable.php # Twig variables
├── twigextensions/
│ └── SiteTwigExtension.php
└── console/
└── controllers/
└── SyncController.php
Main Module Class
// modules/sitecustom/SiteCustomModule.php
namespace modules\sitecustom;
use Craft;
use craft\events\RegisterComponentTypesEvent;
use craft\services\Elements;
use craft\web\twig\variables\CraftVariable;
use modules\sitecustom\services\ProductService;
use modules\sitecustom\variables\SiteVariable;
use modules\sitecustom\twigextensions\SiteTwigExtension;
use yii\base\Event;
use yii\base\Module;
class SiteCustomModule extends Module
{
public static SiteCustomModule $instance;
public function init(): void
{
parent::init();
self::$instance = $this;
// Set alias for paths
Craft::setAlias('@modules/sitecustom', __DIR__);
// Register services
$this->setComponents([
'products' => ProductService::class,
'search' => SearchService::class,
]);
// Register Twig variables
Event::on(
CraftVariable::class,
CraftVariable::EVENT_INIT,
function (Event $event) {
$event->sender->set('site', SiteVariable::class);
}
);
// Register Twig extensions
if (Craft::$app->request->getIsSiteRequest()) {
Craft::$app->view->registerTwigExtension(new SiteTwigExtension());
}
}
}
Register in config/app.php:
return [
'modules' => [
'site-custom' => \modules\sitecustom\SiteCustomModule::class,
],
'bootstrap' => ['site-custom'],
];
Service with Business Logic
// modules/sitecustom/services/ProductService.php
namespace modules\sitecustom\services;
use craft\base\Component;
use craft\elements\Entry;
use craft\helpers\ElementHelper;
class ProductService extends Component
{
public function getFeaturedProducts(int $limit = 6): array
{
return Entry::find()
->section('products')
->featured(true)
->inStock(true)
->orderBy('sortOrder asc, postDate desc')
->limit($limit)
->with(['featuredImage', 'categories'])
->all();
}
public function getRelated(Entry $product, int $limit = 4): array
{
return Entry::find()
->section('products')
->relatedTo([
'element' => $product->categories->all(),
'field' => 'categories',
])
->id('not ' . $product->id)
->limit($limit)
->all();
}
public function updateStock(int $entryId, int $quantity): bool
{
$entry = Entry::find()->id($entryId)->one();
if (!$entry) return false;
$entry->setFieldValue('stockQuantity', $quantity);
return \Craft::$app->elements->saveElement($entry);
}
}
Twig Variables
// modules/sitecustom/variables/SiteVariable.php
namespace modules\sitecustom\variables;
use modules\sitecustom\SiteCustomModule;
class SiteVariable
{
public function featuredProducts(int $limit = 6): array
{
return SiteCustomModule::$instance->products->getFeaturedProducts($limit);
}
public function cartCount(): int
{
return \Craft::$app->session->get('cart_count', 0);
}
}
In Twig:
{% set products = craft.site.featuredProducts(4) %}
{% for product in products %}
{% include '_components/product-card' with { product: product } %}
{% endfor %}
Twig Extensions (Filters and Functions)
namespace modules\sitecustom\twigextensions;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
use Twig\TwigFunction;
class SiteTwigExtension extends AbstractExtension
{
public function getFilters(): array
{
return [
new TwigFilter('formatPrice', [$this, 'formatPrice']),
new TwigFilter('phoneFormat', [$this, 'formatPhone']),
];
}
public function getFunctions(): array
{
return [
new TwigFunction('svg', [$this, 'inlineSvg'], ['is_safe' => ['html']]),
];
}
public function formatPrice(float $price, string $currency = 'RUB'): string
{
return number_format($price, 0, '.', ' ') . ' ' . $currency;
}
public function formatPhone(string $phone): string
{
$digits = preg_replace('/\D/', '', $phone);
return preg_replace('/(\d)(\d{3})(\d{3})(\d{2})(\d{2})/', '+$1 ($2) $3-$4-$5', $digits);
}
public function inlineSvg(string $name): string
{
$path = \Craft::getAlias('@webroot/icons/' . $name . '.svg');
return file_exists($path) ? file_get_contents($path) : '';
}
}
Console Commands
// modules/sitecustom/console/controllers/SyncController.php
namespace modules\sitecustom\console\controllers;
use craft\console\Controller;
use yii\console\ExitCode;
class SyncController extends Controller
{
public function actionProducts(): int
{
$this->stdout("Syncing products...\n");
// Sync logic with external API
$count = SiteCustomModule::$instance->products->syncFromExternalApi();
$this->stdout("Synced: {$count} products\n", Console::FG_GREEN);
return ExitCode::OK;
}
}
php craft site-custom/sync/products
Development of a basic module with 1–2 services and Twig variables takes 1–2 days. Full module with complex business logic and console commands takes 3–7 days.







