Plugins and extensions

suggest change

A plugin system lets other people (or other teams, or future you) add features to an application without editing its core code. WordPress plugins, Composer plugins, PHPUnit extensions, Symfony bundles and Laravel packages are all variations of the same idea:

  1. the application defines a contract: an interface, a set of named hooks, or event classes
  2. it discovers plugins: from a directory, from a config file, or from installed Composer packages
  3. it registers each plugin and calls it at well-defined extension points

This article builds each of those pieces in plain PHP 8.5, from a minimal registry to Composer-based discovery with dependency checks. It's about application-level plugins written in PHP. Native extensions written in C are a different topic, see Compile PHP Extensions.

A plugin contract and a registry

Start with an interface. It's the only thing the core and the plugins both depend on:

<?php
declare(strict_types=1);

interface TextFilterPlugin
{
    public function name(): string;
    public function apply(string $text): string;
}

final class UppercasePlugin implements TextFilterPlugin
{
    public function name(): string { return 'uppercase'; }
    public function apply(string $text): string { return strtoupper($text); }
}

final class TrimPlugin implements TextFilterPlugin
{
    public function name(): string { return 'trim'; }
    public function apply(string $text): string { return trim($text); }
}

final class PluginRegistry
{
    /** @var array<string, TextFilterPlugin> */
    private array $plugins = [];

    public function register(TextFilterPlugin $plugin): void
    {
        $name = $plugin->name();
        if (isset($this->plugins[$name])) {
            throw new LogicException("Plugin '$name' is already registered");
        }
        $this->plugins[$name] = $plugin;
    }

    public function get(string $name): TextFilterPlugin
    {
        return $this->plugins[$name]
            ?? throw new OutOfBoundsException("Unknown plugin '$name'");
    }

    /** @return list<string> */
    public function names(): array
    {
        return array_keys($this->plugins);
    }
}

$registry = new PluginRegistry();
$registry->register(new TrimPlugin());
$registry->register(new UppercasePlugin());

$text = "  hello plugins  ";
foreach ($registry->names() as $name) {
    $text = $registry->get($name)->apply($text);
}
var_dump($text);

try {
    $registry->get('rot13');
} catch (OutOfBoundsException $e) {
    echo $e->getMessage(), "\n";
}

Output:

string(13) "HELLO PLUGINS"
Unknown plugin 'rot13'

The core only knows about TextFilterPlugin. Anyone can write a new class that implements it and the core uses it without changes. The registry rejects duplicate names: when two plugins silently overwrite each other, the result is a bug that's very hard to track down.

Loading plugins from a directory

Registering plugins by hand still means editing the core. The classic solution is a plugins/ directory: drop a file in and it's picked up.

A convenient convention is that each plugin file returns its plugin object. require returns whatever the included file returns, and an anonymous class means the plugin doesn't even need a class name that could clash with another plugin:

app/
├── contracts.php
├── load.php
└── plugins/
    ├── 10-trim.php
    ├── 20-shout.php
    └── 30-broken.php

contracts.php:

<?php
declare(strict_types=1);

interface TextFilterPlugin
{
    public function name(): string;
    public function apply(string $text): string;
}

plugins/10-trim.php:

<?php
return new class implements TextFilterPlugin {
    public function name(): string { return 'trim'; }
    public function apply(string $text): string { return trim($text); }
};

plugins/20-shout.php:

<?php
return new class implements TextFilterPlugin {
    public function name(): string { return 'shout'; }
    public function apply(string $text): string { return strtoupper($text) . '!'; }
};

plugins/30-broken.php:

<?php
// forgot to return a plugin object
function helper() {}

load.php:

<?php
declare(strict_types=1);
require __DIR__ . '/contracts.php';

/** @return list<TextFilterPlugin> */
function loadPlugins(string $dir): array
{
    $files = glob($dir . '/*.php');
    sort($files); // load order = file name order

    // static closure: the plugin file can't see $this or our local variables
    $include = static fn(string $file): mixed => require $file;

    $plugins = [];
    foreach ($files as $file) {
        $plugin = $include($file);
        if (!$plugin instanceof TextFilterPlugin) {
            fprintf(STDERR, "skipping %s: does not return a TextFilterPlugin\n", basename($file));
            continue;
        }
        $plugins[] = $plugin;
    }
    return $plugins;
}

