Proxy method and property interactions in PHP.

v0.1.0 2021-09-07 08:51 UTC

This package is auto-updated.

Last update: 2024-04-07 14:49:17 UTC


README

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

Provides a Proxy class that can be used to intercept method calls, property access and updates.

Support development

If you would like to support the on going maintenance and development of this package, please consider sponsoring me on GitHub.

Installation

You can install the package via Composer:

composer require ryangjchandler/proxy

Usage

This package provides a Proxy class that you can use to wrap any object. It allows you to intercept property access and assignments, as well as method calls.

Here's an example:

class Target
{
    public $firstName = 'Ryan';

    public $lastName = 'Chandler';
}

$proxy = new Proxy(new Target, [
    'get' => function (Target $target, string $property) {
        if ($property === 'fullName') {
            return $target->firstName . ' ' . $target->lastName;
        }

        return $target->{$property};
    },
]);

$proxy->fullName; // 'Ryan Chandler'

If you would like to handle "setting" a property's value, you can add a set key and callback function to the handlers array.

$proxy = new Proxy(new Target, [
    'set' => function (Target $target, string $property, mixed $value) {
        if ($property === 'fullName') {
            $parts = explode(' ', $value);

            $target->firstName = $parts[0];
            $target->lastName = $parts[1];
        } else {
            $target->{$property} = $value;
        }
    },
]);

To intercept method calls, add a call key to the array.

class Target
{
    public int $number = 10;
}

$proxy = new Proxy(new Target, [
    'call' => function (Target $target, string $method, array $arguments) {
        if ($method === 'toInt') {
            return $target->number;
        }

        return $target->{$method}(...$arguments);
    },
]);

$proxy->toInt(); // 10

Testing

composer test

Changelog

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

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

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