Example 1

Use case: Use the Proxy pattern in order to read a text file multiple times without opening the file more than once.

<?php

interface FileReader
{
    public function display(): string;
}

 

<?php

class RealFileReader implements FileReader
{
    private $fileName, $content;

    public function __construct(string $fileName)
    {
        $this->fileName = $fileName;

        $this->load($fileName);
    }

    public function display(): string
    {
        return $this->content;
    }

    public function load(string $fileName): void
    {
        echo "Loading '$fileName'..." . '<br>';

        $openedFile = fopen($fileName, "r");

        $this->content = fread($openedFile, filesize($this->fileName));
    }
}
<?php

class ProxyFileReader implements FileReader
{

    private $realFile, $fileName;

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

    private function getRealFile(): RealFileReader
    {
        if ($this->realFile == null)
            $this->realFile = new RealFileReader($this->fileName);

        return $this->realFile;
    }

    public function display(): string
    {
        return $this->getRealFile()->display();
    }
}

 

<?php

$fileReader = new ProxyFileReader('test.txt');

// First time it will need to open the file and return its content
echo $fileReader->display();

// Subsequent reads will fetch the content from the memory and it will
// display the same content as the first time
echo $fileReader->display();
echo $fileReader->display();
echo $fileReader->display();