PHPackages                             baraja-core/shutdown-terminator - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. baraja-core/shutdown-terminator

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

baraja-core/shutdown-terminator
===============================

Registers handlers that run at the end of the request.

v1.0.1(4y ago)353.7k↑120%2PHPPHP ^8.0CI passing

Since Apr 21Pushed 4mo ago1 watchersCompare

[ Source](https://github.com/baraja-core/shutdown-terminator)[ Packagist](https://packagist.org/packages/baraja-core/shutdown-terminator)[ Docs](https://github.com/baraja-core/shutdown-terminator)[ RSS](/packages/baraja-core-shutdown-terminator/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)Dependencies (7)Versions (5)Used By (2)

PHP Shutdown Terminator
=======================

[](#php-shutdown-terminator)

A lightweight PHP library for registering and executing handlers at the end of script execution, with built-in memory reservation for fatal error recovery.

💡 Key Principles
----------------

[](#bulb-key-principles)

- **Automatic Memory Reservation**: Pre-allocates memory to ensure handlers execute even during fatal out-of-memory errors
- **Priority-Based Execution**: Handlers are sorted and executed in order of their assigned priority
- **Graceful Error Handling**: Exceptions in handlers are caught and logged without disrupting other handlers
- **Zero Dependencies**: Works standalone or integrates seamlessly with Tracy Debugger
- **Simple Interface**: Single method interface for handler implementation
- **Works with `die`/`exit`**: Handlers are invoked even when script terminates via `die()` or `exit()`

🏗️ Architecture &amp; Components
--------------------------------

[](#building_construction-architecture--components)

The package consists of four main components working together:

```
+-------------------------------------------------------------------+
|                           Terminator                              |
|         (Static orchestrator managing handler lifecycle)          |
|                                                                   |
|  +-------------------------------------------------------------+  |
|  |      Reserved Memory Buffer (100KB + custom allocations)    |  |
|  +-------------------------------------------------------------+  |
|                                                                   |
|  +-------------------------------------------------------------+  |
|  |  Handler Registry: array                 |  |
|  |                                                             |  |
|  |  +--------------------+    +--------------------+           |  |
|  |  | RegisteredHandler  |    | RegisteredHandler  |   ...     |  |
|  |  | - handler          |    | - handler          |           |  |
|  |  | - priority: 1      |    | - priority: 5      |           |  |
|  |  +---------+----------+    +---------+----------+           |  |
|  |            |                         |                      |  |
|  |            v                         v                      |  |
|  |  +--------------------+    +--------------------+           |  |
|  |  | TerminatorHandler  |    | TerminatorHandler  |           |  |
|  |  |    (interface)     |    |    (interface)     |           |  |
|  |  +--------------------+    +--------------------+           |  |
|  +-------------------------------------------------------------+  |
+-------------------------------------------------------------------+

                        Shutdown Sequence
                               |
                               v
                  +----------------------+
                  |   PHP Script Ends    |
                  |  (exit/die/natural)  |
                  +-----------+----------+
                              |
                              v
                  +----------------------+
                  |  shutdownHandler()   |
                  |    called by PHP     |
                  +-----------+----------+
                              |
                              v
                  +----------------------+
                  |  Sort handlers by    |
                  |    priority (ASC)    |
                  +-----------+----------+
                              |
                              v
                  +----------------------+
                  | Execute each handler |
                  |  with error trapping |
                  +----------------------+

```

### ⚙️ Component Overview

[](#gear-component-overview)

ComponentTypeDescription`Terminator`Static ClassMain orchestrator that manages the shutdown handler registry, memory reservation, and execution lifecycle`TerminatorHandler`InterfaceContract that all handler classes must implement; defines the `processTerminatorHandler()` method`RegisteredHandler`Value ObjectInternal wrapper that pairs a handler instance with its execution priority`TerminatorShutdownHandlerException`ExceptionCustom exception thrown when handler execution fails; used for Tracy Debugger logging💡 How It Works
--------------

[](#bulb-how-it-works)

### Memory Reservation Strategy

[](#memory-reservation-strategy)

When the first handler is registered, Terminator immediately:

1. Reserves **100 KB** of memory by allocating a string buffer
2. Registers PHP's native `register_shutdown_function()` to invoke `shutdownHandler()`

This pre-allocated memory acts as a safety buffer. If PHP runs out of memory during normal execution, the shutdown handler can still execute because the reserved memory is released and becomes available.

Additional memory can be reserved per-handler for complex cleanup operations.

### Shutdown Execution Flow

[](#shutdown-execution-flow)

1. **Trigger**: PHP shutdown event occurs (script end, `die()`, `exit()`, or fatal error)
2. **Guard Check**: Ensures handlers run exactly once via `$hasShutdown` flag
3. **User Abort Ignored**: Calls `ignore_user_abort(true)` to continue even if client disconnects
4. **Priority Sort**: Handlers are sorted ascending by priority (lower numbers execute first)
5. **Sequential Execution**: Each handler's `processTerminatorHandler()` is invoked
6. **Error Isolation**: Exceptions are caught, logged (via Tracy if available), and execution continues

### Handler States

[](#handler-states)

The `$hasShutdown` flag tracks three states:

StateValueMeaningNot initialized`null`No handlers registered yetReady`false`Handlers registered, waiting for shutdownCompleted`true`Shutdown function has been executed📦 Installation
--------------

[](#package-installation)

It's best to use [Composer](https://getcomposer.org) for installation, and you can also find the package on [Packagist](https://packagist.org/packages/baraja-core/shutdown-terminator) and [GitHub](https://github.com/baraja-core/shutdown-terminator).

To install, simply use the command:

```
$ composer require baraja-core/shutdown-terminator
```

You can use the package manually by creating an instance of the internal classes, or register a DIC extension to link the services directly to the Nette Framework.

### Requirements

[](#requirements)

- PHP 8.0 or higher
- No required dependencies (optional Tracy Debugger integration)

🚀 Basic Usage
-------------

[](#rocket-basic-usage)

### Implementing a Handler

[](#implementing-a-handler)

Create a class that implements the `TerminatorHandler` interface:

```
