Everything a plugin can do, with examples: the $plugin object, the lifecycle, settings, routes, views, translations, migrations, the queue, cron, and console commands. If you haven't created one yet, start with the developer introduction.
Plugin structure #
content/plugins/<slug>/
plugin.json spec 1 manifest (see the manifest reference)
plugin.php entry point: receives $plugin and only orchestrates
Lifecycle.php optional: install, activate, upgrade, deactivate, uninstall
src/ your classes, PSR-4 with the manifest's namespace (no Composer)
migrations/ 0001_name.php, 0002_…: your own tables
views/ .tpl templates: view('<slug>::name')
assets/ public CSS, JS, and images: $plugin->asset('file.js')
lang/ es.php, en.php…: __('<textdomain>::key')The folder name is the slug and must match the one in plugin.json. The classes in src/ load on their own using the manifest's namespace and autoload: "namespace": "MyPlugin\\" and "autoload": "src/" make MyPlugin\Api\Client resolve to src/Api/Client.php. All the manifest fields are in the plugin.json reference.
The $plugin object #
Inside plugin.php you have the $plugin variable (MovieMaster\Extensions\PluginContext). Its methods return the object itself, so they can be chained.
| Method | What it does |
|---|---|
slug(): string | The plugin's slug. |
dir(): string | Absolute path of the plugin's folder. |
path(string $rel = ''): string | Absolute path of a file in the plugin: $plugin->path('assets/app.css'). |
version(): string | The manifest's version. |
manifest | Read-only property with the Manifest (name, get('key'), requirements…). |
app | Read-only property with the application ($plugin->app->container). |
setting(string $key, array $def) | Declares a setting with an automatic form. Saved as plugin.<slug>.<key>. |
get(string $key, mixed $default = null): mixed | Reads one of your own settings: saved value → declared default → $default. secret values arrive already decrypted. |
route(string $method, string $path, mixed $handler, array $options = []) | Public route. Options: name, cache, tags, middleware. |
adminPage(string $key, string $label, mixed $handler, array $options = []) | Admin page at /admin/p/<slug>/<key>. See admin pages. |
views(string $dir, ?string $namespace = null) | Registers templates: view('<slug>::name'). |
lang(string $dir) | Registers translations in the plugin's domain. |
asset(string $file): string | Public URL for assets/<file> with ?v= to bust the browser cache. |
migrations(string $dir) | Runs that folder's migrations on activation and on every upgrade. |
job(string $type, callable|string $handler) | Registers the handler for a queue job type. |
jobs(): Jobs | The queue (MovieMaster\Queue\Jobs) for queuing jobs. |
cron(string $every, callable $fn) | Scheduled task: 'minute', 'hourly', or 'daily'. |
on(string $event, callable $fn) | Lifecycle: install, activate, upgrade, deactivate, uninstall. |
A typical plugin.php:
<?php
/** @var MovieMaster\Extensions\PluginContext $plugin */
declare(strict_types=1);
use MyPlugin\Api;
use MyPlugin\Admin;
$plugin->lang(__DIR__ . '/lang')
->views(__DIR__ . '/views')
->migrations(__DIR__ . '/migrations');
$plugin->adminPage('panel', __('my-plugin::menu'), [Admin::class, 'handle'], ['parent' => 'top', 'icon' => 'star', 'order' => 60]);
$plugin->setting('api_key', ['type' => 'secret', 'label' => __('my-plugin::api_key')]);
$plugin->setting('limit', ['type' => 'number', 'label' => __('my-plugin::limit'), 'default' => 20, 'min' => 1, 'max' => 100]);
$plugin->route('GET', '/api/my-plugin/status', [Api::class, 'status'], ['cache' => false]);
$plugin->job('my-plugin.sync', MyPlugin\Jobs\Sync::class);
$plugin->cron('hourly', static fn() => $plugin->jobs()->pushUnique('my-plugin.sync'));
add_action('title_deleted', static fn(array $title) => app(MyPlugin\Repo::class)->forget((int) $title['id']));Lifecycle #
| Event | When it fires |
|---|---|
install | The first time the plugin is activated on this site. |
activate | Every activation, also right after install or upgrade. |
upgrade($from, $to) | The version changed: when reactivating it or updating it from the store, after the migrations. |
deactivate | On deactivation. |
uninstall | When deleting it from the admin. It fires always, even if the plugin had been deactivated for a while. |
There are two ways to hook in, and they can coexist.
With Lifecycle.php (recommended) #
A <Namespace>\Lifecycle class at the plugin's root. The core loads it directly, without needing plugin.php in memory, so it's the safe way to handle whatever has to happen on uninstall.
<?php
declare(strict_types=1);
namespace MyPlugin;
final class Lifecycle extends \MovieMaster\Extensions\Lifecycle
{
public function install(): void
{
// $this->plugin is the PluginContext
app(\MovieMaster\Content\Settings::class)->set('plugin.my-plugin.installed', gmdate('c'));
}
public function upgrade(string $from, string $to): void
{
if (version_compare($from, '2.0.0', '<')) {
// convert data from the 1.x format
}
}
public function uninstall(): void
{
// notify an external service, delete files outside data.dirs…
}
}The available methods are install(), activate(), upgrade(string $from, string $to), deactivate(), and uninstall(); all empty by default.
With $plugin->on() #
$plugin->on('activate', static function (): void {
app(\MovieMaster\Content\PurgeService::class)->all();
});There are also the functions register_install_hook($slug, $fn), register_activation_hook, register_upgrade_hook, register_deactivation_hook, and register_uninstall_hook. They're only picked up if plugin.php loads during that request.
Guaranteed cleanup #
On uninstall, after your uninstall, the core always deletes whatever you declared in the manifest's data block: the tables in data.tables, the folders in data.dirs (relative to content/), and the settings starting with data.settings_prefix. Even if your code fails, nothing is left behind.
Settings #
$plugin->setting($key, $def) declares a field. The core renders the form, validates it, saves it, and gives you the value back with $plugin->get($key). The settings appear in Settings (under the plugins section of the sidebar index) and in the "Settings" button on the plugin's card in Admin → Plugins. Its URL is route('admin.settings', ['group' => 'plugin-<slug>']).
Field types #
type | Form | Saved value |
|---|---|---|
text | A single line. Supports required and maxlength. | string |
textarea | Multiple lines. Supports required and maxlength. | string |
number | Integer. min and max clamp the value. | int |
checkbox | Checkbox. | bool |
select | Dropdown with options (value => label). A value outside the list falls back to default. | string |
color | Color picker. Only #rrggbb. | string |
url | Validated http(s) URL. Supports required. | string |
list | One item per line (or comma-separated). item_type = url or host discards invalid ones. | array |
media | Media library picker. preset sets the crop. | int (media id) |
secret | Password: never shown again, saved encrypted (AES-256-GCM). Leaving it empty keeps the current value. | string (decrypted with get) |
info | Help text, no field. Never saved. | — |
Definition keys #
| Key | What it's for |
|---|---|
label | Field text (use __()). |
default | Value until the owner saves a different one. |
help | Help text under the field. |
options | For select: ['value' => 'Label']. |
min, max | For number. |
required, maxlength | For text, textarea, and url. |
item_type | For list: url or host. |
preset | For media: the image crop. |
hide_when | Key of another checkbox in the same plugin: the field hides while that checkbox is checked. |
sanitize | fn($value, $field): array that returns ['value' => …, 'error' => ?string, 'notice' => ?string]. Runs after the type's validation. |
$plugin->setting('use_cdn', ['type' => 'checkbox', 'label' => 'Use my CDN', 'default' => false]);
$plugin->setting('cdn_host', [
'type' => 'text',
'label' => 'CDN domain',
'hide_when' => 'use_cdn', // hides while the checkbox is checked
'sanitize' => static function (string $v): array {
$v = strtolower(preg_replace('#^https?://#', '', $v));
return $v === '' || preg_match('/^[a-z0-9.-]+$/', $v)
? ['value' => $v]
: ['value' => $v, 'error' => 'Enter just the domain, with no paths.'];
},
]);Reading settings:
$plugin->get('limit'); // inside the plugin
plugin_setting('my-plugin', 'limit', 20); // from anywhere
setting('plugin.my-plugin.limit'); // raw value (a secret arrives encrypted)When any group is saved, the settings_before_save($save, $group) filter and the settings_saved($group, $save) action run, and the page cache is cleared. Your plugin's group is called plugin-<slug>.
Public routes #
$plugin->route('GET', '/new-releases', [MyPlugin\NewReleases::class, 'index'], ['name' => 'new-releases', 'cache' => true, 'tags' => ['list:titles']]);
$plugin->route('GET', '/new-releases/page/{n:\d+}', [MyPlugin\NewReleases::class, 'index'], ['cache' => true, 'tags' => ['list:titles']]);
$plugin->route('POST', '/api/my-plugin/vote/{id:\d+}', [MyPlugin\Api::class, 'vote'], ['cache' => false]);- Methods:
GET,POST,PUT,DELETE, or a list (['GET', 'POST']). AGETroute also responds toHEAD. - Parameters:
{name}captures a segment ([^/]+);{name:regex}restricts it ({id:\d+},{type:movie|series}). - Options:
| Option | Effect |
|---|---|
name | Name for route('name', ['id' => 5]). Extra parameters go into the query string. |
cache | true allows the response to be stored in the static page cache. Defaults to false. |
tags | Page cache tags (list:titles, title:42…) so it purges itself when the content changes. |
middleware | List of classes implementing MovieMaster\Http\Middleware (handle(Request $request, callable $next): Response). |
The core's routes are registered before the plugins', and when two routes match the same URL, the first one registered wins: you can't override a core route, so pick your own (/api/<slug>/…, /<slug>/…).
The controller #
The handler can be [Class::class, 'method'], a closure, or any callable. It's called with dependency injection:
- The class's constructor receives any service from the container by its type (
TitleRepository,Settings,Connection…). - The method receives the route's parameters by name (
$id,$slug…) and$request.
<?php
declare(strict_types=1);
namespace MyPlugin;
use MovieMaster\Content\Repositories\TitleRepository;
use MovieMaster\Http\HttpException;
use MovieMaster\Http\Request;
use MovieMaster\Http\Response;
final class Api
{
public function __construct(private TitleRepository $titles) {}
public function vote(Request $request, string $id): Response
{
$title = $this->titles->find((int) $id);
if ($title === null) {
throw new HttpException(404);
}
$stars = max(1, min(5, $request->int('stars')));
// … save the vote
return Response::json(['ok' => true, 'stars' => $stars])->noCache();
}
}What the handler returns is converted like this:
| You return | Response |
|---|---|
Response | As-is. |
string | HTML with status 200. |
array or JsonSerializable | JSON. |
null | 204 with no content. |
| Anything else | Converted to text. |
For errors, throw MovieMaster\Http\HttpException with the status code (404, 403…): the theme renders its error page.
Page cache #
A response is stored in the static cache only if all these conditions are met: the route has cache => true, it's a GET, it responds 200, it carries no cookies, the request has no query string or session cookie, the route doesn't start with /admin, /install, or /api, and the page_cache_bypass($bypass, $request) filter doesn't return true. The response carries the X-MM-Cache: BYPASS header when it isn't stored.
Public forms and CSRF #
The core's CSRF token is only checked on /admin and /install. A public route that accepts POST must protect itself:
- If your plugin depends on Members, request
Members\Guardfrom the container (app(\Members\Guard::class)):check($request)checks same origin + token (X-CSRF-Tokenor_token),member($request)returns the logged-in member ornull,csrf($request)gives the browser's token, andGuard::expose($member)is the only thing that can go out to the browser (id,name). Never read its cookies by hand. - If not, at least check the origin (
$request->header('Origin')equal to$request->baseUrl()), rate-limit attempts withMovieMaster\Auth\RateLimiter, and validate every field.
Pages inside the theme's layout #
For a full public page (with the theme's header, footer, and SEO), extend MovieMaster\Frontend\Controllers\FrontController and use its page() method, which adds $site, $seo, and $template, and fires template_data, before_render, and template_path:
<?php
declare(strict_types=1);
namespace MyPlugin;
use MovieMaster\Content\Repositories\TitleRepository;
use MovieMaster\Frontend\Controllers\FrontController;
use MovieMaster\Http\Request;
use MovieMaster\Http\Response;
final class NewReleases extends FrontController
{
public function index(Request $request, TitleRepository $titles, string $n = '1'): Response
{
$page = max(1, (int) $n);
$result = $titles->paginate(['order' => 'release'], $page, $this->perPage());
$seo = $this->seo->error(200);
$seo->title = $this->seo->wrap(__('my-plugin::new_releases'));
$seo->canonical = url('/new-releases', true);
return $this->page('my-plugin::new-releases', [
'titles' => $result['items'],
'pagination' => $result,
], ['list:titles'], $seo);
}
}And views/new-releases.tpl:
@extends('layout')
@section('content')
<section class="wrap sec">
<h1 class="h1">{{ __('my-plugin::new_releases') }}</h1>
@include('partials/grid', ['titles' => $titles, 'lcp' => 8])
{!! pagination($pagination, '/new-releases') !!}
</section>
@endsectionpartials/grid is the active theme's grid: your page looks like the rest of the site without a single line of CSS. paginate() returns items, total, page, per_page, and last_page, exactly what pagination() expects (it takes the route without the domain and adds the language and /page/N itself). The full template syntax is in the template engine.
Views #
$plugin->views(__DIR__ . '/views'); // namespace = slug
echo view('my-plugin::widget', ['items' => $items]);A plugin view can @extends('layout') (the active theme's layout) or @extends('admin::layout') (the admin's), and include the theme's partials (@include('partials/card', …)) or its own (@include('my-plugin::partials/rail', …)). Names support subfolders with /.
Translations #
$plugin->lang(__DIR__ . '/lang');lang/es.php and lang/en.php return an array:
<?php
return [
'menu' => 'My plugin',
'greeting' => 'Hello, :name',
'results' => ':count result|:count results',
];| Usage | Result |
|---|---|
__('my-plugin::menu') | "My plugin" in the current language. |
__('my-plugin::greeting', ['name' => 'Ana']) | "Hello, Ana." Placeholders are :name. |
_n('my-plugin::results', 3) | "3 results." Singular and plural separated by |; :count is substituted automatically. |
__('my-plugin::menu', [], 'en') | Force a language. |
With spec 1, keys live in their own domain (textdomain, the slug by default), isolated from the core and from other plugins: you'll never overwrite a core string by using the same name. In templates it's used the same way: {{ __('my-plugin::menu') }}.
Assets: CSS, JavaScript, and images #
$plugin->asset('file') returns the public URL of assets/file with ?v=<modification date>. To stay within the Lighthouse budgets:
- CSS: print it inline and only on the pages that need it, from the
headhook. Build on the theme's tokens (var(--fg),var(--primary),var(--line)…) with a fallback value. - JavaScript: never in the initial load. Load it with
import()when needed (as the element approaches withIntersectionObserver, on click, or only if there's a session).
// Find out which template is being rendered
$tpl = null;
add_action('before_render', static function ($template = null) use (&$tpl): void {
$tpl = is_string($template) ? $template : null;
}, 10, 1);
// Inline CSS only on movie or show detail pages
add_action('head', static function () use (&$tpl, $plugin): void {
if ($tpl === 'title') {
echo '<style>' . minify_css((string) file_get_contents($plugin->path('assets/detail.css'))) . '</style>';
}
});
// JS on demand: downloads as the box comes into view
add_action('after_content', static function () use (&$tpl, $plugin): void {
if ($tpl !== 'title') {
return;
}
echo '<div id="my-box" style="min-height:240px"></div>'
. '<script type="module">{const e=document.getElementById("my-box");new IntersectionObserver((o,io)=>{if(o[0].isIntersecting){io.disconnect();import('
. json_encode($plugin->asset('box.js'), JSON_UNESCAPED_SLASHES) . ').then(m=>m.default(e))}},{rootMargin:"600px"}).observe(e)}</script>';
});Database and migrations #
$plugin->migrations(__DIR__ . '/migrations');php bin/console.php make:migration my-plugin create_votes_tableGenerates migrations/0001_create_votes_table.php. A migration returns an anonymous class with up():
<?php
declare(strict_types=1);
use MovieMaster\Database\Connection;
use MovieMaster\Database\Migration;
use MovieMaster\Database\Schema\Blueprint;
use MovieMaster\Database\Schema\Schema;
return new class extends Migration {
public function up(Schema $s, Connection $db): void
{
if ($s->hasTable('votes')) {
return;
}
$s->create('votes', function (Blueprint $t) {
$t->id();
$t->unsignedBigInteger('title_id');
$t->tinyInteger('stars');
$t->string('ip_hash', 64)->nullable();
$t->timestamps();
$t->index(['title_id']);
});
}
};- Migrations run in order when the plugin is activated, on every upgrade, and with
php bin/console.php migrate. Each one runs exactly once. - They are forward-only: don't change a published migration, add another one (
0002_…). - Table names go without a prefix: the core adds the site's own (
mm_). Declare your tables indata.tablesso they get deleted on uninstall. - They work the same way on MySQL/MariaDB and SQLite. Write portable SQL or use the query builder.
To query: db()->table('votes')->where('title_id', 42)->count(). The full query builder, Schema, Blueprint, and the content repositories are in the PHP API reference.
Job queue #
Heavy work (external API calls, importing images, recalculating) goes to the queue, which the cron processes every minute.
// Register the handler: a callable that receives the payload, or a class with handle(array $payload)
$plugin->job('my-plugin.sync', MyPlugin\Jobs\Sync::class);
$plugin->job('my-plugin.ping', static function (array $payload): void {
// …
});
// Queue it
$plugin->jobs()->push('my-plugin.ping', ['url' => $url]); // now
$plugin->jobs()->push('my-plugin.ping', ['url' => $url], 300); // in 5 minutes
$plugin->jobs()->pushUnique('my-plugin.sync', ['id' => 42], 0, 5); // doesn't duplicate an identical pending one; priority 5- If the handler throws an exception or returns
false, the job retries later (60 s × attempt). After 3 attempts it's marked failed and shows up in Admin → Queue. - A handler class is created through the container: its constructor can request services.
- Use names prefixed with your plugin (
my-plugin.something) so you don't collide with the core's (tmdb.import,catalog.import,mail.send…). - Locally, without cron, process the queue with
php bin/console.php queue:work.
Scheduled tasks #
$plugin->cron('minute', static fn() => …); // every cron run (every minute)
$plugin->cron('hourly', static fn() => …); // once an hour
$plugin->cron('daily', static fn() => app(MyPlugin\Repo::class)->cleanup());These are equivalent to the cron, cron_hourly, and cron_daily actions. The hourly and daily ones run after the core's maintenance. Cron must be fast: if a task takes a while, queue a job and return.
Console commands #
Add commands to php bin/console.php with the console_commands filter:
add_filter('console_commands', static function (array $commands): array {
$commands['my-plugin:sync'] = MyPlugin\Console\SyncCommand::class;
return $commands;
});<?php
declare(strict_types=1);
namespace MyPlugin\Console;
use MovieMaster\Console\Command;
use MovieMaster\Console\Io;
final class SyncCommand implements Command
{
public static function description(): string
{
return 'Syncs the votes with the external service';
}
public function run(array $args, Io $io): int
{
$limit = (int) ($args['limit'] ?? 100); // --limit=50
$io->title('Syncing');
// …
$io->success("Done ($limit)");
return 0; // exit code
}
}$args carries the positional arguments with a numeric index ($args[0]) and the --key=value options by name. Io offers line, info, success, warn, error, title, ask, secret, confirm, and table. Commands only exist once the site is installed.
Contracts with the theme #
A contract is a named, versioned agreement (name@N) between the theme and the plugins: that way neither needs to know the other's classes.
- The theme declares in
theme.json→contractswhat its markup guarantees (player@1,mylist@1,install@1,i18n@1,account@1,comments@1). - The plugin declares in
plugin.json→provideswhat it implements (Money Player:"provides": ["player@1"]).
$contracts = (array) (active_theme()['contracts'] ?? []);
if (in_array('comments@1', $contracts, true)) {
// the theme already provides its slot with @hook('comments'): don't print the box in after_content
}
plugin_active('members'); // is that plugin active?
plugin_providers('player@1'); // slugs of the active plugins that offer that contractWhat each contract guarantees is in create themes.
Best practices #
- Escape everything you print with
e()(in templates,{{ }}already escapes). Use{!! !!}only with trusted HTML. - Check permissions with
app(\MovieMaster\Auth\Auth::class)->can('manage_content')on anything that doesn't go through an admin route withcap. - Store keys and passwords as
secretsettings, never in plain text or in files. - Use the repositories to create, edit, or delete content: they write the 410s, purge the cache, update the sitemaps, and notify IndexNow.
- Purge whatever you change:
app(\MovieMaster\Content\PurgeService::class)->title($id)or->purge(['your-tag']). - Never call
mail(): useapp(\MovieMaster\Mail\Mailer::class)->later($to, $subject, $body), which sends it through the queue. - Build URLs with
url(),route(), orlang_url(). - Log errors with
logger()->error('…')instead ofechoorvar_dump. - Prefix your tables, settings, jobs,
/api/<slug>/…routes, and CSS classes so you don't collide with other plugins.