PHPackages                             marcojetson/php-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. marcojetson/php-decorators

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

marcojetson/php-decorators
==========================

Python-like decorators for PHP

46PHP

Since Jun 18Pushed 10y ago1 watchersCompare

[ Source](https://github.com/marcojetson/php-decorators)[ Packagist](https://packagist.org/packages/marcojetson/php-decorators)[ RSS](/packages/marcojetson-php-decorators/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

php-decorators
==============

[](#php-decorators)

Python-like decorators for PHP

[![Build status](https://camo.githubusercontent.com/c3c39cdfed500c7085fb343c240b383c517be8f77f46f9bb1a5da01413ec8fb8/68747470733a2f2f7472617669732d63692e6f72672f6d6172636f6a6574736f6e2f7068702d6465636f7261746f72732e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/marcojetson/php-decorators)[![Test coverage](https://camo.githubusercontent.com/ced5cabba66b7dcb4ff628d5f25cdce2aabe7679eeadb4d556eac9028a3d71a7/68747470733a2f2f636f6465636c696d6174652e636f6d2f6769746875622f6d6172636f6a6574736f6e2f7068702d6465636f7261746f72732f6261646765732f636f7665726167652e737667)](https://codeclimate.com/github/marcojetson/php-decorators/coverage)

Disclaimer
----------

[](#disclaimer)

Please note that this is a proof of concept, use it at your own risk.

Usage
-----

[](#usage)

Specify decorators with the `@Decorate` annotation using one of the following formats:

- Class name::method name
- Class name (must implement \_\_invoke)
- Function name

Decorators take the original method and the context as arguments and must return a function that takes the same arguments the original method does.

It's possible to add as many decorators as desired, always returning a valid callable for the next decorator.

(almost) Real life examples
---------------------------

[](#almost-real-life-examples)

### In memory cache

[](#in-memory-cache)

```
class InMemoryCacheDecorator
{
    private static $cache;

    public function __invoke($callable)
    {
        return function () use ($callable) {
            $args = func_get_args();
            $key = serialize([$callable, $args]);

            if (!isset(static::$cache[$key])) {
                static::$cache[$key] = call_user_func_array($callable, $args);
            }

            return static::$cache[$key];
        };
    }
}

class MyClass
{
    use Decorator\AnnotationDecoratorFactoryTrait;

    /**
     * @Decorate InMemoryCacheDecorator
     */
    public function myMethod($name)
    {
        sleep(1);
        return 'Hello ' . $name;
    }
}

$x = MyClass::factory(); // or use new AnnotationDecorator(new MyClass());

echo $x->myMethod('Marco'), PHP_EOL;
echo $x->myMethod('Marco'), ' (this time is cached)', PHP_EOL;
echo $x->myMethod('Marco'), ' (this time is cached)', PHP_EOL;

echo $x->myMethod('World'), PHP_EOL;
echo $x->myMethod('World'), ' (this time is cached)', PHP_EOL;
echo $x->myMethod('World'), ' (this time is cached)', PHP_EOL;
```

### Cart promos

[](#cart-promos)

```
class Cart
{
    private $total = 100;

    /**
     * @Decorate halfVat
     * @Decorate fixedDiscount
     */
    public function calcTotal($vat)
    {
        return $this->total * (1 + $vat / 100);
    }
}

function halfVat($callable)
{
    return function ($vat) use ($callable) {
        return $callable($vat / 2);
    };
}

function fixedDiscount($callable)
{
    return function ($vat) use ($callable) {
        $total = $callable($vat) - 5;
        return $total < 0 ? 0 : $total;
    };
}

/** @var Cart $order */
$order = new Decorator\AnnotationDecorator(new Cart());
echo $order->calcTotal(21), PHP_EOL;
```

### Controller requirements

[](#controller-requirements)

```
function require_http_post($callable, $context)
{
    return function () use ($callable, $context) {
        if ($context->getMethod() !== 'POST') {
            throw new \Exception('Not supported');
        }

        return call_user_func_array($callable, func_get_args());
    };
}

class AddressController
{
    use Decorator\AnnotationDecoratorFactoryTrait;

    private $method;

    public function __construct($method)
    {
        $this->method = $method;
    }

    public function getMethod()
    {
        return $this->method;
    }

    /**
     * @Decorate require_http_post
     */
    public function deleteAction($id)
    {
        // delete...
        return 'success';
    }
}

echo AddressController::factory('POST')->deleteAction(1), PHP_EOL;
echo AddressController::factory('GET')->deleteAction(1), PHP_EOL;
```

Gotchas
-------

[](#gotchas)

- Only works for methods
- Not completely transparent, you need to use the factory method
- No parameters type hinting for the decorated class

###  Health Score

21

—

LowBetter than 18% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity8

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity41

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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.

### Community

Maintainers

![](https://www.gravatar.com/avatar/fea021b095644a08ddb0d040b2048832304b2360844ba59b8145d6aee70bbf22?d=identicon)[marcojetson](/maintainers/marcojetson)

---

Top Contributors

[![marcojetson](https://avatars.githubusercontent.com/u/408194?v=4)](https://github.com/marcojetson "marcojetson (8 commits)")

### Embed Badge

![Health badge](/badges/marcojetson-php-decorators/health.svg)

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

PHPackages © 2026

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