Mainstay GitHub
All docs

Writing a plugin

A package's types, blocks, field types, admin screens, listeners and AI providers, on one class.

A plugin is a class extending Mainstay\Plugin. Only the plugins config/mainstay.php names load: installing a package switches nothing on, and nothing is switched on from the admin.

'plugins' => [Acme\Seo\Seo::class],

With routes cached, run route:cache again after changing the list.

The class

src/Seo.php
namespace Acme\Seo;

use Mainstay\Content\Icon;
use Mainstay\Events\Published;
use Mainstay\Plugin;

#[Icon('star')]
class Seo extends Plugin
{
    public static function handle(): string
    {
        return 'seo';
    }

    public function types(): array
    {
        return [SeoRedirect::class, SeoSettings::class];
    }

    public function views(): ?string
    {
        return __DIR__.'/../resources/views';
    }

    public function routes(): ?string
    {
        return __DIR__.'/../routes/admin.php';
    }

    public function listeners(): array
    {
        return [Published::class => [PurgeCache::class]];
    }
}

The handle

The handle names everything the plugin takes: its views are seo::, its screens are under /admin/seo, and its capability is use_seo. A handle that one of the admin's screens, a view namespace, a type or another plugin already has is refused as Mainstay boots.

Types, blocks and field types

Its types register as yours do. A block draws from the plugin's views by naming the handle, protected ?string $viewNamespace = 'seo';, and is then drawn by seo::blocks. and its own handle; a field type names it as a protected string, drawn by seo::components.fields. and its kebab-cased name. One handle names one block across a site, so give a plugin's blocks names of their own, SeoFaq rather than Faq. A site overrides any of the views at resources/views/vendor/seo.

Admin screens

The routes file is loaded inside the admin, behind its sign-in and CSRF check, and answered only to someone holding use_seo, which the roles grid lists under Plugins. The route named index is the plugin's item in the sidebar, drawn with its #[Icon]. A screen's view is drawn in <x-mainstay::admin>, and its forms carry @csrf:

Route::get('/', [RedirectController::class, 'index'])->name('index');

Listeners

listeners() maps Mainstay's events, Saved, Published, Deleted and Restored, to listener classes. They are heard once the write commits. A listener that throws in the request does so after the content is saved, so make one that can fail a queued listener.

AI providers

providers() adds providers to the Connectors screen: see AI connectors.

A plugin runs as your application does, with its access. Mainstay stops what a plugin declares from taking another's name, not what its code does, so install one as you would any dependency.