kwidoo/lifecycle 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

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

kwidoo/lifecycle

Composer 安装命令:

composer require kwidoo/lifecycle

包简介

Lifecycle for my Laravel apps

README 文档

README

Latest Version on Packagist Tests Code Style Total Downloads

A Laravel package that provides a flexible lifecycle management system for your application operations. This package helps you implement consistent patterns for handling events, transactions, logging, authorization, caching, and rate limiting across your Laravel application.

Features

  • 🛡️ Authorization Management: Control access with configurable authorization strategies
  • 🔄 Transaction Management: Wrap operations in database transactions
  • 📊 Logging: Automatically log actions, results, and errors
  • 📡 Event Dispatching: Dispatch events before and after operations
  • 💾 Caching: Cache operation results for improved performance
  • 🚦 Rate Limiting: Protect against abuse with configurable rate limiting
  • 🔁 Retry Handling: Automatically retry failed operations with backoff
  • 🧩 Strategy Pattern: Choose which features to enable for each operation
  • 🔌 Extensible: Create custom strategies for your specific requirements

Installation

You can install the package via composer:

composer require kwidoo/lifecycle

Configuration

Publish the configuration file:

php artisan vendor:publish --provider="Kwidoo\\Lifecycle\\LifecycleServiceProvider"

This will create a config/lifecycle.php file where you can configure default behaviors.

Usage

Basic Usage

use Kwidoo\Lifecycle\Data\LifecycleContextData;
use Kwidoo\Lifecycle\Data\LifecycleOptionsData;
use Kwidoo\Lifecycle\Contracts\Lifecycle;

class YourService
{
    public function __construct(protected Lifecycle $lifecycle) {}

    public function performAction($context)
    {
        $contextData = new LifecycleContextData(
            action: 'create',
            resource: 'users',
            context: $context
        );

        return $this->lifecycle->run($contextData, function ($contextData) {
            // Your business logic here
            $result = $this->createUser($contextData->context);

            return $result;
        }, new LifecycleOptionsData());
    }
}

Customizing Strategy Options

You can use the fluent interface to customize which strategies are enabled:

// Configure strategies with fluent interface
$result = $this->lifecycle->run(
    $contextData,
    function ($contextData) {
        // Business logic
        return $result;
    },
    (new LifecycleOptionsData())
        ->withoutTrx()       // Disable transactions
        ->withEvents()       // Enable events
        ->withoutLogging()   // Disable logging
        ->withCache()        // Enable caching
        ->withRetry()        // Enable retry on failure
);

Lifecycle Data

The package now uses separate data objects for input and output:

// Input context data - immutable
$contextData = new LifecycleContextData(
    action: 'update',      // The action being performed (create, update, delete, etc.)
    resource: 'products',  // The resource being operated on
    context: $product,     // The contextual data for the operation
);

// Execute with lifecycle
$resultData = $this->lifecycle->run($contextData, function($contextData) {
    // Business logic - process the context
    $result = processData($contextData->context);

    // Return the result
    return $result;
});

Events

Events are dispatched with the following naming pattern:

  • Before operation: before.{resource}.{action}
  • After operation: after.{resource}.{action}
  • On error: error.{resource}.{action}

Advanced Usage

Custom Authorizers

You can create custom authorizers for specific resources:

namespace App\Authorizers;

use Kwidoo\Lifecycle\Authorizers\DefaultAuthorizer;

class ProductAuthorizer extends DefaultAuthorizer
{
    public function authorize(string $action, $context): bool
    {
        // Custom authorization logic for products
        if ($action === 'delete' && !$this->userCanDeleteProduct($context)) {
            return false;
        }

        return true;
    }

    protected function userCanDeleteProduct($product): bool
    {
        return auth()->user()->hasPermission('delete-products');
    }
}

Custom Strategy Implementations

You can create custom strategies by implementing the respective interfaces:

namespace App\Strategies\Logging;

use Kwidoo\Lifecycle\Contracts\Strategies\LogStrategy;
use Kwidoo\Lifecycle\Data\LifecycleContextData;

class EnhancedLogStrategy implements LogStrategy
{
    public function execute(LifecycleContextData $data, callable $callback): mixed
    {
        // Custom pre-execution logging
        $this->logWithMetadata($data, 'before');

        // Execute the callback
        $result = $callback();

        // Custom post-execution logging
        $this->logWithMetadata($data, 'after', $result);

        return $result;
    }

    public function logPhase(LifecycleContextData $data, string $phase, string $level = 'info'): void
    {
        // Your custom logging implementation
    }

    protected function logWithMetadata(LifecycleContextData $data, string $phase, $result = null): void
    {
        // Enhanced logging with additional metadata
    }
}

Using Caching

Enable caching for frequently-used operations:

$result = $this->lifecycle->run(
    $contextData,
    function ($contextData) {
        // Expensive operation that will be cached
        return $this->repository->fetchExpensiveData($contextData->context);
    },
    (new LifecycleOptionsData())
        ->withCache()  // Results will be cached
);

Rate Limiting

Protect your application from abuse:

$result = $this->lifecycle->run(
    $contextData,
    function ($contextData) {
        // Operation that needs rate limiting
        return $this->processSensitiveOperation($contextData->context);
    },
    (new LifecycleOptionsData())
        ->withRateLimit()  // Apply rate limiting
);

Testing

composer test

The package includes comprehensive test coverage for all components including:

  • Unit tests for all service components
  • Strategy implementation tests
  • Feature/integration tests demonstrating real-world use cases

Tests are automatically run via GitHub Actions when code is pushed to the repository.

Upgrading

If you're upgrading from a previous version, please see the Upgrade Guide for detailed instructions.

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security issues, please email oleg@pashkovsky.me instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.

kwidoo/lifecycle 适用场景与选型建议

kwidoo/lifecycle 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 04 月 24 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「lifecycle」 「kwidoo」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

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

围绕 kwidoo/lifecycle 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-04-24