Oussama Elgoumri
Oussama Elgoumri

Reputation: 617

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?

Upvotes: 0

Views: 623

Answers (3)

Gnucki
Gnucki

Reputation: 5133

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.

Upvotes: 0

Ja͢ck
Ja͢ck

Reputation: 173662

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());

Upvotes: 0

casraf
casraf

Reputation: 21694

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;
}

Upvotes: 0

Related Questions