> For the complete documentation index, see [llms.txt](https://docs.pteroca.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.pteroca.com/for-developers/plugins/bootstrap-and-lifecycle.md).

# Bootstrap & Lifecycle

The Bootstrap class handles plugin initialization and cleanup during the plugin lifecycle.

## Basic Structure

```php
<?php
namespace Plugins\MyPlugin;

use Psr\Log\LoggerInterface;

class Bootstrap
{
    public function __construct(
        private readonly LoggerInterface $logger,
    ) {}

    /**
     * Called when plugin is enabled
     */
    public function initialize(): void
    {
        $this->logger->info('MyPlugin initialized', [
            'plugin' => 'my-plugin',
            'version' => '1.0.0'
        ]);

        // Initialization logic here
        // DO NOT initialize settings - use migrations instead
    }

    /**
     * Called when plugin is disabled
     */
    public function cleanup(): void
    {
        $this->logger->info('MyPlugin cleanup', [
            'plugin' => 'my-plugin'
        ]);

        // Cleanup logic here
        // DO NOT delete user data!
        // DO NOT drop database tables!
    }
}
```

## Dependency Injection

Bootstrap supports full dependency injection:

```php
class Bootstrap
{
    public function __construct(
        private readonly LoggerInterface $logger,
        private readonly EntityManagerInterface $entityManager,
        private readonly PluginSettingService $pluginSettings,
        private readonly EventDispatcherInterface $eventDispatcher,
    ) {}
}
```

## What to Do in initialize()

**Good practices:**

* Log initialization
* Validate runtime requirements (PHP extensions, etc.)
* Register runtime hooks (if needed)
* Perform initial data validation
* Trigger initial sync with external services (if needed)

**Bad practices:**

* ❌ Create database tables (use migrations instead)
* ❌ Initialize settings (use migrations instead)
* ❌ Heavy computations (keep it fast)
* ❌ Make external API calls (unless absolutely necessary)
* ❌ Throw exceptions unless truly critical

## What to Do in cleanup()

**Good practices:**

* Log cleanup
* Cancel scheduled jobs (if using external schedulers)
* Close external connections
* Clear temporary caches
* Notify external services of deactivation

**Bad practices:**

* ❌ Delete user data
* ❌ Drop database tables
* ❌ Delete plugin settings
* ❌ Remove migrations
* ❌ Any destructive operations

**Important**: Cleanup is NOT uninstall! Users may re-enable the plugin later and expect their data intact.

## Error Handling

```php
public function initialize(): void
{
    try {
        // Initialization logic
        $this->setupExternalService();
    } catch (\Exception $e) {
        $this->logger->error('Plugin initialization failed', [
            'plugin' => 'my-plugin',
            'error' => $e->getMessage(),
            'trace' => $e->getTraceAsString()
        ]);

        // Plugin will enter FAULTED state
        throw $e;
    }
}
```

## Bootstrap Registration

Ensure Bootstrap is public in `services.yaml`:

```yaml
services:
    Plugins\MyPlugin\Bootstrap:
        public: true
```

## Plugin Lifecycle

The plugin goes through these states:

1. **DISCOVERED**: Plugin found by scanner
2. **REGISTERED**: Plugin manifest validated and registered
3. **ENABLED**: Plugin active, Bootstrap->initialize() called
4. **DISABLED**: Plugin inactive, Bootstrap->cleanup() called
5. **UPDATE\_PENDING**: Plugin has an available update
6. **FAULTED**: Plugin encountered error during initialization

## Related Guides

* [Plugin Manifest](/for-developers/plugins/plugin-manifest.md) - Configure bootstrap\_class
* [Dependencies](/for-developers/plugins/dependencies.md) - Service injection
* [Entities & Database](/for-developers/plugins/entities-and-database.md) - Use migrations for setup


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.pteroca.com/for-developers/plugins/bootstrap-and-lifecycle.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
