Digging Deeper

Events and pipelines

Hook side effects (mail, metrics, search indexes) onto tenancy lifecycle without putting that logic inside controllers. Register listeners on the application with laravel.Listen, then let the package dispatch events when tenants and domains change or when a request enters/leaves a tenant context.

Provision and teardown stay on an explicit pipeline (CreatePipeline / DeletePipeline) so create/migrate/delete remain ordered and testable; use events for reactions, pipelines for required steps.

Register listeners

import (
    laravel "go.laravel.com"

    "github.com/martinshaw/laravel-go-tenancy/events"
)

laravel.Options{
    Listeners: []laravel.Listener{
        laravel.Listen(func(ctx context.Context, e events.TenantCreated) error {
            // e.Tenant is fully provisioned when AutoProvision ran
            return notifyOps(ctx, "tenant created", e.Tenant.ID)
        }),
        laravel.Listen(func(ctx context.Context, e events.DomainCreated) error {
            // e.Domain.Domain is the stored hostname (Herd-rewritten when active)
            return indexHostname(ctx, e.Domain.Domain, e.Domain.TenantID)
        }),
        laravel.Listen(func(ctx context.Context, e events.TenancyInitialized) error {
            return metrics.Inc(ctx, "tenancy.initialized", e.Tenant.ID)
        }),
        laravel.Listen(func(ctx context.Context, e events.TenantDeleted) error {
            return purgeSearchIndex(ctx, e.Tenant.ID)
        }),
    },
}

laravel.Listen defers until the outermost DB transaction commits when you dispatch inside a transaction. Use laravel.ListenAtDispatch if the listener must run inside the same transaction.

Events the package dispatches

Event When
events.TenantCreated After CreateTenant (and after auto-provision when enabled)
events.TenantDeleted After DeleteTenant finishes teardown, row delete, and Herd unlink
events.DomainCreated After a domains row is inserted (CreateDomain)
events.DomainDeleted After a domains row is removed (DeleteDomain)
events.TenancyInitialized After bootstrappers complete in Initialize
events.TenancyEnded After End reverts bootstrappers

Pipelines

Replace default DB create/migrate/delete steps when you need custom provisioning:

tenancy.New(func(cfg *tenancy.Config) {
    cfg.CreatePipeline = []tenancy.Job{
        // your jobs...
    }
})

Jobs implement:

type Job interface {
    Name() string
    Handle(ctx context.Context, tenant Tenant) error
}