可重用对象v状态和新对象创建

时间:2016-04-21 15:54:14

标签: php oop design-patterns dependency-injection

的含义是什么?
// Use a setData method to populate data on the object.  This will allow data to be set multiple times with a single object
class Testy
{
    private $data = [];

    public function setData(array $data)
    {
       $this->data = $data;      
    }

    public function validate()
    {
        foreach($this->data as $data) {
            if (! isset($data['id'])) {
                return false;   
            }
        }
        return true;
    }
}

// Set data using the constructor that will require multiple objects to handle multiple use cases
class Testy
{
    private $data = [];

    public function __construct(array $data)
    {
       $this->data = $data;      
    }

    public function validate()
    {
        foreach($this->data as $data) {
            if (! isset($data['id'])) {
                return false;   
            }
        }
        return true;
    }
}

// Set data to be validated directly on the validate method.  This is the most concise of the 3 but the class simply becomes a wrapper for the method which may be a smell that it belongs elsewhere.
class Testy
{
    public function validate($data)
    {
        foreach($data as $data) {
            if (! isset($data['id'])) {
                return false;   
            }
        }
        return true;
    }
}

提供一些上下文:示例非常简化,每个$ data数组都包含用于验证的对象。我想知道在给定请求中可能多次使用此对象的情况,哪些示例会被认为更好,并且如果列出的任何方法都有任何影响。

0 个答案:

没有答案