All the global functions and core classes a plugin or theme can use, with their real signatures. Services are requested from the container with app(Class::class) or, better, received in your classes' constructors (type-hint injection).
Global functions #
Core #
| Function | Returns |
|---|---|
app(?string $abstract = null): mixed | With no arguments, the application ($app->container, $app->hooks()). With a class, the service resolved by the container. |
config(string $key, mixed $default = null): mixed | Config from config.php, dot notation (config('app.url')). |
setting(string $key, mixed $default = null): mixed | A saved setting (setting('general.site_name')). |
db(): Connection | The database connection. |
cache(): CacheManager | The object cache (files, APCu, or Redis). |
logger(): Logger | The log at content/logs/app.log. |
request(): Request | The current request. |
hooks(): HookManager | The hook manager. See the hooks reference. |
media(): MediaRepository | The media library. |
mm_version(): string | Core version (0.9.54). |
now(): string | UTC date and time in Y-m-d H:i:s format, the one database columns use. |
Text and data #
| Function | What it does |
|---|---|
e(mixed $value): string | Escapes for HTML. null → '', true → '1', arrays and objects → escaped JSON. |
str_limit(string $s, int $max = 160, string $end = '…'): string | Trims text without splitting multibyte characters. |
array_get(array $arr, string $key, mixed $default = null): mixed | Reads an array with dot notation ('a.b.c'). |
compact_number(int $n): string | 1500 → 1.5K, 2000000 → 2M. |
minify_css(string $css): string | Minifies CSS (used by inline_css and your inline styles). |
Languages and URLs #
| Function | What it does |
|---|---|
__(string $key, array $replace = [], ?string $lang = null): string | Translates. 'domain::key' for a plugin's or theme's strings. |
_n(string $key, int $count, array $replace = [], ?string $lang = null): string | Translates with a plural ('one|many'); fills in :count. |
current_lang(): string | The request's language (es, en). |
url(string $path = '/', bool $absolute = false): string | URL of a site route in the current language, with the owner's URL words (/movies → /peliculas). |
lang_url(string $path, ?string $lang = null, bool $absolute = false): string | Same, but choosing the language. |
route(string $name, array $params = [], ?string $lang = null, bool $absolute = false): string | URL of a named route. Extra parameters go into the query string. |
site_url(string $path = '/'): string | Absolute URL with the site's domain, without translating words or adding a language (files, webhooks). |
Views, forms, and media #
| Function | What it does |
|---|---|
view(string $name, array $data = []): string | Renders a template ('partials/card', 'my-plugin::box', 'admin::layout'). |
csrf_token(): string / csrf_field(): string | The admin panel's token and its <input type="hidden" name="_token">. |
old(string $key, mixed $default = null): mixed | Value submitted in the previous form (after a validation error). |
media_url(int $id, string $size = 'thumb', string $format = 'jpg'): string | URL of an image variant. |
img(?array $media, string|int $size = 'thumb', array $options = []): string | <picture> AVIF → WebP → JPEG with srcset, width, and height. Options: alt, lazy (defaults to true), priority (the LCP image), sizes, class, max. |
art_img(?array $wide, ?array $tall, string $alt = '', bool $priority = false, string $class = 'bg'): string | Background image with landscape art on desktop and portrait on mobile. |
Theme functions (player(), trailer_facade(), wordmark(), rating_badge(), rank_svg(), pagination(), lang_switcher(), theme_setting(), theme_vars(), inline_css(), theme_asset(), child_theme_asset(), brand_asset(), theme_file(), theme_dirs()) are covered in creating themes.
Extensions #
| Function | What it does |
|---|---|
plugin_setting(string $slug, string $key, mixed $default = null): mixed | A plugin's setting (secret ones arrive decrypted). |
plugin_active(string $slug): bool | Is that plugin active? |
plugin_providers(string $contract): array | Slugs of the active plugins that declare that contract in provides. |
active_theme(): ?array | The active theme's manifest (slug, name, version, contracts, supports…). |
register_install_hook(string $slug, callable $fn) | Also register_activation_hook, register_upgrade_hook, register_deactivation_hook, register_uninstall_hook. See lifecycle. |
Request and response #
MovieMaster\Http\Request #
| Method | Returns |
|---|---|
method(), isGet(), isPost(), isMethod('PUT') | HTTP method (isGet() includes HEAD). |
path(): string | Normalized path, without the query string. |
query(?string $key = null, $default = null) | Query string parameters (no key: all of them). |
post(?string $key = null, $default = null) | Form fields. |
input(string $key, $default = null) | Looks in the JSON body, the form, and the query string. |
all(): array | All of the above combined. |
string(string $key, string $default = '') | Field as trimmed text. |
int(string $key, int $default = 0) | Field as an integer. |
bool(string $key, bool $default = false) | Field as a boolean (1, true, on, yes). |
array(string $key): array | Field as an array. |
json(): mixed | Decoded JSON body. |
rawBody(): string | Raw body (webhooks with a signature). |
file(string $key): ?array / files() | Uploaded files. |
cookie(string $key, ?string $default = null), hasCookie(), cookies() | Cookies. |
header(string $name, ?string $default = null), headers() | Headers (case-insensitive). |
ip(): string | Visitor's IP. |
isSecure(), scheme(), host(), baseUrl(), url(), fullUrl() | URL data. |
isAjax(), wantsJson(), userAgent(), referer() | Client data. |
param(string $key, $default = null) | Route parameter ({id}). |
attribute(), setAttribute() | Data middleware passes to the controller. |
MovieMaster\Http\Response #
Response::html(string $body, int $status = 200)
Response::json(mixed $data, int $status = 200, int $flags = 0)
Response::xml(string $body, int $status = 200)
Response::text(string $body, int $status = 200)
Response::redirect(string $url, int $status = 302)
Response::notFound(string $body = 'Not Found')Chainable methods: setStatus(int), setBody(string), header(string $name, string $value), cookie(string $name, string $value, int $expires = 0, array $options = []), cacheTags(array $tags), and noCache() (prevents it from being stored in the page cache and sends Cache-Control: no-store).
To abort with an error from anywhere: throw new \MovieMaster\Http\HttpException(404).
Router #
You receive it in the routes (public site) and admin_routes (inside /admin) actions. For public routes, prefer $plugin->route().
$r->get(string $pattern, mixed $handler, array $options = []); // also post, put, delete, any
$r->add(string|array $methods, string $pattern, mixed $handler, array $options = []);
$r->group(string $prefix, array $options, callable $fn);
$r->has(string $name): bool;
$r->url(string $name, array $params = []): string;Database #
Connection (db()) #
| Method | What for |
|---|---|
table(string $table): Query | Starts a query. The name goes without the prefix. |
select(string $sql, array $bindings = []): array | Raw SQL: all rows. |
selectOne(string $sql, array $bindings = []): ?array | Raw SQL: one row. |
scalar(string $sql, array $bindings = []): mixed | Raw SQL: a single value. |
execute(string $sql, array $bindings = []): int | Raw SQL that modifies data: rows affected. |
transaction(callable $fn): mixed | Runs $fn in a transaction; rolls back if it throws. |
prefixed(string $table): string | The real table name (votes → mm_votes), for raw SQL. |
quoteId(string $id): string | Quotes an identifier for the engine in use. |
driver(), isMysql(), isSqlite() | The engine in use. |
lastInsertId(): int | Last inserted id. |
Query #
Fluent builder. All filter methods return the query itself.
| Group | Methods |
|---|---|
| Selection | select(...$cols), addSelect(...), distinct(), from($table, $alias), Query::raw($sql, $bindings) |
| Conditions | where($col, $op, $val) (or where($col, $val)), orWhere(...), where(fn($q) => …) to group, whereRaw($sql, $bindings), whereIn($col, array|Query), whereNotIn(...), whereNull($col), whereNotNull($col), whereBetween($col, $a, $b), whereLike($col, $value), whereExists(Query $sub) |
| Joins | join($table, $first, $op, $second), leftJoin(...), joinRaw($sql) |
| Order and limits | orderBy($col, 'ASC'|'DESC'), orderByRaw($sql), latest($col = 'created_at'), inRandomOrder(), groupBy(...), having($sql, $bindings), limit($n), offset($n), forPage($page, $perPage) |
| Reading | get(): array, first(): ?array, find($id, $col = 'id'), value($col), pluck($col, $key = null), exists(): bool, count(), sum($col), max($col), min($col), paginate($page, $perPage) → items, total, page, per_page, last_page |
| Writing | insert(array) (one row or several), insertGetId(array): int, insertOrIgnore(array), upsert(array $values, array $uniqueBy, ?array $update), update(array): int, increment($col, $n = 1, $extra = []), decrement(...), delete(): int, truncate() |
| Debugging | toSql(): array (SQL and bindings) |
$top = db()->table('votes')
->select('title_id', Query::raw('COUNT(*) AS total'))
->where('created_at', '>=', gmdate('Y-m-d H:i:s', time() - 86400 * 7))
->groupBy('title_id')
->orderBy('total', 'DESC')
->limit(10)
->get();
db()->table('votes')->upsert(
['title_id' => 42, 'ip_hash' => $hash, 'stars' => 5, 'created_at' => now(), 'updated_at' => now()],
['title_id', 'ip_hash'],
['stars', 'updated_at'],
);Migrations: Schema and Blueprint #
A migration extends MovieMaster\Database\Migration and implements up(Schema $schema, Connection $db): void. See database and migrations.
| Schema | Blueprint (columns) | Column (modifiers) |
|---|---|---|
create($table, fn(Blueprint $t)), table($table, fn) (alter), drop($table), hasTable($table), hasColumn($table, $col), columns($table), rename($from, $to) | id(), string($name, $len = 190), char(), text(), mediumText(), longText(), integer(), unsignedInteger(), bigInteger(), unsignedBigInteger(), smallInteger(), tinyInteger(), boolean(), decimal(), float(), date(), dateTime(), timestamp(), timestamps(), json(), binary(); indexes primary(), unique(), index(), fulltext(); when altering, dropColumn(), dropIndex(), dropUnique(), renameColumn() | nullable(), default($v), unsigned(), primary(), unique(), index(), useCurrent(), after($col) (MySQL only) |
Types are translated to MySQL/MariaDB and SQLite automatically.
Settings and cache #
MovieMaster\Content\Settings #
| Method | What for |
|---|---|
get(string $key, mixed $default = null): mixed | Read. Same as setting(). |
set(string $key, mixed $value, bool $autoload = true): void | Save one. autoload = false for large values not needed on every request. |
setMany(array $values, bool $autoload = true): void | Save several. |
delete(string $key) / deleteGroup(string $prefix) | Delete one, or all starting with a prefix. |
group(string $prefix): array | All of the settings under a prefix ('plugin.my-plugin.'). |
Object cache (cache()) #
$data = cache()->remember('my-plugin:ranking', 600, fn() => computeRanking()); // 10 minutes
cache()->get($key, $default); cache()->set($key, $value, $ttl = 3600); cache()->has($key);
cache()->delete($key); cache()->increment($key, $by = 1, $ttl = 3600);The owner picks the driver (files, APCu, or Redis with the Redis Cache plugin). A plugin can add one with CacheManager::extend('name', fn() => new MyDriver()) implementing MovieMaster\Cache\CacheInterface. Always prefix your keys.
Page cache and purges #
| Class and method | What for |
|---|---|
PurgeService::title(int $id, array $extraTags = []) | Purges the detail page, its cards, listings, home page, sitemaps, RSS, and search. |
PurgeService::term(int $id, string $taxonomy), person(int $id), page(int $id) | Same, for terms, people, and pages. |
PurgeService::purge(array $tags) | Purges specific tags (your own). |
PurgeService::all() | Clears the entire page cache. |
PageCache::purgePath(string $uri) | Deletes a specific URL. |
PageCache::enabled(): bool | Is the static page cache active? |
Tags the core uses: home, title:<id>, card:<id>, term:<id>, person:<id>, list:titles, list:movies, list:series, list:people, list:terms:genre, list:terms:tag, sitemap, rss, search, robots, pwa.
Content #
The repositories live in MovieMaster\Content\Repositories. They return arrays already translated into the requested language ($lang, the current one by default) and with url ready to link to. Always write through them: they generate the 410s and 301s, purge the cache, reindex search, and notify IndexNow.
TitleRepository (movies and series) #
| Method | What for |
|---|---|
find(int $id, ?string $lang = null, bool $withRelations = true, int $castLimit = 0): ?array | A title with genres, cast, etc. |
findBySlug(string $type, string $slug, ?string $lang = null, bool $publishedOnly = true): ?array | By slug (movie/series). |
findByTmdb(string $type, int $tmdbId): ?int | Local id of a TMDB title. |
list(array $filters, int $limit, ?string $lang = null, bool $withRelations = false): array | A list. |
paginate(array $filters, int $page, int $perPage, ?string $lang = null, bool $withRelations = false): array | A page: items, total, page, per_page, last_page. |
query(array $filters, ?string $lang = null): Query | The unexecuted query, for you to refine. |
published(?string $type = null): Query | Published and visible only. |
related(array $title, int $limit, ?string $lang = null): array | Related titles. |
hero(int $limit, ?string $lang = null): array | The ones in the home page carousel. |
counts(): array, years(?string $type = null): array | Totals, and years with titles. |
save(array $data, array $translations, ?array $termIds, ?array $credits, ?int $id = null): int | Create or edit. |
delete(int $id): void, setStatus(array $ids, string $status): void | Delete or change status (published, draft). |
TitleRepository::isPublic(array $t): bool | Can a visitor see it? |
Filters for list, paginate, and query:
| Filter | Value |
|---|---|
type | movie or series |
order | newest (default), popular, views, trending, rating, year, release, updated, random |
term_id | Id of a genre or tag |
person_id | Id of a cast or crew person |
year | Year |
search | Text to search for |
featured | 1 = featured only |
with_backdrop | 1 = only ones with a backdrop image |
exclude | Array of ids to exclude |
status | Status (defaults to published only) |
no_sources | 1 = only ones without video sources |
Fields of a title: id, type, slug, url, title, overview, tagline, year, rating, runtime_label, poster, backdrop, logo (media rows for img()), genres, tags, terms, cast, directors, writers, creators, meta_title, meta_description, noindex, is_fallback (the translation came from the default language).
EpisodeRepository #
| Method | What for |
|---|---|
seasons(int $titleId, ?string $lang = null): array / season($titleId, $number, $lang) | Seasons. |
episodes(int $titleId, int $seasonNumber, ?string $lang = null): array | A season's episodes. |
episode(int $titleId, int $season, int $episode, ?string $lang = null): ?array / find(int $id) | A single episode. |
neighbours(array $ep, ?string $lang = null): array | Previous and next. |
latest(int $limit, ?string $lang = null): array | Latest published episodes. |
saveSeason(...), saveEpisode(...), deleteSeason(...), deleteEpisode(int $id) | Writing. |
url(string $seriesSlug, int $season, int $episode, ?string $lang = null) / seasonUrl(...) | URL of an episode or season. |
PersonRepository, TermRepository, and PageRepository #
| Repository | Reading | Writing |
|---|---|---|
PersonRepository | find, findBySlug, findMany(array $ids), paginate($page, $perPage, $lang, $search, $order), search($q, $limit), creditsForTitles(array $titleIds), findByTmdb | save, findOrCreateByName, delete, recount |
TermRepository | find, findBySlug($taxonomy, $slug), findMany, all($taxonomy, $lang, $order, $limit, $onlyUsed), paginate($taxonomy, …), forTitles(array $titleIds, $lang, $taxonomy), search($taxonomy, $q), url(array $term) | save($taxonomy, …), findOrCreateByName, findOrCreateByTmdb, delete, recount |
PageRepository | find, findBySlug, all($lang, $publishedOnly, $footerOnly) | save, delete |
The core's taxonomies are genre and tag. A plugin can use its own ('platform') with TermRepository, and give it a name and URL via the taxonomy_label and taxonomy_url_prefix filters.
SourceRepository (video sources) #
| Method | What for |
|---|---|
forTitle(int $titleId, ?int $episodeId = null, bool $activeOnly = true): array | Sources for a movie or episode. |
SourceRepository::grouped(array $sources): array | Grouped by language, as received by player(). |
add(int $titleId, ?int $episodeId, string $url, array $meta = []) | Add one (meta: language, quality, server, sort_order, is_active). Returns the id, or an error string if the URL isn't valid. If it already exists, returns its id. |
replace(int $titleId, ?int $episodeId, array $rows): array | Replace all of them. |
delete(int $id) | Delete one. |
SourceRepository::languages(), defaultLanguage(), serverName(string $url) | Valid languages, the default one, and a URL's server name. |
MediaRepository (media()) #
| Method | What for |
|---|---|
find(int $id): ?array, findMany(array $ids) | Media rows. |
store(array|string $file, string $preset = 'thumb', ?int $userId = null, ?string $alt = null): array | Stores an uploaded image ($request->file('x')) or a path, and generates the variants. |
importFromUrl(string $url, string $preset = 'thumb', ?int $userId = null, ?string $alt = null): array | Downloads and processes a remote image. |
url(int|array $media, string|int $size = 'thumb', string $format = 'jpg'): string | URL of a variant. |
delete(int $id): bool, updateAlt(int $id, string $alt) | Delete it, or change its alt text. |
Presets: poster (2:3), backdrop (16:9), still (16:9), profile (2:3), thumb (16:9), logo, title_logo, cover, term, favicon, og. To render one, always use img($media, 'poster', ['alt' => …]).
SEO, URLs, and redirects #
| Class | Useful methods |
|---|---|
Seo\SeoBuilder | error(int $status): PageSeo (empty base for your pages), wrap(string $title): string (applies the site's title pattern). |
Seo\PageSeo | Public properties: title, description, canonical, robots, type, image, imageWidth, imageHeight, alternates, prev, next, videoUrl, videoDuration, publishedTime, graph. |
Seo\MetaStore | get(string $entity, int $id, string $lang), save($entity, $id, array $byLang), forget($entity, $ids): custom SEO title and description for title, season, episode, term, person, and page. |
Seo\IndexNow | enabled(), queue(array $paths, bool $urgent = false): notifies Bing, Yandex, and others of new or changed URLs (the repositories already do this). |
Content\Redirects | add(string $from, string $to, int $status = 301), gone(string $path) (410), find(string $path), delete(int $id), all(). |
Content\UrlKeys | setSeason(...), setEpisode(...): change a season's or episode's URL word, creating the 301s. |
I18n\Lang | current(), default(), enabled(), isEnabled($lang), url(string $path, ?string $lang), word(string $key, ?string $lang) (configured URL word: word('movie') → pelicula), locale(). |
Users, permissions, and security #
Auth and roles #
$auth = app(\MovieMaster\Auth\Auth::class);
$auth->check(); // is there an admin panel session?
$auth->user(); // the user row, or null
$auth->id(); $auth->role();
$auth->can('manage_content'); // capability| Role | Capabilities |
|---|---|
admin | All of them (*). |
editor | access_admin, manage_content, publish_content, edit_others_content, delete_content, upload_media, manage_terms, manage_people, manage_pages, view_stats |
author | access_admin, manage_content, upload_media, view_stats |
Only admin has manage_settings (settings, SEO, appearance, plugins, themes, license, updates) and manage_users; the same goes for any new capability you invent, until you grant it to another role. A plugin can grant new capabilities to a role with the role_capabilities filter:
add_filter('role_capabilities', static function (array $caps, string $role): array {
if ($role === 'editor') {
$caps[] = 'my_plugin_moderate';
}
return $caps;
});These are admin panel users. Registered site visitors belong to the Members plugin (Members\Guard, see creating plugins).
Session, CSRF, and rate limiting #
| Class | Methods |
|---|---|
Auth\Session (admin panel only) | get, set, has, remove, flash($key, $value), getFlash($key), regenerate() |
Auth\Csrf (admin panel only) | token(), validate(Request $request). In /admin it's already checked automatically on every POST. |
Auth\RateLimiter | tooManyAttempts(string $key): bool, hit(string $key): int, availableIn(string $key): int (seconds), clear(string $key). Defaults to 5 attempts every 15 minutes. |
$limiter = app(\MovieMaster\Auth\RateLimiter::class);
$key = 'my-plugin:vote:' . hash('sha256', $request->ip());
if ($limiter->tooManyAttempts($key)) {
return Response::json(['error' => 'too_many'], 429);
}
$limiter->hit($key);Secret #
MovieMaster\Extensions\Secret encrypts with the site's key (AES-256-GCM). This is what secret-type settings use.
$encrypted = Secret::encrypt($token);
$token = Secret::decrypt($encrypted);
Secret::isSet($encrypted); // is there a saved value?Email #
$mailer = app(\MovieMaster\Mail\Mailer::class);
$mailer->later($to, $subject, $text); // via the queue: the normal way
$mailer->send($to, $subject, $text); // right now: true or false; the reason is in $mailer->error()
$mailer->usable(); // is a sending method configured?Email is plain text. The owner picks the method in Settings → Email; a plugin can send it on its own (a provider's API) with the mail_send filter.
Queue #
MovieMaster\Queue\Jobs (or $plugin->jobs()):
| Method | What for |
|---|---|
push(string $type, array $payload = [], int $delaySeconds = 0, ?int $priority = null): int | Queues a job. Higher priority = sooner. |
pushUnique(string $type, array $payload = [], int $delaySeconds = 0, ?int $priority = null): ?int | Same, unless one with the same type and payload is already pending (null). |
pending(): int, pendingOf(array $types): int, counts(): array | How many are waiting. |
failed(int $limit = 50): array, retry(int $id): bool, delete(int $id) | Managing failed ones. |
Console: Io #
Received by a command's run(array $args, Io $io):
| Method | What for |
|---|---|
line(string $s = ''), info(), success(), warn(), error(), title() | Write (with color if the terminal supports it; error goes to stderr). |
ask(string $question, ?string $default = null): string | Ask a question. |
secret(string $question): string | Ask without showing what's typed. |
confirm(string $question, bool $default = false): bool | Yes or no. |
table(array $headers, array $rows) | Table. |
Logging (logger()) #
debug, info, notice, warning, error, and critical take (string $message, array $context = []); exception(Throwable $e) logs the exception with its trace. Everything goes to content/logs/app.log.
try {
$api->sync();
} catch (\Throwable $e) {
logger()->exception($e, ['plugin' => 'my-plugin']);
}