$plugins = loadPlugins(__DIR__ . '/plugins');
$text = "   it works   ";
foreach ($plugins as $plugin) {
    echo "applying ", $plugin->name(), "\n";
    $text = $plugin->apply($text);
}
var_dump($text);

Output:

skipping 30-broken.php: does not return a TextFilterPlugin
applying trim
applying shout
string(9) "IT WORKS!"

Notes:

Hooks: actions and filters

An interface with one method works when plugins do one kind of thing. Real applications need many extension points: "change the page title", "do something after a user registers", "add a menu item". WordPress popularized a simple and flexible design for this: named hooks with two flavors:

Both have a priority so plugins can control the order:

<?php
declare(strict_types=1);

final class Hooks
{
    /** @var array<string, array<int, list<callable>>> */
    private array $filters = [];
    /** @var array<string, array<int, list<callable>>> */
    private array $actions = [];

    public function addFilter(string $hook, callable $fn, int $priority = 10): void
    {
        $this->filters[$hook][$priority][] = $fn;
    }

    public function addAction(string $hook, callable $fn, int $priority = 10): void
    {
        $this->actions[$hook][$priority][] = $fn;
    }

    /** Pass $value through every filter; each returns the new value. */
    public function applyFilters(string $hook, mixed $value, mixed ...$args): mixed
    {
        foreach ($this->sorted($this->filters[$hook] ?? []) as $fn) {
            $value = $fn($value, ...$args);
        }
        return $value;
    }

    /** Notify every action; return values are ignored. */
    public function doAction(string $hook, mixed ...$args): void
    {
        foreach ($this->sorted($this->actions[$hook] ?? []) as $fn) {
            $fn(...$args);
        }
    }

    /** @return iterable<callable> lower priority runs first, ties keep insertion order */
    private function sorted(array $byPriority): iterable
    {
        ksort($byPriority);
        foreach ($byPriority as $callbacks) {
            yield from $callbacks;
        }
    }
}

$hooks = new Hooks();

// "core" application code exposes extension points
function renderPost(Hooks $hooks, array $post): string
{
    $title = $hooks->applyFilters('post.title', $post['title'], $post);
    $body  = $hooks->applyFilters('post.body', $post['body'], $post);
    $html  = "<h1>$title</h1>\n<p>$body</p>";
    $hooks->doAction('post.rendered', $post['id'], strlen($html));
    return $html;
}

// plugin A: escape HTML first (priority 1)
$hooks->addFilter('post.title', fn(string $t) => htmlspecialchars($t), 1);
$hooks->addFilter('post.body', fn(string $b) => htmlspecialchars($b), 1);

// plugin B: mark drafts
$hooks->addFilter('post.title', fn(string $t, array $post) => $post['draft'] ? "[DRAFT] $t" : $t);

// plugin C: turn :) into an emoji, after escaping
$hooks->addFilter('post.body', fn(string $b) => str_replace(':)', '🙂', $b), 20);

// plugin D: log
$hooks->addAction('post.rendered', function (int $id, int $bytes): void {
    echo "[log] post $id rendered, $bytes bytes\n";
});

echo renderPost($hooks, [
    'id' => 7,
    'title' => 'Tips & <tricks>',
    'body' => 'Plugins are fun :)',
    'draft' => true,
]), "\n";

Output:

[log] post 7 rendered, 70 bytes
<h1>[DRAFT] Tips &amp; &lt;tricks&gt;</h1>
<p>Plugins are fun 🙂</p>

The escaping filter runs first because it has priority 1, the emoji filter runs last with priority 20, and the draft filter in between uses the default 10. Extra arguments passed to applyFilters() (here the whole $post) give filters context without making it part of the value being filtered.

String hook names are easy to add and easy to document, but nothing checks them: a typo in 'post.titel' registers a filter that never runs, and the arguments a callback gets are only documented by convention. The next two sections fix that with typed events.

Typed events with PSR-14

PSR-14 is the standard event dispatcher interface used by Symfony, Laravel and many libraries. Instead of string names, each extension point is an event class, and listeners are type-checked callables that receive the event object.

