A factory class encapsulates instance creations and makes it possible to hide the detail of a class from its user.

In the snippet below, the factory class creates an instance of the concrete class that provides the functionality to write data to a file.

<?php
namespace sample;

interface FileWriter
{
    public function write($data);
}

class NullFileWriter implements FileWriter
{
    public function write($data)
    {
    }
}

class JsonFileWriter implements FileWriter
{
    private $filePath;

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

    public function write($data)
    {
        $json = json_encode($data, true);
        file_put_contents($this->filePath, $json);
    }
}

class FileWriterFactory
{
    public static function create($filePath)
    {
        if (is_null($filePath)) {
            return new NullFileWriter();
        }

        if (self::endsWith($filePath, '.json')) {
            return new JsonFileWriter($filePath);
        }

        throw new \Exception('The file format is not supported.');
    }

    private static function endsWith($heystack, $suffix)
    {
        return substr($heystack, 0 - strlen($suffix)) === $suffix;
    }
}

Let’s use FileWriterFactory class.

<?Php
$writer = FileWriterFactory::create('sample.json');
$writer->write([1, 2, 3, 4]);