Saltar al contenido
MovieMaster

Desarrolladores: plugins y themes

PHP API reference

17 min de lectura 11 apartados

En esta página

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 #

FunctionReturns
app(?string $abstract = null): mixedWith no arguments, the application ($app->container, $app->hooks()). With a class, the service resolved by the container.
config(string $key, mixed $default = null): mixedConfig from config.php, dot notation (config('app.url')).
setting(string $key, mixed $default = null): mixedA saved setting (setting('general.site_name')).
db(): ConnectionThe database connection.
cache(): CacheManagerThe object cache (files, APCu, or Redis).
logger(): LoggerThe log at content/logs/app.log.
request(): RequestThe current request.
hooks(): HookManagerThe hook manager. See the hooks reference.
media(): MediaRepositoryThe media library.
mm_version(): stringCore version (0.9.54).
now(): stringUTC date and time in Y-m-d H:i:s format, the one database columns use.

Text and data #

FunctionWhat it does
e(mixed $value): stringEscapes for HTML. null → '', true → '1', arrays and objects → escaped JSON.
str_limit(string $s, int $max = 160, string $end = '…'): stringTrims text without splitting multibyte characters.
array_get(array $arr, string $key, mixed $default = null): mixedReads an array with dot notation ('a.b.c').
compact_number(int $n): string1500 → 1.5K, 2000000 → 2M.
minify_css(string $css): stringMinifies CSS (used by inline_css and your inline styles).

Languages and URLs #

FunctionWhat it does
__(string $key, array $replace = [], ?string $lang = null): stringTranslates. 'domain::key' for a plugin's or theme's strings.
_n(string $key, int $count, array $replace = [], ?string $lang = null): stringTranslates with a plural ('one|many'); fills in :count.
current_lang(): stringThe request's language (es, en).
url(string $path = '/', bool $absolute = false): stringURL 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): stringSame, but choosing the language.
route(string $name, array $params = [], ?string $lang = null, bool $absolute = false): stringURL of a named route. Extra parameters go into the query string.
site_url(string $path = '/'): stringAbsolute URL with the site's domain, without translating words or adding a language (files, webhooks).

Views, forms, and media #

FunctionWhat it does
view(string $name, array $data = []): stringRenders a template ('partials/card', 'my-plugin::box', 'admin::layout').
csrf_token(): string / csrf_field(): stringThe admin panel's token and its <input type="hidden" name="_token">.
old(string $key, mixed $default = null): mixedValue submitted in the previous form (after a validation error).
media_url(int $id, string $size = 'thumb', string $format = 'jpg'): stringURL 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'): stringBackground 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 #

FunctionWhat it does
plugin_setting(string $slug, string $key, mixed $default = null): mixedA plugin's setting (secret ones arrive decrypted).
plugin_active(string $slug): boolIs that plugin active?
plugin_providers(string $contract): arraySlugs of the active plugins that declare that contract in provides.
active_theme(): ?arrayThe 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 #

MethodReturns
method(), isGet(), isPost(), isMethod('PUT')HTTP method (isGet() includes HEAD).
path(): stringNormalized 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(): arrayAll 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): arrayField as an array.
json(): mixedDecoded JSON body.
rawBody(): stringRaw 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(): stringVisitor'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 #

php
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().

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

MethodWhat for
table(string $table): QueryStarts a query. The name goes without the prefix.
select(string $sql, array $bindings = []): arrayRaw SQL: all rows.
selectOne(string $sql, array $bindings = []): ?arrayRaw SQL: one row.
scalar(string $sql, array $bindings = []): mixedRaw SQL: a single value.
execute(string $sql, array $bindings = []): intRaw SQL that modifies data: rows affected.
transaction(callable $fn): mixedRuns $fn in a transaction; rolls back if it throws.
prefixed(string $table): stringThe real table name (votes → mm_votes), for raw SQL.
quoteId(string $id): stringQuotes an identifier for the engine in use.
driver(), isMysql(), isSqlite()The engine in use.
lastInsertId(): intLast inserted id.

Query #

Fluent builder. All filter methods return the query itself.

GroupMethods
Selectionselect(...$cols), addSelect(...), distinct(), from($table, $alias), Query::raw($sql, $bindings)
Conditionswhere($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)
Joinsjoin($table, $first, $op, $second), leftJoin(...), joinRaw($sql)
Order and limitsorderBy($col, 'ASC'|'DESC'), orderByRaw($sql), latest($col = 'created_at'), inRandomOrder(), groupBy(...), having($sql, $bindings), limit($n), offset($n), forPage($page, $perPage)
Readingget(): 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
Writinginsert(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()
DebuggingtoSql(): array (SQL and bindings)
php
$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.

SchemaBlueprint (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 #

MethodWhat for
get(string $key, mixed $default = null): mixedRead. Same as setting().
set(string $key, mixed $value, bool $autoload = true): voidSave one. autoload = false for large values not needed on every request.
setMany(array $values, bool $autoload = true): voidSave several.
delete(string $key) / deleteGroup(string $prefix)Delete one, or all starting with a prefix.
group(string $prefix): arrayAll of the settings under a prefix ('plugin.my-plugin.').

Object cache (cache()) #

php
$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 methodWhat 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(): boolIs 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) #

MethodWhat for
find(int $id, ?string $lang = null, bool $withRelations = true, int $castLimit = 0): ?arrayA title with genres, cast, etc.
findBySlug(string $type, string $slug, ?string $lang = null, bool $publishedOnly = true): ?arrayBy slug (movie/series).
findByTmdb(string $type, int $tmdbId): ?intLocal id of a TMDB title.
list(array $filters, int $limit, ?string $lang = null, bool $withRelations = false): arrayA list.
paginate(array $filters, int $page, int $perPage, ?string $lang = null, bool $withRelations = false): arrayA page: items, total, page, per_page, last_page.
query(array $filters, ?string $lang = null): QueryThe unexecuted query, for you to refine.
published(?string $type = null): QueryPublished and visible only.
related(array $title, int $limit, ?string $lang = null): arrayRelated titles.
hero(int $limit, ?string $lang = null): arrayThe ones in the home page carousel.
counts(): array, years(?string $type = null): arrayTotals, and years with titles.
save(array $data, array $translations, ?array $termIds, ?array $credits, ?int $id = null): intCreate or edit.
delete(int $id): void, setStatus(array $ids, string $status): voidDelete or change status (published, draft).
TitleRepository::isPublic(array $t): boolCan a visitor see it?

Filters for list, paginate, and query:

FilterValue
typemovie or series
ordernewest (default), popular, views, trending, rating, year, release, updated, random
term_idId of a genre or tag
person_idId of a cast or crew person
yearYear
searchText to search for
featured1 = featured only
with_backdrop1 = only ones with a backdrop image
excludeArray of ids to exclude
statusStatus (defaults to published only)
no_sources1 = 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 #

MethodWhat for
seasons(int $titleId, ?string $lang = null): array / season($titleId, $number, $lang)Seasons.
episodes(int $titleId, int $seasonNumber, ?string $lang = null): arrayA 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): arrayPrevious and next.
latest(int $limit, ?string $lang = null): arrayLatest 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 #

RepositoryReadingWriting
PersonRepositoryfind, findBySlug, findMany(array $ids), paginate($page, $perPage, $lang, $search, $order), search($q, $limit), creditsForTitles(array $titleIds), findByTmdbsave, findOrCreateByName, delete, recount
TermRepositoryfind, 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
PageRepositoryfind, 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) #

MethodWhat for
forTitle(int $titleId, ?int $episodeId = null, bool $activeOnly = true): arraySources for a movie or episode.
SourceRepository::grouped(array $sources): arrayGrouped 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): arrayReplace 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()) #

MethodWhat for
find(int $id): ?array, findMany(array $ids)Media rows.
store(array|string $file, string $preset = 'thumb', ?int $userId = null, ?string $alt = null): arrayStores 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): arrayDownloads and processes a remote image.
url(int|array $media, string|int $size = 'thumb', string $format = 'jpg'): stringURL 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 #

ClassUseful methods
Seo\SeoBuildererror(int $status): PageSeo (empty base for your pages), wrap(string $title): string (applies the site's title pattern).
Seo\PageSeoPublic properties: title, description, canonical, robots, type, image, imageWidth, imageHeight, alternates, prev, next, videoUrl, videoDuration, publishedTime, graph.
Seo\MetaStoreget(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\IndexNowenabled(), queue(array $paths, bool $urgent = false): notifies Bing, Yandex, and others of new or changed URLs (the repositories already do this).
Content\Redirectsadd(string $from, string $to, int $status = 301), gone(string $path) (410), find(string $path), delete(int $id), all().
Content\UrlKeyssetSeason(...), setEpisode(...): change a season's or episode's URL word, creating the 301s.
I18n\Langcurrent(), 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 #

php
$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
RoleCapabilities
adminAll of them (*).
editoraccess_admin, manage_content, publish_content, edit_others_content, delete_content, upload_media, manage_terms, manage_people, manage_pages, view_stats
authoraccess_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:

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

ClassMethods
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\RateLimitertooManyAttempts(string $key): bool, hit(string $key): int, availableIn(string $key): int (seconds), clear(string $key). Defaults to 5 attempts every 15 minutes.
php
$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.

php
$encrypted = Secret::encrypt($token);
$token = Secret::decrypt($encrypted);
Secret::isSet($encrypted);   // is there a saved value?

Email #

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

MethodWhat for
push(string $type, array $payload = [], int $delaySeconds = 0, ?int $priority = null): intQueues a job. Higher priority = sooner.
pushUnique(string $type, array $payload = [], int $delaySeconds = 0, ?int $priority = null): ?intSame, unless one with the same type and payload is already pending (null).
pending(): int, pendingOf(array $types): int, counts(): arrayHow 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):

MethodWhat 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): stringAsk a question.
secret(string $question): stringAsk without showing what's typed.
confirm(string $question, bool $default = false): boolYes 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.

php
try {
    $api->sync();
} catch (\Throwable $e) {
    logger()->exception($e, ['plugin' => 'my-plugin']);
}

¿Te quedó alguna duda?

Escríbenos y te ayudamos con tu caso.

Hablar con nosotros
¿Hablamos?