Skip to main content
FreeAn audit of your Drupal siteA written audit of your Drupal site, within three business days
All articles

Backend & EngineeringNov 12, 20269 min read

Tilizy Commerce: modern ecommerce in Drupal

Valentin ZsigmondFounder & Lead Engineer

Tilizy Commerce is a GPL ecommerce platform built as Drupal 11 modules. One Drupal install runs many isolated stores. Merchants work in a React back office, and shoppers get a server-rendered storefront, a theme on the DRAST engine we described in Theming Drupal without Twig. Payments, taxes, shipping, promotions, subscriptions and invoices are each a module you can swap, extend or leave out.

This article is about three engineering decisions rather than features: how stores stay isolated, where extensions plug in, and how EU VAT is decided. The examples use release v1.0.47 of the 1.0.x line, which needs Drupal 11.3 and PHP 8.3 or newer.

The store is the tenant boundary

A tc_store entity holds everything that differs between tenants: currencies, locales, domains, timezone, tax settings and branding. Every entity that belongs to a store implements StoreScopedInterface and carries a store_id base field. StoreContext keeps two current stores. The storefront store comes from tagged tilizy_commerce.store_resolver services, in priority order: a store that a headless API client names (the X-Commerce-Store header or ?store=), then the request's hostname, then the default store. The back-office store is the merchant's own selection, honored only for stores they manage; otherwise it is the first store they manage.

Isolation is enforced on the server in three layers: entity access, access-checked entity queries and the API controllers. The first layer is one access handler shared by every store-scoped entity type. Here is its checkAccess():

protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account): AccessResultInterface {
  assert($entity instanceof StoreScopedInterface);
  if ($this->storeAccess->hasCapability($account, (int) $entity->getStoreId(), $this->storeAccess->entityCapability($entity->getEntityTypeId(), (string) $operation))) {
    return AccessResult::allowed()->cachePerUser()->addCacheableDependency($entity)->setCacheMaxAge(0);
  }
  if ($operation === 'view' && $entity->isPubliclyVisible()) {
    return AccessResult::allowed()->addCacheableDependency($entity);
  }
  return AccessResult::neutral()->cachePerUser()->addCacheableDependency($entity)->setCacheMaxAge(0);
}

Access is a question about the entity's own store, never about a store the request happens to be in. Staff grants vary per user and carry a max-age of zero, so they are never cached. Shoppers see an entity only when the entity itself says it is public. Platform operators with administer tilizy commerce manage every store. With the optional tilizy_commerce_team module, staff get per-store capabilities such as catalog.view from the tilizy_capabilities modules, which we covered in Scoped permissions with Drupal's access policy API.

A custom entity that is tenant-safe from the start

The same isolation is available to your own modules. Implement the interface, use the trait, add the store field and point the access handler at the shared class. This lookbook entity follows the pattern of the platform's own tc_brand:

<?php

declare(strict_types=1);

namespace Drupal\acme_lookbook\Entity;

use Drupal\Core\Entity\Attribute\ContentEntityType;
use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Entity\EntityChangedInterface;
use Drupal\Core\Entity\EntityChangedTrait;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\tilizy_commerce\Access\StoreScopedAccessControlHandler;
use Drupal\tilizy_commerce\Entity\StoreScopedInterface;
use Drupal\tilizy_commerce\Entity\StoreScopedTrait;

#[ContentEntityType(
  id: 'acme_lookbook',
  label: new TranslatableMarkup('Lookbook'),
  entity_keys: ['id' => 'id', 'uuid' => 'uuid', 'label' => 'title'],
  handlers: ['access' => StoreScopedAccessControlHandler::class],
  base_table: 'acme_lookbook',
  admin_permission: 'administer tilizy commerce',
  additional: ['tc_capabilities' => ['view' => 'catalog.view', 'manage' => 'catalog.manage']],
)]
final class Lookbook extends ContentEntityBase implements StoreScopedInterface, EntityChangedInterface {

  use StoreScopedTrait;
  use EntityChangedTrait;

  public static function baseFieldDefinitions(EntityTypeInterface $entity_type): array {
    $fields = parent::baseFieldDefinitions($entity_type) + static::storeBaseFieldDefinitions();
    $fields['title'] = BaseFieldDefinition::create('string')->setRequired(TRUE)->setSetting('max_length', 255);
    $fields['status'] = BaseFieldDefinition::create('boolean')->setDefaultValue(TRUE);
    $fields['changed'] = BaseFieldDefinition::create('changed');
    return $fields;
  }

  public function isPubliclyVisible(): bool {
    return (bool) $this->get('status')->value;
  }

}

Three details matter. tc_capabilities says which store capability governs reading and writing; without it, an entity type from a module outside the platform falls under the generic extensions.operate capability. The trait's isPubliclyVisible() returns FALSE, so an entity stays private until you decide otherwise. And the changed field is not decoration: the admin API uses it for optimistic concurrency.

