Skip to content
Darin Larimore
All posts

Extending Craft with a custom module

5 min read
On this page
  1. Registering one
  2. The skeleton
  3. Keeping two relation fields in sync
  4. A JSON endpoint
  5. The rule

Every Craft site I have built in the last few years has a modules/ directory, and the Commerce store I have maintained since 2022 has six of them. None of them are plugins. A plugin has a settings page, a version, a migration track and a Plugin Store listing, and it is worth all of that when you will install it on a second site. A module is a Yii module that Craft bootstraps from config/app.php. It has none of that ceremony and it is the right home for the code that makes one site that site.

Registering one

Two files tell Craft the module exists. composer.json maps the namespace, and config/app.php lists the class and asks for it to be bootstrapped, which means instantiated on every request rather than the first time something references it:

'modules' => [
    'outreachfields' => [
        'class' => Module::class,
        'components' => [
            'outreachFieldsService' => [
                'class' => 'modules\outreachfields\services\OutreachFieldsService',
            ],
        ],
    ],
    'statistics' => \modules\statistics\Statistics::class,
    'shop' => \modules\shop\Shop::class,
],
'bootstrap' => ['outreachfields', 'statistics', 'shop'],

Services can be declared right there as components, or inside the module with setComponents(). Either way they are reached as Module::$instance->outreachFieldsService.

The skeleton

The constructor and init() are nearly identical across every module I have. The constructor sets an alias so templates and asset bundles can find the module's files, registers a CP template root so statistics/index resolves to modules/statistics/templates/index.twig, and stores the instance:

public function __construct($id, $parent = null, array $config = [])
{
    Craft::setAlias('@modules/outreachfields', $this->getBasePath());
    $this->controllerNamespace = 'modules\outreachfields\controllers';

    Event::on(View::class, View::EVENT_REGISTER_CP_TEMPLATE_ROOTS, function (RegisterTemplateRootsEvent $e) {
        if (is_dir($baseDir = $this->getBasePath().DIRECTORY_SEPARATOR.'templates')) {
            $e->roots[$this->id] = $baseDir;
        }
    });

    static::setInstance($this);
    parent::__construct($id, $parent, $config);
}

public function init()
{
    parent::init();
    self::$instance = $this;

    if (Craft::$app->request->isConsoleRequest) {
        $this->controllerNamespace = 'modules\\outreachfields\\console\\controllers';
    }

    Craft::$app->onInit(function () {
        $this->attachEventHandlers();
    });
}

The console check gives the module a second controller namespace, so php craft outreachfields/cleanup/orphaned-addresses and /actions/outreachfields/... can both exist without one leaking into the other. The onInit() wrapper defers the event listeners until Craft has finished building itself, which matters as soon as a listener touches a plugin's class.

From there a module adds whatever it needs: a craft.statistics variable through CraftVariable::EVENT_INIT, a nav item through Cp::EVENT_REGISTER_CP_NAV_ITEMS, a Twig global through an extension that implements GlobalsInterface, an asset bundle registered on View::EVENT_BEFORE_RENDER_TEMPLATE for CP-only CSS. All of it is in Craft's own events. The module is just the place to put the listeners.

Keeping two relation fields in sync

The store assigns funding vouchers to users. A voucher has an assignToUser field, and the user has an attachedVouchers field, because managers wanted to edit the relationship from either side. Two relation fields that mean the same thing will drift unless something keeps them together, so the module listens for saves on both element types and writes the other side.

The part that bit me is that saving the other side fires the same event again. The guard is a per-element key that marks the element as in flight:

Event::on(Element::class, Element::EVENT_AFTER_PROPAGATE, function (ModelEvent $event) {
    $element = $event->sender;

    if ($element->getIsRevision() || ! $element instanceof Code) {
        return;
    }

    $key = $element->id.'__'.$element->siteId;

    if (isset($this->preparsedElements['onPropagate'][$key])) {
        return;
    }

    $this->preparsedElements['onPropagate'][$key] = true;

    collect($element->assignToUser->all())->each(function ($user) use ($element) {
        $ids = collect($user->attachedVouchers->ids())->merge($element->id)->unique()->toArray();

        if ($ids === $user->attachedVouchers->ids()) {
            return;
        }

        $user->setFieldValue('attachedVouchers', $ids);
        Craft::$app->elements->saveElement($user, true, false);
    });

    unset($this->preparsedElements['onPropagate'][$key]);
});

The getIsRevision() check is not optional. Craft saves a revision for most entry saves, and the revision fires the same events.

The same module later had to do something less tidy. Commerce attaches its own Address::EVENT_AFTER_SAVE handler that updates every cart using that address, and for a user with a long history of abandoned carts, editing a saved address was hanging the server. Last December I registered a handler ahead of it (the final false argument puts it at the front of the list) that sets $event->handled = true for user-owned addresses, so Commerce's handler never runs for them. Active carts no longer pick up the edited address automatically; the customer re-selects it at checkout. That trade is written in a comment above the listener, because it is the kind of thing the next person will try to "fix".

A JSON endpoint

The most recent module is also the smallest. The product grid is served from a static cache, and last week the client reported cards saying "Out of stock" for things the product page said were in stock. The card's stock state had been baked into the cached fragment, and Commerce's inventory changes were not firing the event the cache plugin listens for. The fix was to stop caching the answer: a shop module with one controller that the grid calls once per page for all visible variants.

class StockController extends Controller
{
    protected array|int|bool $allowAnonymous = true;

    public function actionIndex(): Response
    {
        $this->requireAcceptsJson();

        $ids = array_filter(array_map('intval', explode(',', $this->request->getParam('variantIds', ''))));
        $stock = [];

        foreach (Variant::find()->id($ids)->all() as $variant) {
            $stock['v'.$variant->id] = $variant->hasStock();
        }

        return $this->asJson($stock);
    }
}

My first version of that endpoint was a Twig template that output JSON, excluded from the cache by path. A controller under /actions/ is never cached, sets the content type, and can insist on an Ajax request. Two short files, and it matches how the other five already work.

The rule

If it is about this site, it is a module. If you would install it twice, it is a plugin. Keep the skeleton the same in every module so the interesting part is only ever the listeners.