如何在PHP中实现装饰器? [英] How to implement a decorator in PHP?

查看:59
本文介绍了如何在PHP中实现装饰器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有一个名为"Class_A"的类,它具有一个名为"func"的成员函数.

Suppose there is a class called "Class_A", it has a member function called "func".

我希望"func"通过将Class_A包装在装饰器类中来做一些额外的工作.

I want the "func" to do some extra work by wrapping Class_A in a decorator class.

$worker = new Decorator(new Original());

有人可以举一个例子吗?我从未在PHP中使用OO.

Can someone give an example? I've never used OO with PHP.

以下版本正确吗?

class Decorator
{
    protected $jobs2do;

    public function __construct($string) {
        $this->jobs2do[] = $this->do;
    }

    public function do() {
        // ...
    }
}

上面的代码旨在为数组增加一些额外的工作.

The above code intends to put some extra work to a array.

推荐答案

我建议您还为装饰器和要装饰的对象创建一个统一的接口(甚至是抽象基类).

I would suggest that you also create a unified interface (or even an abstract base class) for the decorators and the objects you want decorated.

要继续上述示例,请提供以下内容:

To continue the above example provided you could have something like:

interface IDecoratedText
{
    public function __toString();
}

然后当然要修改 Text来实现该接口.

Then of course modify both Text and LeetText to implement the interface.

class Text implements IDecoratedText
{
...//same implementation as above
}

class LeetText implements IDecoratedText
{    
    protected $text;

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

    public function __toString() {
        return str_replace(array('e', 'i', 'l', 't', 'o'), array(3, 1, 1, 7, 0), $this->text->toString());
    }

}

为什么要使用界面?

因为这样您可以添加任意数量的装饰器,并确保每个装饰器(或要装饰的对象)将具有所有必需的功能.

Because then you can add as many decorators as you like and be assured that each decorator (or object to be decorated) will have all the required functionality.

这篇关于如何在PHP中实现装饰器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