Skip to content

Lifecycle and Migrations

Lukman Nakib edited this page May 30, 2026 · 1 revision

Lifecycle & Migrations

Lifecycle

Core\Lifecycle owns activation, deactivation, and uninstall — one declarative place instead of scattered register_activation_hook calls. Extend it by listening to its events, not by adding your own hooks:

  • Activate: Migrator::run()do_action('wppm/lifecycle/seed_defaults')do_action('wppm/lifecycle/register_capabilities') → schedule cron from the wppm/lifecycle/cron_events filter → flush_rewrite_rules()do_action('wppm/activated').
  • Deactivate: unschedule cron → flush → do_action('wppm/deactivated').
  • Uninstall (uninstall.php): gated by apply_filters('wppm/uninstall_destructive', false) — data is preserved by default. If opted in: roll back migrations, delete wppm_* options, clear cron. Always do_action('wppm/uninstalled').
// Seed data at activation
add_action('wppm/lifecycle/seed_defaults', function () {
    if (empty(Book::all())) {
        Book::create(['title' => 'Sample']);
    }
});

// Contribute a cron event (the canonical cron seam — prefer this over the Cron helper)
add_filter('wppm/lifecycle/cron_events', function ($events) {
    $events[] = ['hook' => 'wppm/cron/prune_books', 'recurrence' => 'daily', 'timestamp' => null];
    return $events;
});
add_action('wppm/cron/prune_books', fn () => /* … */);

Migrations

Versioned, declarative schema changes. One file = one change, scanned and applied in filename order at activation, recorded in wp_options.wppm_migrations (idempotent across reactivations).

  • Migration files live in database/migrations/ (plugin root), named YYYY_MM_DD_HHMMSS_CreateXTable.php.
  • The Migrator + Migration base class live in app/Database/Migrations/.
// database/migrations/2026_06_01_120000_CreateBooksTable.php
final class CreateBooksTable extends Migration
{
    public function up(): void
    {
        global $wpdb;
        $table = $wpdb->prefix . 'wppm_books';
        $charset = $wpdb->get_charset_collate();
        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta("CREATE TABLE {$table} (
            id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
            title VARCHAR(191) NOT NULL,
            PRIMARY KEY (id)
        ) {$charset};");
    }

    public function down(): void
    {
        global $wpdb;
        $wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}wppm_books");
    }
}

Migrations are append-only. Never edit an applied migration — add a new one.

Generate one with wp matrix:make:migration create_books_table (the filename timestamp is generated at command runtime).

Clone this wiki locally