当前位置: 动力学知识库 > 问答 > 编程问答 >

oop - Get all the instances of a particular class in PHP

问题描述:

I want to be able to do something like:

objects = getAllInstances(ClassName);

where ClassName has a unique field, so that two instances can not have the exact same value of that field.

class ClassName {

protected $unique_field;

public function __construct($value)

{

$objects = getAllInstances(self);

foreach($objects as $object)

{

if($object->getUniqueField() === $value)

{

return $object;

}

}

}

public function getUniqueField()

{

return $this->unique_field;

}

};

Is there a design pattern, a built-in function in PHP for this purpose, or must I use a static array that holds all the created instances and then just loop over it?

网友答案:

You could create a factory that keeps a reference to all instances created with it:

class ClassNameFactory 
{
    private $instances = [];

    public function create($value)
    {
        return $this->instances[] = new ClassName($value);
    }

    public function getInstances()
    {
        return $this->instances;
    }
}

$f = new ClassNameFactory();
$o1 = $f->create('foo');
$o2 = $f->create('bar');
print_r($f->getInstances());
网友答案:

You can hold a static array with all the existing instances. Something similar to this...

static $instances;

public function __construct($name) {
    $this->unique_field = $name;

    if (empty($instances)) {
        self::$instances = array();
    }

    foreach (self::$instances as $instance) {
        if ($instance->getUniqueField() === $name)
            return $instance;
    }

    self::$instances[] = $this;
}
网友答案:

What you need is the registry pattern:

class ClassNameRegistry {
    private $instances = array();

    public function set($name, InterfaceName $instance) {
        $this->instances[$name] = $instance;
    }

    public function get($name) {
        if (!$this->has($name)) {
            throw new \LogicException(sprintf(
                'No instance "%s" found for class "ClassName".',
                $name
            );
        }

        return $this->instances[$name];
    }

    public function has($name) {
        return isset($this->instances[$name]);
    }

    public function getAll() {
        return $this->instances;
    }
}

This is certainly the best OOP architecture option because you isolate the behaviour in a standalone class as a service. If you do not have a dependency injection mechanism with services, I would suggest you to define the registry class as a singleton!

In my example, I used a InterfaceName to have a low coupling between Registry and its handled instances.

分享给朋友:
您可能感兴趣的文章:
随机阅读: