3
0 Comments

Dynamic Traits in PHP

Hi all!

For quite some time, I implemented a feature, and I want to share it with you.

But first, a question. Have you ever struggled trying to customize how someone's code works without modifying it, for example, writing a plugin for some product and trying to overcome the limitations of the plugin API?

Well, look at it from the perspective of that code author.

You can think through all possible cases of how people may want to use your code. However, you can't predict how they may want to customize it to their needs.

You may provide extension points, but it's not enough. The best approach is AOP-like techniques that allow modifying anything in the original codebase.

So back to the feature I implemented, dynamic traits. It does allow changing the original codebase without any hassle.

For example, let's say the original code has something like

class Foo extends Object_ {
    public function exists(string $code): bool {
        ...
    } 
}

Then, in your code, you can customize standard behavior as follows:

#[UseIn(Foo::class)]
trait FooTrait {
    protected function around_exists(callable $proceed, string $code): bool {
        // this is executed before the original method
        ...
        $result = $proceed($code);
        ...
        // this is executed after original method
        return $result;
    }
}  

And it works with any method, any class. Read the whole article, I hope you will find it useful.

The whole thing is in active development, you are interested, I'm building it in public, follow me on Twitter.

on October 21, 2021