Design Patterns PHP - Proxy Java

1) What have we done?

We just created "Subject" interface which define an functionality offered by this object.

Class "RealSubject" provide proper implementation. As we know creating of objects is time-consuming.

interface Subject
{
    public function doSomething();
}

class RealSubject implements Subject
{
    public function __construct()
    {
        usleep(10000);
    }

    public function doSomething()
    {
        echo 'doing something' . PHP_EOL;
    }
}




2) What is the proxy?

"Proxy" is the special objects which is a "Subject" and has a "RealSubject" for offering the client the same implementation.
For the client "Proxy" is transparent as is a "Subject" type.


class Proxy implements Subject
{
    /**
     * @var RealSubject
     */
    protected $realSubject = null;

    public function doSomething()
    {
        if ($this->realSubject == null) {
            $this->realSubject = new RealSubject();
        }
        $this->realSubject->doSomething();
    }

}

/** @var Subject[] $subjects */
$subjects = [];
for ($i = 0; $i < 500; $i++) {
    $subjects[] = new Proxy();
}

for ($i = 0; $i < 10; $i++) {
    $subjects[array_rand($subjects)]->doSomething();
}




In client now our pools is pools of "Proxy" objects not "RealSubject"
We just create "RealSubject" only when we need it.

Now we don't have to wait 5 seconds at the beginning and the functionality didn't change. Everything thanks to the "Proxy" objects.