Skip to content
ReferenceForDeveloper⏱ About 12 min

Modules: the back end ​

Routes ​

api.entry is the router file, api.router its function, api.prefixes the paths it owns:

json
"api": { "entry": "api/routes.php", "router": "hello_route", "prefixes": ["/hello"], "default_permission": "hello.view", "public_paths": [] }
  • The function is function($method, $path, $body). Return when the path isn't yours; otherwise answer and stop.
  • Answer with ApiResponse::ok($data, $message = '') or ApiResponse::error($message, $status, $data = null); both end the request. The client gets {"success", "message", "data", …}.
  • On an unexpected error use ApiResponse::fail('Could not …', 500, $e, 'hello_failed'): it logs the exception and gives the caller a request id, never the exception's text.
  • public_paths skip sign-in and CSRF (for webhooks): those routes must check their own signature.
  • Your router file is loaded only for organizations that have the module enabled.

Permissions ​

json
"permissions": [
  { "key": "hello.view", "label": "Use Hello", "scope": "tenant", "default_groups": ["tenant_admin"] },
  { "key": "hello.edit", "label": "Change Hello", "scope": "tenant" }
]
  • Keys are <module id>.<action>. scope is tenant or platform. default_groups (tenant_admin, all_users) are granted when an organization enables the module.
  • The gate already checks default_permission for every path. For finer checks:
CallDoes
Rbac::requirePermission('hello.edit')401 if signed out, 403 without the key
Rbac::hasPermission('hello.edit')true / false
Rbac::requireTenantAdmin($tenantId)organization admins only
Rbac::requirePlatform()BMA staff only
  • A key added in a later version reaches existing organizations through x-grant-from-menus (grant it to groups that already see one of your menus); default_groups covers new installs.

How grants and menus work together:

  • On enable, default_groups get the module's keys (tenant_admin: groups holding tenant.admin; all_users: every group of the organization). An existing grant row, even one an administrator switched off, is never changed.
  • A permission brings its menus: install and enable grant each menu item to the groups that hold the item's permission. They never change a menu row's existing on/off state.
  • Upgrades never re-grant. x-grant-from-menus grants only keys that the new version lists and the previous one did not. A key an administrator took away stays away in later versions; nothing is ever revoked. Each grant is audited as module.grant_from_menus.

Data, scoped to the organization ​

Every row belongs to one organization, and every query must say so. Tenant::currentId() is the caller's organization.

  • Your own tables (data.tables, created by your migrations): give each a tenant_id column and filter on it, or declare the right scope (tenant_column, tenant_db, tenant_prefix).

  • Shared inventory tables: use InventoryQuery, which turns a /*TENANT*/ marker into the right filter for each organization's database layout and refuses statements without it:

    php
    $rows = InventoryQuery::select('SELECT id, name FROM vehicles WHERE /*TENANT*/ AND status = ?', array('open'));
  • Never put request values into SQL text: bind them.

  • When a scoped lookup finds nothing, answer 404, never 403, so organizations can't probe each other's ids.

  • php bin/lint-tenant-scope.php finds unscoped queries; the test suite fails on any finding. Set scope_verified: true only when it reports none.

  • Files go through TenantFileStore, never a fixed path.

Migrations ​

List them in data.migrations; each returns up (and down):

php
<?php
return array(
    'up' => function (PDO $pdo, $driver, array $ctx) {
        // $driver: mysql, pgsql or sqlite; $ctx: tenant_id, module_id, migration, shared
        // check before creating: migrations can run more than once on a shared database
    },
    'down' => function (PDO $pdo, $driver, array $ctx) { /* undo, or null */ },
);

Rules: idempotent; portable across MySQL, PostgreSQL and SQLite (no NOW() (bind the time from PHP), no backticks, no ON DUPLICATE KEY, no IFNULL); never rename a migration file. On upgrade only new files run; a downgrade runs the down() of files the older version doesn't list, and is refused if one has none.

Lifecycle hooks ​

"hooks": {"class": "HelloModuleHooks"}, declared in your router file. Extend ModuleHooksBase and override what you need: install($ctx), enable($ctx), disable($ctx), upgrade($ctx, $from), uninstall($ctx). $ctx has the organization, module, version and a db callable. No schema changes in hooks: that's what migrations are for.

StepRuns
installmigrations, then install, permissions, menus
enablechecks, then enable, default grants
upgradenew migrations, then upgrade($ctx, $from)
disabledisable (never blocks)
uninstalluninstall, optionally the down()s

Scheduled work: have the hooks class implement task($name, $ctx), and create the job from enable with CronService::ensureModuleTaskJob() (remove it in disable). It runs only while the module is enabled.

Hooks run inside the registry's transaction

install, enable and uninstall run inside the registry's own transaction on the app database: an exception rolls the whole step back (hook_failed). So a hook must stay small. In practice it should only add or remove its cron job row. Don't open the organization's inventory connection from a hook (a second connection would wait on the transaction), and don't write your own tables there: seed defaults on the first request instead, as SAWScore does (worked example). This is a rule, not a check: nothing stops a hook from doing more, so review it.

Settings ​

settings_schema is a small JSON Schema: an object of string, number, integer, boolean or string-array properties with title, description, default, enum, limits, format (uri, email).

  • "x-secret": true: sealed at rest, never sent back (the form shows Saved).
  • "x-tenant-editable": false: only BMA staff can change it.
  • Read them on the server with ModuleRegistry::runtimeSettings($tenantId, 'hello') (defaults applied, secrets opened; never send that to a browser). Your screens get the non-secret ones as host().settings.
  • A new x-secret field must also be listed in BMA's secret registry (SecretRegistry); a test fails until it is.

Marketplace-managed modules ​

Two manifest keys matter when a module is sold in the marketplace:

KeyEffect
"x-entitlement": "marketplace"the organization's subscription switches the module on and off. Organization administrators get 403 managed_by_marketplace on install, enable, disable, uninstall, pin, upgrade and fork; BMA staff keep every action. A variant follows its base
"x-no-backfill": truethe module is new in BMA 2.x: the upgrade from classic installs (module:import-legacy) never installs or enables it for an organization by itself