The second layer needs no code from you. A hook_query_alter() implementation hands every query to StoreQueryFilter, which acts on entity queries tagged <entity type>_access, the tag that accessCheck(TRUE) adds. If the entity class implements StoreScopedInterface and the user is not a platform operator, the query gets a store_id IN (…) condition limited to the stores where the user holds the view capability. A user with no such store gets IN (0) and an empty result, not an error. When store_id lives in a separate field table, the filter adds a subquery instead.

Endpoints that see one store only

The third layer is the back-office API. Controllers extend AdminApiControllerBase, whose helpers carry the store into every read. store() resolves the merchant's store and answers 403 when they manage none. scopedQuery() returns an access-checked query with an explicit store_id condition. loadScoped() answers 404 for an id that belongs to another store:

<?php

declare(strict_types=1);

namespace Drupal\acme_lookbook\Controller\Admin;

use Drupal\acme_lookbook\Entity\Lookbook;
use Drupal\tilizy_commerce\Api\AdminApiControllerBase;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

final class LookbookController extends AdminApiControllerBase {

  public function list(Request $request): JsonResponse {
    $query = $this->scopedQuery('acme_lookbook');
    return $this->json($this->pagedList('acme_lookbook', $query, $request, $this->row(...), 'title', 'ASC'));
  }

  public function get(int $id): JsonResponse {
    $lookbook = $this->loadScoped('acme_lookbook', $id);
    assert($lookbook instanceof Lookbook);
    return $this->json($this->row($lookbook));
  }

  private function row(Lookbook $lookbook): array {
    return ['id' => (int) $lookbook->id(), 'title' => $lookbook->label()];
  }

}

The list query is filtered twice: once by the explicit condition for the selected store, and once by StoreQueryFilter for the stores the user may see. pagedList() returns the envelope every back-office collection uses, {items, meta: {page, per_page, total, has_more}}. The routes follow the platform's conventions:

acme_lookbook.api.lookbooks.list:
  path: '/api/commerce/admin/lookbooks'
  defaults:
    _controller: '\Drupal\acme_lookbook\Controller\Admin\LookbookController::list'
  methods: [GET]
  requirements:
    _permission: 'access tilizy commerce admin+administer tilizy commerce'
    _tc_capability: 'catalog.view'
  options:
    no_cache: TRUE

acme_lookbook.api.lookbooks.get:
  path: '/api/commerce/admin/lookbooks/{id}'
  defaults:
    _controller: '\Drupal\acme_lookbook\Controller\Admin\LookbookController::get'
  methods: [GET]
  requirements:
    _permission: 'access tilizy commerce admin+administer tilizy commerce'
    _tc_capability: 'catalog.view'
    id: '\d+'
  options:
    no_cache: TRUE

_tc_capability is checked by the team module when it is enabled; an unknown admin API route without it requires the broader extensions.operate capability. Write routes add _csrf_request_header_token: 'TRUE'. The public storefront API works the other way on purpose: its controllers extend StorefrontApiControllerBase, read with accessCheck(FALSE), and must add the store_id condition and a status filter themselves, because a shopper manages no store.

Extension points instead of forks

The free modules never name an optional module. Premium extensions, such as gift cards, loyalty and analytics, live in their own repositories, and country rules live in free tilizy_commerce_country_<cc> modules. All of them plug in through documented extension points: product kinds, adjustment types, order processors, price resolvers, checkout contributors, invoice providers, mail templates, storefront slots and back-office registry slots. Each third-party service gets its own extension, and core holds only the tool-neutral layer.

The order pipeline shows the pattern. OrderRefresher runs every service tagged tilizy_commerce.order_processor by priority: prices at 1000, promotions at 500, shipping at 300, tax at 100, prepaid means of payment at 50, totals last. A processor removes the adjustments it owns and adds them again, so a refresh can run any number of times. Only unlocked carts are refreshed; placed orders are frozen. A module that writes its own adjustment declares it with hook_tc_adjustment_types() and a role (payment, discount, charge or tax), and the role decides the taxable base, how invoices report it and where totals show it.

Product kinds are the smallest extension point to try. A kind decides what selling a product type means: whether new variants track stock, and whether promotions may discount its lines.

<?php

declare(strict_types=1);

namespace Drupal\acme_license\Plugin\ProductKind;

use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\tilizy_commerce_catalog\Attribute\ProductKind;
use Drupal\tilizy_commerce_catalog\Plugin\ProductKind\ProductKindBase;

/**
 * Software licenses: no stock, a key issued once the order is paid.
 */
#[ProductKind(
  id: 'license',
  label: new TranslatableMarkup('License'),
  description: new TranslatableMarkup('A license key issued after payment.'),
  trackInventory: FALSE,
  discountable: TRUE,
  weight: 10,
)]
final class License extends ProductKindBase {}

Fulfillment beyond shipping belongs to the module that provides the kind. It listens to the order events and asks the kind manager about each line:

<?php

declare(strict_types=1);

namespace Drupal\acme_license\EventSubscriber;

use Drupal\acme_license\LicenseIssuer;
use Drupal\tilizy_commerce_catalog\ProductKindManager;
use Drupal\tilizy_commerce_order\Event\OrderEvent;
use Drupal\tilizy_commerce_order\Event\OrderEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

final class LicenseOrderSubscriber implements EventSubscriberInterface {

  public function __construct(
    private readonly ProductKindManager $kinds,
    private readonly LicenseIssuer $issuer,
  ) {}

  public static function getSubscribedEvents(): array {
    return [OrderEvents::PAID => 'onPaid'];
  }

  public function onPaid(OrderEvent $event): void {
    foreach ($event->order->getItems() as $item) {
      if ($this->kinds->kindIdOfPurchasable($item->getPurchasable()) === 'license') {
        $this->issuer->issueFor($item);
      }
    }
  }

}

LicenseIssuer is your own service; make it safe to call twice for the same line. Register both classes as services, the subscriber with the event_subscriber tag. ProductKindManager has an autowiring alias, so autowire: true resolves the constructor. If the module is ever uninstalled, products of the unknown kind behave as standard and stay sellable. The back office shows the kind picker on product types only once a module adds a kind.

EU VAT, decided inside the pipeline

Tax is the processor at priority 100, so it always sees discounted prices and the chosen shipping. The eu_vat engine applies the place-of-supply rules in a fixed order. This is an abridged excerpt of EuVat::resolve(); the conditions are verbatim, and the remaining TaxRateResult arguments (label, source id, country, class, included rate and note) are left out:

if ($context->customerTaxExempt) {
  return [new TaxRateResult(TaxRateResult::KIND_EXEMPT, '0.0', /* label, source, note */)];
}
if (!$in_territory) {
  return [new TaxRateResult(TaxRateResult::KIND_EXPORT, '0.0', /* Art. 146 */)];
}
if ($destination_state === $store_country) {
  return [$this->taxable($store_country, $class, $store_country, $context)];
}
$vat_country = $context->isValidatedBusiness() ? VatNumberFormat::country($context->vatNumber) : NULL;
if ($vat_country !== NULL && $vat_country !== $store_country) {
  return [new TaxRateResult(TaxRateResult::KIND_REVERSE_CHARGE, '0.0', /* Art. 196 */)];
}
if (!empty($context->settings['oss_registered']) || $context->thresholdExceeded) {
  return [$this->taxable($destination_state, $class, $store_country, $context)];
}
return [$this->taxable($store_country, $class, $store_country, $context)];

Read it top to bottom, after an earlier branch for stores established outside the EU: tax-exempt customer, export outside the EU VAT territory, domestic sale, B2B buyer with a validated VAT number from another member state, then a consumer elsewhere in the EU, who pays the destination rate when the store is OSS-registered or has passed the €10,000 cross-border threshold this or last calendar year. Zero-rated outcomes still add a zero-amount tax adjustment that carries its legal basis, and the wording lands in order data as tax_note, ready for the invoice. VAT numbers go through VatNumberValidator, which checks the syntax and then VIES, caches definitive answers for 24 hours, and returns valid = NULL instead of throwing when VIES is unavailable.

Invoices close the loop. Numbers are gapless per store, document type and year: the sequence row is locked with SELECT … FOR UPDATE and advanced inside the transaction that saves the document, so a failed save hands the same number out again. Everything printed is a snapshot taken at issue time, and UblWriter produces UBL 2.1 invoices and credit notes following the EN 16931 core.

Trade-offs and limits

  • Isolation has a scope. It covers entity access and access-checked entity queries. A plain load() checks nothing until you call access() on the result, and a query with accessCheck(FALSE), a View or a direct database query is not filtered at all. Storefront code and custom SQL must add the store condition themselves, and in review those calls deserve a second look.
  • Priorities are a contract. A processor placed in the wrong slot sees the wrong totals. Choose its priority from the documented order and test it with tax and promotions enabled.
  • A platform of its own. Entity type ids carry a tc_ prefix so it can run next to Drupal Commerce on one site, but the two are separate platforms, and modules written for one do not plug into the other.
  • A modern stack. It needs Drupal 11.3, PHP 8.3, the SDX modules, Node.js on the build host for drush sdx:* and, for live back-office updates, a Mercure hub (it falls back to polling).
  • Known tax limits. OSS totals count EUR orders only, Northern Ireland goods rules are not modeled, and stores established in a special territory are not handled. Stores under other tax systems use the custom zones engine, where the merchant defines the zones.

The project page on drupal.org has the code and the issue queue, and the repository's docs/ARCHITECTURE.md and docs/DEVELOPING.md go further into the topics above. We left out the storefront's zero-build theming, where colors, fonts, radius, logo and home-page sections are store data applied as CSS custom properties; it deserves its own article. If you are planning a store, or a custom module on top of one, our build team can help.

Written by

Valentin Zsigmond

Founder & Lead Engineer

Full-stack Drupal architect with almost two decades of experience leading large teams in enterprise environments. Founded Tilizy Digital to bring senior-level expertise directly to the organizations that need it. Mentor to dozens of Drupal developers and creator of SDX — a Drupal extension for building modern frontends with React and Vue.

Enjoyed this article?

If this resonated, imagine what we could do working together on your Drupal site.