PHPackages                             mykemeynell/laravel-decorators - 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. mykemeynell/laravel-decorators

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

mykemeynell/laravel-decorators
==============================

Attribute-based method decorators (Log, Cache, Retry, …) wired into the Laravel IoC container.

v0.1.0(1mo ago)00MITPHPPHP &gt;=8.2CI passing

Since May 27Pushed 1mo agoCompare

[ Source](https://github.com/mykemeynell/laravel-decorators)[ Packagist](https://packagist.org/packages/mykemeynell/laravel-decorators)[ RSS](/packages/mykemeynell-laravel-decorators/feed)WikiDiscussions main Synced 1w ago

READMEChangelog (1)Dependencies (11)Versions (3)Used By (0)

Laravel Decorators
==================

[](#laravel-decorators)

> Python/TypeScript-style method decorators for Laravel services, powered by PHP 8 attributes.

This package provides a clean, attribute-based way to apply cross-cutting concerns (logging, caching, retries, etc.) to your Laravel service methods. It uses a lightweight proxy pattern to intercept method calls and wrap them in a decorator chain.

Requirements
------------

[](#requirements)

- **PHP:** `>=8.2`
- **Laravel:** `^11.0`, `^12.0`, or `^13.0`

Installation
------------

[](#installation)

```
composer require mykemeynell/laravel-decorators
```

Quick Start
-----------

[](#quick-start)

### 1. Add Attributes to Your Service

[](#1-add-attributes-to-your-service)

```
namespace App\Services;

use MykeMeynell\Laravel\Decorators\Decorators\Log;
use MykeMeynell\Laravel\Decorators\Decorators\Cache;

class UserService
{
    #[Log]
    #[Cache(ttl: 3600)]
    public function findUser(int $id): array
    {
        return User::findOrFail($id)->toArray();
    }
}
```

### 2. Resolve the Decorated Service

[](#2-resolve-the-decorated-service)

You can resolve your service through the `Decorator` facade to ensure it is wrapped in the proxy:

```
use MykeMeynell\Laravel\Decorators\Facades\Decorator;
use App\Services\UserService;

$service = Decorator::make(UserService::class);
$user = $service->findUser(1); // Call is logged and cached!
```

Built-in Decorators
-------------------

[](#built-in-decorators)

### `#[Log]`

[](#log)

Records method calls, arguments, and execution time to Laravel logs.

```
#[Log(level: 'info', logArgs: true, channel: 'stack')]
```

- `level`: PSR-compatible log level (default: `debug`).
- `logArgs`: Whether to include raw arguments in the log (default: `true`).
- `channel`: The Laravel log channel to use (default: config `log_channel`).

### `#[Cache]`

[](#cache)

Caches the method return value based on its identity and arguments.

```
#[Cache(ttl: 3600, store: 'redis', tags: ['users'], prefix: 'u:')]
```

- `ttl`: Time-to-live in seconds. Use `0` to cache forever (default: `3600`).
- `store`: The cache store to use (default: config `cache_store`).
- `tags`: Array of cache tags for taggable stores (default: `[]`).
- `prefix`: Key prefix (default: config `cache_prefix`).

### `#[Retry]`

[](#retry)

Transparently retries failed method calls with configurable backoff.

```
#[Retry(times: 3, delay: 100, backoff: 2.0, catch: [ServiceException::class])]
```

- `times`: Maximum attempts including the first call (default: `3`).
- `delay`: Base delay in milliseconds between retries (default: `0`).
- `backoff`: Multiplier for exponential backoff (default: `1.0`).
- `catch`: Array of exception classes to retry on (default: `[]`, catches all `Throwable`).
- `log`: Whether to log retry attempts (default: `true`).

### `#[RateLimit]`

[](#ratelimit)

Throttles method execution using Laravel's rate limiter.

```
#[RateLimit(maxAttempts: 5, decaySeconds: 60, key: 'my-bucket')]
```

- `maxAttempts`: Max calls within the window (default: `60`).
- `decaySeconds`: Window duration in seconds (default: `60`).
- `key`: Optional fixed bucket identifier. By default, keys are unique to method + arguments.

### `#[Transactional]`

[](#transactional)

Wraps the method execution in a database transaction.

```
#[Transactional(connection: 'mysql', attempts: 2)]
```

- `connection`: Database connection name (default: default connection).
- `attempts`: Number of times to retry the transaction on deadlock (default: `1`).

### `#[Validate]`

[](#validate)

Validates method arguments using Laravel's validator before execution.

```
#[Validate(['id' => 'required|integer', 'email' => 'required|email'])]
```

- `rules`: Array of validation rules. Can be keyed by parameter name or index.

### `#[Deprecated]`

[](#deprecated)

Emits a deprecation warning when the method is called.

```
#[Deprecated('Use newMethod() instead.')]
```

- `message`: Custom deprecation message. Emits `E_USER_DEPRECATED` in local/testing environments.

### `#[DecorateWith]`

[](#decoratewith)

Delegates decoration behavior to an arbitrary callable. This is useful for ad-hoc decoration without creating a dedicated attribute class.

```
#[DecorateWith(MyCustomWrapper::class)]
#[DecorateWith('App\Decorators\MyDecorator::handle')]
#[DecorateWith('my_global_decorator_function')]
public function myMethod() { ... }
```

- `classOrFunction`: A class name (must be invokable), a `Class::method` string, or a global function name.
- `method`: Optional method name if providing a class name separately.

**The callable must return another callable** that performs the actual wrapping:

```
class MyCustomWrapper
{
    public function __invoke(callable $next): callable
    {
        return function (array $args) use ($next) {
            // Pre-processing
            $result = $next($args);
            // Post-processing
            return $result;
        };
    }
}
```

Configuration
-------------

[](#configuration)

Publish the configuration file:

```
php artisan vendor:publish --tag="decorators-config"
```

### Auto-Decoration

[](#auto-decoration)

You can configure certain classes to be automatically decorated when resolved from the Laravel container:

```
// config/decorators.php
return [
    'decorate' => [
        App\Contracts\PaymentProcessor::class,
    ],
];
```

Creating Custom Decorators
--------------------------

[](#creating-custom-decorators)

Implement the `MethodDecorator` interface:

```
namespace App\Decorators;

use Attribute;
use MykeMeynell\Laravel\Decorators\Contracts\MethodDecorator;

#[Attribute(Attribute::TARGET_METHOD)]
class MyCustomDecorator implements MethodDecorator
{
    public function wrap(callable $next, array $context = []): callable
    {
        return function (array $args) use ($next) {
            // Logic before
            $result = $next($args);
            // Logic after
            return $result;
        };
    }
}
```

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

34

—

LowBetter than 75% of packages

Maintenance88

Actively maintained with recent releases

Popularity0

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity37

Early-stage or recently created project

 Bus Factor1

Top contributor holds 66.7% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

58d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/494de8188ad97403b72e40e385235a74ef6331aa2710b3727193f646189af9fc?d=identicon)[mykemeynell](/maintainers/mykemeynell)

---

Top Contributors

[![mykemeynell](https://avatars.githubusercontent.com/u/1590190?v=4)](https://github.com/mykemeynell "mykemeynell (2 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (1 commits)")

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/mykemeynell-laravel-decorators/health.svg)

```
[![Health](https://phpackages.com/badges/mykemeynell-laravel-decorators/health.svg)](https://phpackages.com/packages/mykemeynell-laravel-decorators)
```

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3345.3M347](/packages/psalm-plugin-laravel)[roots/acorn

Framework for Roots WordPress projects built with Laravel components.

9762.4M133](/packages/roots-acorn)[mike-bronner/laravel-model-caching

Automatic caching for Eloquent models.

2.4k96.5k1](/packages/mike-bronner-laravel-model-caching)[mongodb/laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel

7.1k8.4M98](/packages/mongodb-laravel-mongodb)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

255.2k](/packages/aedart-athenaeum)[laravel/ai

The official AI SDK for Laravel.

1.0k3.2M246](/packages/laravel-ai)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
