m1lt0n/delegator

适用于PHP 5.4+的简单代理器

1.1.0 2015-09-04 08:02 UTC

This package is not auto-updated.

Last update: 2024-09-18 10:01:47 UTC


README

Build Status

代理器

一个简单的对象代理机制。

Delegator是一个简单的库,允许将对象的方法代理到其他对象。它可以与实现Delegators结合使用,部分装饰对象,部分将代理到原始未装饰的对象。

示例

<?php

use Delegator\DelegatorInterface;

// Assume we have a Person class
class Person implements DelegatorInterface
{
    use \Delegator\DelegatorTrait;

    // Implement the delegateMap method. This is the only requirement
    // of the DelegatorInterface
    public function delegateMap()
    {
        return [
            'address' => [ 'fullAddress' ],
            'settings' => static::ANY,
        ];
    }

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

class Address
{
    protected $street;
    protected $number;
    protected $city;

    public function __construct($street, $number, $city)
    {
        $this->street = $street;
        $this->number = $number;
        $this->city = $city;
    }

    public function fullAddress()
    {
        return "{$this->number}, {$this->street}, {$this->city}";
    }
}

class Settings
{
    public function all()
    {
        return 'all settings';
    }

    public function something()
    {
        return 'some setting';
    }
}

// Simply by using the DelegatorTrait and implementing the delegateMap method,
// we can now delegate calls to the mapped delegates.
$address = new Address('Percy str.', 9, 'London');
$settings = new Settings();
$me = new Person($address, $settings);

echo $me->fullAddress(); // this will be delegated to $me->address->fullAddress();
echo $me->all(); // this will be delegated to $me->settings->all();

// this is equivalent to $me->address->fullAddress, but we have simplified
// our API and hide the internals, while ensuring separation of concerns and
// limited responsibility for each class.

注意:在映射中可以分配多个代理人。