Saltar al contenido
MovieMaster

Desarrolladores: plugins y themes

Building plugins

3 min de lectura 14 apartados

En esta página

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 #

text
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.

MethodWhat it does
slug(): stringThe plugin's slug.
dir(): stringAbsolute path of the plugin's folder.
path(string $rel = ''): stringAbsolute path of a file in the plugin: $plugin->path('assets/app.css').
version(): stringThe manifest's version.
manifestRead-only property with the Manifest (name, get('key'), requirements…).
appRead-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): mixedReads 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): stringPublic 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(): JobsThe 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
<?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 #

EventWhen it fires
installThe first time the plugin is activated on this site.
activateEvery 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.
deactivateOn deactivation.
uninstallWhen 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
<?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() #

php
$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 #

typeFormSaved value
textA single line. Supports required and maxlength.string
textareaMultiple lines. Supports required and maxlength.string
numberInteger. min and max clamp the value.int
checkboxCheckbox.bool
selectDropdown with options (value => label). A value outside the list falls back to default.string
colorColor picker. Only #rrggbb.string
urlValidated http(s) URL. Supports required.string
listOne item per line (or comma-separated). item_type = url or host discards invalid ones.array
mediaMedia library picker. preset sets the crop.int (media id)
secretPassword: never shown again, saved encrypted (AES-256-GCM). Leaving it empty keeps the current value.string (decrypted with get)
infoHelp text, no field. Never saved.—

Definition keys #

KeyWhat it's for
labelField text (use __()).
defaultValue until the owner saves a different one.
helpHelp text under the field.
optionsFor select: ['value' => 'Label'].
min, maxFor number.
required, maxlengthFor text, textarea, and url.
item_typeFor list: url or host.
presetFor media: the image crop.
hide_whenKey of another checkbox in the same plugin: the field hides while that checkbox is checked.
sanitizefn($value, $field): array that returns ['value' => …, 'error' => ?string, 'notice' => ?string]. Runs after the type's validation.
php
$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:

php
$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 #

php
$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']). A GET route also responds to HEAD.
  • Parameters: {name} captures a segment ([^/]+); {name:regex} restricts it ({id:\d+}, {type:movie|series}).
  • Options:
OptionEffect
nameName for route('name', ['id' => 5]). Extra parameters go into the query string.
cachetrue allows the response to be stored in the static page cache. Defaults to false.
tagsPage cache tags (list:titles, title:42…) so it purges itself when the content changes.
middlewareList 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
<?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 returnResponse
ResponseAs-is.
stringHTML with status 200.
array or JsonSerializableJSON.
null204 with no content.
Anything elseConverted 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\Guard from the container (app(\Members\Guard::class)): check($request) checks same origin + token (X-CSRF-Token or _token), member($request) returns the logged-in member or null, csrf($request) gives the browser's token, and Guard::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 with MovieMaster\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
<?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:

html
@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>
@endsection

partials/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 #

php
$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 #

php
$plugin->lang(__DIR__ . '/lang');

lang/es.php and lang/en.php return an array:

php
<?php
return [
    'menu' => 'My plugin',
    'greeting' => 'Hello, :name',
    'results' => ':count result|:count results',
];
UsageResult
__('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 head hook. 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 with IntersectionObserver, on click, or only if there's a session).
php
// 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 #

php
$plugin->migrations(__DIR__ . '/migrations');
bash
php bin/console.php make:migration my-plugin create_votes_table

Generates migrations/0001_create_votes_table.php. A migration returns an anonymous class with up():

php
<?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 in data.tables so 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.

php
// 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 #

php
$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:

php
add_filter('console_commands', static function (array $commands): array {
    $commands['my-plugin:sync'] = MyPlugin\Console\SyncCommand::class;
    return $commands;
});
php
<?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 → contracts what its markup guarantees (player@1, mylist@1, install@1, i18n@1, account@1, comments@1).
  • The plugin declares in plugin.json → provides what it implements (Money Player: "provides": ["player@1"]).
php
$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 contract

What 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 with cap.
  • Store keys and passwords as secret settings, 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(): use app(\MovieMaster\Mail\Mailer::class)->later($to, $subject, $body), which sends it through the queue.
  • Build URLs with url(), route(), or lang_url().
  • Log errors with logger()->error('…') instead of echo or var_dump.
  • Prefix your tables, settings, jobs, /api/<slug>/… routes, and CSS classes so you don't collide with other plugins.

¿Te quedó alguna duda?

Escríbenos y te ayudamos con tu caso.

Hablar con nosotros
¿Hablamos?