Install the interfaces (they're just interfaces, about 3 files):

$ composer require psr/event-dispatcher

A listener provider maps events to listeners, and the dispatcher calls them. A stoppable event lets a listener veto the action and prevents the remaining listeners from running:

<?php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';

use Psr\EventDispatcher\EventDispatcherInterface;
use Psr\EventDispatcher\ListenerProviderInterface;
use Psr\EventDispatcher\StoppableEventInterface;

// --- events: plain objects owned by the application ---

final class UserRegistered
{
    public function __construct(public readonly string $email) {}
}

final class CheckoutStarted implements StoppableEventInterface
{
    private ?string $blockedBy = null;

    public function __construct(public readonly float $total) {}

    public function block(string $reason): void { $this->blockedBy = $reason; }
    public function blockedBy(): ?string { return $this->blockedBy; }
    public function isPropagationStopped(): bool { return $this->blockedBy !== null; }
}

// --- the dispatcher machinery ---

final class ListenerProvider implements ListenerProviderInterface
{
    /** @var array<class-string, list<callable>> */
    private array $listeners = [];

    public function listen(string $eventClass, callable $listener): void
    {
        $this->listeners[$eventClass][] = $listener;
    }

    public function getListenersForEvent(object $event): iterable
    {
        foreach ($this->listeners as $class => $listeners) {
            if ($event instanceof $class) { // also matches parent classes and interfaces
                yield from $listeners;
            }
        }
    }
}

final class Dispatcher implements EventDispatcherInterface
{
    public function __construct(private ListenerProviderInterface $provider) {}

    public function dispatch(object $event): object
    {
        foreach ($this->provider->getListenersForEvent($event) as $listener) {
            if ($event instanceof StoppableEventInterface && $event->isPropagationStopped()) {
                break;
            }
            $listener($event);
        }
        return $event;
    }
}

// --- plugins register listeners ---

$provider = new ListenerProvider();

$provider->listen(UserRegistered::class, function (UserRegistered $e): void {
    echo "newsletter plugin: subscribing {$e->email}\n";
});
$provider->listen(CheckoutStarted::class, function (CheckoutStarted $e): void {
    if ($e->total > 1000) {
        $e->block('fraud check: order too large');
    }
});
$provider->listen(CheckoutStarted::class, function (CheckoutStarted $e): void {
    echo "analytics plugin: checkout of {$e->total}\n";
});

// --- core code dispatches ---

$dispatcher = new Dispatcher($provider);
$dispatcher->dispatch(new UserRegistered('ann@example.com'));

foreach ([49.90, 2500.00] as $total) {
    $event = $dispatcher->dispatch(new CheckoutStarted($total));
    echo $event->blockedBy() === null
        ? "checkout $total: ok\n"
        : "checkout $total: blocked ({$event->blockedBy()})\n";
}

Output:

newsletter plugin: subscribing ann@example.com
analytics plugin: checkout of 49.9
checkout 49.9: ok
checkout 2500: blocked (fraud check: order too large)

For the second checkout the fraud-check listener stopped propagation, so the analytics listener never ran, and the core code read the decision back from the returned event object. The instanceof $class test in the provider means a listener can subscribe to an interface or a base class and receive every event that implements it.

In a real project you'd usually use an existing implementation, such as symfony/event-dispatcher or league/event, instead of writing your own; the point of PSR-14 is that plugins written against the interfaces work with any of them.

Registering listeners with attributes

With many listeners, wiring each one by hand with listen() gets tedious. Attributes let a plugin class declare its listeners next to the code, and the core finds them with reflection. The event type comes from the method's parameter type, so it can't get out of sync:

<?php
declare(strict_types=1);

#[Attribute(Attribute::TARGET_METHOD)]
final class AsListener
{
    public function __construct(public int $priority = 0) {}
}

#[Attribute(Attribute::TARGET_CLASS)]
final class Plugin
{
    public function __construct(public string $name, public string $version) {}
}

final class OrderPlaced
{
    public function __construct(public readonly int $orderId) {}
}

final class OrderShipped
{
    public function __construct(public readonly int $orderId) {}
}

#[Plugin(name: 'mailer', version: '1.2.0')]
final class MailerPlugin
{
    #[AsListener]
    public function onPlaced(OrderPlaced $e): void
    {
        echo "mailer: confirmation for order {$e->orderId}\n";
    }

    #[AsListener]
    public function onShipped(OrderShipped $e): void
    {
        echo "mailer: tracking email for order {$e->orderId}\n";
    }

    public function notAListener(OrderPlaced $e): void {}
}

#[Plugin(name: 'stock', version: '0.9.1')]
final class StockPlugin
{
    #[AsListener(priority: 100)] // must run before emails go out
    public function reserve(OrderPlaced $e): void
    {
        echo "stock: reserving items for order {$e->orderId}\n";
    }
}

final class EventBus
{
    /** @var array<class-string, list<array{int, callable}>> */
    private array $listeners = [];

    public function registerPlugin(object $plugin): void
    {
        $class = new ReflectionObject($plugin);
        $meta = $class->getAttributes(Plugin::class)[0]
            ?? throw new InvalidArgumentException($class->getName() . ' has no #[Plugin] attribute');
        $info = $meta->newInstance();
        echo "loaded {$info->name} {$info->version}\n";

        foreach ($class->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
            $attr = $method->getAttributes(AsListener::class)[0] ?? null;
            if ($attr === null) {
                continue;
            }
            $type = ($method->getParameters()[0] ?? null)?->getType();
            if (!$type instanceof ReflectionNamedType || $type->isBuiltin()) {
                throw new LogicException("{$class->getName()}::{$method->getName()} needs an event class parameter");
            }
            $this->listeners[$type->getName()][] = [
                $attr->newInstance()->priority,
                $method->getClosure($plugin),
            ];
        }
    }

    public function dispatch(object $event): void
    {
        $listeners = $this->listeners[$event::class] ?? [];
        // higher priority first; usort is stable since PHP 8.0
        usort($listeners, fn(array $a, array $b) => $b[0] <=> $a[0]);
        foreach ($listeners as [, $listener]) {
            $listener($event);
        }
    }
}

$bus = new EventBus();
$bus->registerPlugin(new MailerPlugin());
$bus->registerPlugin(new StockPlugin());

$bus->dispatch(new OrderPlaced(42));
$bus->dispatch(new OrderShipped(42));

Output:

loaded mailer 1.2.0
loaded stock 0.9.1
stock: reserving items for order 42
mailer: confirmation for order 42
mailer: tracking email for order 42

notAListener() has a matching parameter type but no #[AsListener] attribute, so it's ignored. ReflectionMethod::getClosure($plugin) turns a method into a closure bound to the plugin instance, which is what gets stored. This is the same technique Symfony uses for #[AsEventListener]; frameworks run the reflection scan once at build time and cache the result, so it costs nothing per request.

Discovering plugins installed with Composer

For plugins distributed as packages, Composer already solves installation, versioning and autoloading. The application only needs to find which installed packages are plugins. A common convention is:

The project layout:

cp/
├── app/
│   ├── composer.json
│   └── main.php
└── plugins/
    ├── contracts/          (acme/plugin-contracts)
    │   ├── composer.json
    │   └── src/
    │       ├── Application.php
    │       └── PluginInterface.php
    └── hello/              (acme/hello-plugin)
        ├── composer.json
        └── src/HelloPlugin.php

The shared contract package, plugins/contracts/composer.json:

{
    "name": "acme/plugin-contracts",
    "autoload": { "psr-4": { "Acme\\Plugin\\": "src/" } }
}

plugins/contracts/src/PluginInterface.php:

<?php
namespace Acme\Plugin;

interface PluginInterface
{
    public function boot(Application $app): void;
}

plugins/contracts/src/Application.php is the API the core exposes to plugins:

<?php
namespace Acme\Plugin;

final class Application
{
    /** @var array<string, callable> */
    private array $commands = [];

    public function addCommand(string $name, callable $handler): void
    {
        $this->commands[$name] = $handler;
    }

    public function run(string $name, string ...$args): void
    {
        ($this->commands[$name] ?? fn() => print("unknown command $name\n"))(...$args);
    }

    /** @return list<string> */
    public function commandNames(): array
    {
        return array_keys($this->commands);
    }
}

The plugin package, plugins/hello/composer.json:

{
    "name": "acme/hello-plugin",
    "version": "1.0.0",
    "type": "acme-plugin",
    "require": { "acme/plugin-contracts": "*" },
    "autoload": { "psr-4": { "Acme\\Hello\\": "src/" } },
    "extra": {
        "acme-plugin": { "class": "Acme\\Hello\\HelloPlugin" }
    }
}

plugins/hello/src/HelloPlugin.php:

<?php
namespace Acme\Hello;

use Acme\Plugin\Application;
use Acme\Plugin\PluginInterface;

final class HelloPlugin implements PluginInterface
{
    public function boot(Application $app): void
    {
        $app->addCommand('hello', fn(string $who = 'world') => print("Hello, $who!\n"));
    }
}

The application, app/composer.json. A path repository is a convenient way to develop plugins locally; published plugins would come from Packagist or a private repository instead:

{
    "name": "acme/app",
    "repositories": [
        { "type": "path", "url": "../plugins/*" }
    ],
    "require": {
        "acme/plugin-contracts": "@dev",
        "acme/hello-plugin": "@dev"
    }
}

app/main.php uses Composer\InstalledVersions, a class that Composer generates in every project, to list packages of the plugin type:

<?php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';

use Acme\Plugin\Application;
use Acme\Plugin\PluginInterface;
use Composer\InstalledVersions;

$app = new Application();

foreach (InstalledVersions::getInstalledPackagesByType('acme-plugin') as $package) {
    $path = InstalledVersions::getInstallPath($package);
    $manifest = json_decode(file_get_contents("$path/composer.json"), true, flags: JSON_THROW_ON_ERROR);
    $class = $manifest['extra']['acme-plugin']['class'] ?? null;

    if ($class === null || !is_a($class, PluginInterface::class, true)) {
        fprintf(STDERR, "%s: missing or invalid extra.acme-plugin.class\n", $package);
        continue;
    }
    $version = InstalledVersions::getPrettyVersion($package);
    echo "booting $package ($version) via $class\n";
    (new $class())->boot($app);
}

echo "commands: ", implode(', ', $app->commandNames()), "\n";
$app->run('hello');
$app->run('hello', 'plugins');

Install and run:

$ composer install
...
  - Installing acme/plugin-contracts (dev-main 7a1a6de): Junctioning from ../plugins/contracts
  - Installing acme/hello-plugin (1.0.0): Junctioning from ../plugins/hello
Generating autoload files
$ php main.php

booting acme/hello-plugin (1.0.0) via Acme\Hello\HelloPlugin commands: hello Hello, world! Hello, plugins!

Installing a new plugin is now composer require vendor/some-plugin and nothing else: Composer downloads it, registers its autoloader, and the next run of main.php boots it. Note that is_a($class, PluginInterface::class, true) triggers autoloading of the class, so a typo in extra is reported instead of causing a fatal error later. See Autoloading with Composer for how the generated autoloader works.

Composer itself has a separate, more powerful mechanism: packages of type composer-plugin that hook into Composer's own install process (that's how custom installers that put WordPress plugins into wp-content/plugins/ work). You don't need that for application plugins; reading the installed packages at runtime, as above, is enough.

