sgh/decorate-anything

2.0.0 2014-11-06 21:48 UTC

This package is not auto-updated.

Last update: 2024-09-24 02:52:33 UTC


README

  • 概要
  • 安装
  • 需求
  • 用法

概要

此包是装饰器设计模式的简化实现。通过PHP的魔术方法和松散的类型化,可以不需要为每个对象创建抽象组件和抽象装饰器,从而使用提供的装饰器类的子类来装饰任何对象。

安装

您可以直接下载 Decorator.php 并将其包含在任何地方,但我建议使用composer。

require: {
    "sgh/decorate-anything": "~2.0"
}

需求

此包需要PHP 5.3或更高版本。

用法

要为组件(例如ConcreteComponent)创建装饰器,只需像这样扩展装饰器

class ConcreteDecorator extends \SGH\DecorateAnything\Decorator
{
    const COMPONENT_CLASS = 'ConcreteComponent';
}

要在装饰器中扩展组件方法的函数,使用parent关键字,就像在原始装饰器模式中做的那样

public function foo()
{
    parent::foo();
    some_special_functionality();
}

现在您可以这样装饰您的组件

$component = new ConcreteDecorator(new ConcreteComponent());

$component将与ConcreteComponent具有相同的接口,您也可以访问装饰组件的公共属性。

$component->foo();
$component->bar(1,2); // assuming a method ConcreteComponent::bar($x,$y)
var_dump($component->baz); // assuming a property ConcreteComponent::$baz
var_dump(isset($component->baz));
$component->baz = 1;
unset($component->baz);

如果您真的需要显式命名装饰器和组件的公共接口,请这样做

interface IConcreteComponent
{
    public function foo();
    public function bar($x,$y);
}
class ConcreteComponent implements IConcreteComponent
{
    public $baz = 'baz';
    public function foo()
    {
        // implementation
    }
    public function bar($x,$y)
    {
        // implementation
    }
}
class ConcreteDecorator extends \SGH\DecorateAnything\Decorator implements IConcreteComponent
{
    const COMPONENT_CLASS = 'ConcreteComponent';
    public function foo()
    {
        parent::foo();
        // additional implementation
    }
    public function bar($x,$y)
    {
        return parent::bar($x,$y);
    }
}