承接 fast-forward/defer 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

fast-forward/defer

Composer 安装命令:

composer require fast-forward/defer

包简介

Fast Forward Deferred Callbacks utility classes

README 文档

README

PHP Version Composer Package Tests Coverage Docs License GitHub Sponsors

A minimal utility that brings defer-style execution (similar to Go) to PHP using object scope and destructors. It allows you to register callbacks that will run automatically at the end of a scope, in LIFO order (Last-In, First-Out).

Core Concept

A Defer instance represents a scope-bound execution stack.

  • Register callbacks using $defer(...) or $defer->defer(...)
  • Callbacks execute automatically when the object goes out of scope
  • Execution is always LIFO (stack behavior)
  • Execution is guaranteed during exception unwinding
  • Errors inside callbacks are captured and reported, without interrupting the chain

Basic Usage

use FastForward\Defer\Defer;

function example(): void
{
    $defer = new Defer();

    $defer(function () {
        echo "First defer\n";
    });

    $defer(function () {
        echo "Second defer\n";
    });

    echo "Inside function\n";
}

example();

Output

Inside function
Second defer
First defer

Using Arguments

Deferred callbacks receive exactly the arguments you pass.

function example(): void
{
    $defer = new Defer();

    $defer(function ($file) {
        echo "Deleting {$file}\n";
    }, 'temp.txt');

    echo "Working...\n";
}

example();

Output

Working...
Deleting temp.txt

⚠️ Execution Order Matters

Deferred callbacks execute in reverse order of registration.

$defer(fn() => unlink($file));
$defer(fn() => fclose($handle));

Execution order:

fclose($handle)
unlink($file)

Always register in reverse of the desired execution order.

Exception Safety

Deferred callbacks always run, even if an exception occurs.

function process(): void
{
    $defer = new Defer();

    $defer(fn() => print "Cleanup\n");

    throw new Exception('Failure');
}

try {
    process();
} catch (Exception) {
    echo "Exception caught\n";
}

Output

Cleanup
Exception caught

Nested Scopes

Each Defer instance is isolated.

function outer(): void
{
    $defer = new Defer();

    $defer(fn() => print "Outer cleanup\n");

    inner();
}

function inner(): void
{
    $defer = new Defer();

    $defer(fn() => print "Inner cleanup\n");
}

outer();

Output

Inner cleanup
Outer cleanup

Helper Functions

defer()

Creates a new Defer instance.

Inside function
Second defer
First defer0

scope()

Runs a block with an isolated defer scope.

use function FastForward\Defer\scope;

scope(function ($defer) {
    $defer(fn() => print "Cleanup\n");

    echo "Inside\n";
});

using()

Structured resource management (acquire → use → cleanup).

Inside function
Second defer
First defer2

Error Handling

Deferred callbacks never break execution flow.

  • If a callback throws, execution continues
  • Errors are forwarded to an ErrorReporter
  • Default behavior uses error_log()

Custom Error Reporter

Inside function
Second defer
First defer3

Composite Reporter

Inside function
Second defer
First defer4

PSR Integration

PSR-3 Logger

use FastForward\Defer\ErrorReporter\PsrLoggerErrorReporter;

Defer::setErrorReporter(
    new PsrLoggerErrorReporter($logger)
);

PSR-14 Event Dispatcher

Inside function
Second defer
First defer6

This allows multiple listeners (logging, metrics, tracing, etc.).

HTTP Middleware (PSR-15)

You can bind a Defer instance to a request lifecycle.

Inside function
Second defer
First defer7

The middleware:

  • creates a Defer per request
  • injects it into request attributes
  • ensures execution at the end of the request

Accessing Defer in Handlers

use FastForward\Defer\DeferInterface;

$defer = $request->getAttribute(DeferInterface::class);
$defer(fn() => cleanup());

Execution Model

Within a single scope

  • Last registered → runs first

Across nested scopes

  • Inner scope resolves before outer

Design Principles

  • Deterministic cleanup
  • Minimal API
  • No manual flush
  • Failure isolation
  • Extensible reporting

Notes

  • Execution is triggered by __destruct()
  • Do not share instances across scopes
  • Prefer short-lived instances
  • Avoid long-lived/global usage

When to Use

  • resource cleanup
  • file handling
  • locks
  • temporary state
  • exception-safe teardown

When NOT to Use

  • long-lived lifecycle management
  • orchestration logic
  • cases requiring explicit execution timing

Summary

Defer provides a strict and predictable cleanup model:

  • automatic execution at scope end
  • LIFO ordering
  • safe failure handling
  • pluggable reporting
  • PSR-friendly integrations

It is intentionally small, deterministic, and constrained.

fast-forward/defer 适用场景与选型建议

fast-forward/defer 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 331 次下载、GitHub Stars 达 0, 最近一次更新时间为 2026 年 03 月 27 日, 在 PHP 生态内属于活跃度较高的组件。

我们在过去多个企业项目中使用过 fast-forward/defer 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 fast-forward/defer 我们能提供哪些服务?
定制开发 / 二次开发

基于 fast-forward/defer 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 331
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 23
  • 依赖项目数: 2
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-03-27