Versions, dependencies and failure isolation

Once there are more than a handful of plugins, the loader has to deal with:

One broken plugin should be skipped, with a clear message, instead of taking the whole application down:

<?php
declare(strict_types=1);

const APP_API_VERSION = '2.3.0';

final class PluginInfo
{
    /** @param array<string, string> $requires plugin name => minimum version */
    public function __construct(
        public readonly string $name,
        public readonly string $version,
        public readonly string $minApi,
        public readonly array $requires,
        public readonly Closure $boot,
    ) {}
}

final class PluginLoader
{
    /** @var array<string, PluginInfo> */
    private array $available = [];
    /** @var array<string, true> */
    private array $booted = [];
    /** @var array<string, string> name => reason */
    private array $failed = [];

    public function add(PluginInfo $p): void
    {
        $this->available[$p->name] = $p;
    }

    public function bootAll(): void
    {
        foreach (array_keys($this->available) as $name) {
            $this->boot($name, []);
        }
    }

    /** @param list<string> $stack names currently being booted, to detect cycles */
    private function boot(string $name, array $stack): bool
    {
        if (isset($this->booted[$name])) {
            return true;
        }
        if (isset($this->failed[$name])) {
            return false;
        }
        $p = $this->available[$name] ?? null;
        if ($p === null) {
            return $this->fail($name, 'not installed');
        }
        if (in_array($name, $stack, true)) {
            return $this->fail($name, 'circular dependency: ' . implode(' -> ', [...$stack, $name]));
        }
        if (version_compare(APP_API_VERSION, $p->minApi, '<')) {
            return $this->fail($name, "needs app API >= {$p->minApi}, have " . APP_API_VERSION);
        }
        foreach ($p->requires as $dep => $minVersion) {
            if (!$this->boot($dep, [...$stack, $name])) {
                return $this->fail($name, "dependency '$dep' unavailable");
            }
            $have = $this->available[$dep]->version;
            if (version_compare($have, $minVersion, '<')) {
                return $this->fail($name, "needs $dep >= $minVersion, have $have");
            }
        }
        try {
            ($p->boot)();
        } catch (Throwable $e) {
            return $this->fail($name, get_class($e) . ': ' . $e->getMessage());
        }
        $this->booted[$name] = true;
        echo "booted  $name {$p->version}\n";
        return true;
    }

