Next, I want to demonstrate the power of event system in the stancl/tenancy package. We have seen an example earlier in this course when creating a database and migrating tables when a tenant is created. You can listen to an event and have a lot of classes executed on that event.
In the TenantServiceProvider
, we have already seen a job pipeline when a tenant is being created.
app/Providers/TenantServiceProvider.php:
class TenancyServiceProvider extends ServiceProvider{ // By default, no namespace is used to support the callable array syntax. public static string $controllerNamespace = ''; public function events() { return [ // Tenant events Events\CreatingTenant::class => [], Events\TenantCreated::class => [ JobPipeline::make([ Jobs\CreateDatabase::class, Jobs\MigrateDatabase::class, // Jobs\SeedDatabase::class, // Your own jobs to prepare the tenant. // Provision API keys, create S3 buckets, anything you want! ])->send(function (Events\TenantCreated $event) { return $event->tenant; })->shouldBeQueued(false), // `false` by default, but you probably want to make this `true` for production. ], Events\SavingTenant::class => [], Events\TenantSaved::class => [], Events\UpdatingTenant::class => [], Events\TenantUpdated::class => [], Events\DeletingTenant::class => [], Events\TenantDeleted::class => [ JobPipeline::make([ Jobs\DeleteDatabase::class, ])->send(function (Events\TenantDeleted $event) { return $event->tenant; })->shouldBeQueued(false), // `false` by default, but you probably want to make this `true` for production. ], // ... ]; } // ...}
Now, let's try to delete the tenant and see what happens. We have an event, TenantDeleted
, and then...