The flyweight pattern is a relatively unknown design pattern in PHP. The fundamental principle behind the flyweight pattern is that memory can be saved by remembering objects after they have been created. Then, if the same objects need to be used again, resources do not have to be wasted recreating them.

Balloon lifting a barbell

You can think of the flyweight pattern as a modification to a conventional object factory. The modification being that rather than just creating new objects all the time, the factory should check to see if it has already created the requested object. If it has, it should return this instance rather than create the object again.

A good use case for the flyweight pattern would be an application that has to load large files. These files would be our flyweight objects.

The Flyweight Object

One important feature of flyweight objects is that they are immutable. This means that they cannot be changed once they have been constructed. This is because our factory can only guarantee that it has remembered the correct object if it can also guarantee that the object it originally created has not been modified.

Below is a very simple example flyweight object for a file. We can tell that it is immutable because the ‘data’ property cannot be changed after the constructor has been called. There is no ‘setData’ method.

class File
{
    private $data;

    public function __construct($filePath)
    {
        // Check to make sure the file exists
        if (!file_exists($filePath)) {
            throw new InvalidArgumentException('File does not exist: '.$filePath);
        }

        $this->data = file_get_contents($filePath);
    }

    public function getData()
    {
        return $this->data;
    }
}

Continue reading %Flyweight Design Pattern and Immutability: A Perfect Match%

Source: SitePoint