    private function fail(string $name, string $reason): bool
    {
        if (isset($this->failed[$name])) {
            return false; // already reported (happens with cycles)
        }
        $this->failed[$name] = $reason;
        echo "skipped $name: $reason\n";
        return false;
    }
}

$noop = fn() => null;
$loader = new PluginLoader();
$loader->add(new PluginInfo('seo', '1.0.0', '2.0', ['core-ui' => '1.4'], $noop));
$loader->add(new PluginInfo('core-ui', '1.5.2', '2.0', [], $noop));
$loader->add(new PluginInfo('gallery', '3.1.0', '3.0', [], $noop));
$loader->add(new PluginInfo('lightbox', '0.2.0', '2.0', ['gallery' => '3.0'], $noop));
$loader->add(new PluginInfo('payments', '2.0.0', '2.1', [],
    fn() => throw new RuntimeException('API key not configured')));
$loader->add(new PluginInfo('invoices', '1.1.0', '2.1', ['payments' => '2.0'], $noop));
$loader->add(new PluginInfo('sitemap', '1.0.0', '2.0', ['seo' => '2.0'], $noop));
$loader->add(new PluginInfo('comments', '1.0.0', '2.0', ['antispam' => '1.0'], $noop));
$loader->bootAll();

Output:

booted  core-ui 1.5.2
booted  seo 1.0.0
skipped gallery: needs app API >= 3.0, have 2.3.0
skipped lightbox: dependency 'gallery' unavailable
skipped payments: RuntimeException: API key not configured
skipped invoices: dependency 'payments' unavailable
skipped sitemap: needs seo >= 2.0, have 1.0.0
skipped antispam: not installed
skipped comments: dependency 'antispam' unavailable

The loader boots dependencies recursively before the plugin that needs them, so core-ui is booted before seo even though seo was added first. version_compare() understands versions like 1.5.2, 2.0 and 1.0.0-beta1. A failure propagates to dependents (invoices needs payments), and the $stack parameter detects cycles:

$loader = new PluginLoader();
$loader->add(new PluginInfo('a', '1.0', '2.0', ['b' => '1.0'], $noop));
$loader->add(new PluginInfo('b', '1.0', '2.0', ['a' => '1.0'], $noop));
$loader->bootAll();

Output:

skipped a: circular dependency: a -> b -> a
skipped b: dependency 'a' unavailable

If plugins are Composer packages, you get most of this for free: declare plugin-to-plugin dependencies in require and the API version as a requirement on your contracts package ("acme/plugin-contracts": "^2.1"), and Composer refuses to install incompatible combinations.

What can and can't be caught

try/catch (Throwable) around plugin code catches exceptions and errors such as TypeError, and it even catches a syntax error in an included file, which is thrown as ParseError:

<?php
foreach (['typo.php'] as $f) {
    try {
        require __DIR__ . "/plugins/$f";
    } catch (ParseError $e) {
        printf("%s: %s: %s on line %d\n", $f, get_class($e), $e->getMessage(), $e->getLine());
    }
}
echo "application keeps running\n";

Output, with plugins/typo.php missing a ;:

typo.php: ParseError: syntax error, unexpected token "}", expecting ";" on line 3
application keeps running

Some failures are fatal and can't be caught, though. The most common one in plugin systems is two plugins declaring the same class name in the global namespace:

<?php
foreach (['a.php', 'b.php'] as $f) {
    try {
        require __DIR__ . "/plugins/$f";
    } catch (Throwable $e) {
        echo "caught: ", $e->getMessage(), "\n";
    }
}
echo "never printed\n";

Output, when both a.php and b.php declare class Helper {}:

Fatal error: Cannot redeclare class Helper (previously declared in ...\plugins\a.php:2) in ...\plugins\b.php on line 2
Stack trace:
#0 ...\t2.php(4): require()
#1 {main}

That's why plugins should put their code in their own namespace (Acme\Hello\...) or use anonymous classes. Running out of memory, exceeding max_execution_time and calling exit() also end the whole script no matter what you catch.

Security

PHP has no sandbox: a plugin runs with exactly the same permissions as the application. It can read the database password, write files and make network requests. Practical consequences:

If you need to run untrusted code, run it in a separate process or container, or use an embedded scripting language designed for sandboxing, rather than in-process PHP.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents