PHP design patterns: simple factory

Factory design pattern, is one of the creational design patterns to deal with the problem of creating objects through factory methods and classes, without having to specify which exact classes the created objects will have.

Simple Factory - the simplest Factory design pattern version 

In it's simplest form, Simple Facoty means that we have some single method to create Objects of specific class, but we don't know exactly how it does it, so basically this design pattern simply encapsulates the object instantiation and you don't need to use the new keyword.

Let's create a simple Factory class and see what it has:

<?php

namespace App\DesignPatterns\SimpleFactory;

class SimpleFactory
{
    public function createJukebox(): Jukebox
    {
        return new Jukebox();
    }
}

We can see that the only interesting part in it is createJukebox method, which creates an instance of Jukebox();

Of course, it's also allowed to have multiple versions of createJukebox() with different parameters or even subclasses whenever there is a need for something more advanced. 

<?php

namespace App\DesignPatterns\SimpleFactory;

class Jukebox
{
    public function play(string $title)
    {
        // @todo: implement
    }
}

Now we can run a simple test to check if the Jukebox class was successfully created.

<?php 

namespace App\Tests;

use App\DesignPatterns\SimpleFactory\Jukebox;
use App\DesignPatterns\SimpleFactory\SimpleFactory;

class SimpleFactoryTest extends \Codeception\Test\Unit
{
    /**
     * @var \App\Tests\UnitTester
     */
    protected $tester;
    
    protected function _before()
    {
    }

    protected function _after()
    {
    }

    public function testCreateJukeboxSuccess()
    {
        $jukebox = (new SimpleFactory())->createJukebox();

        $this->assertInstanceOf(Simple::class, $jukebox);
    }
}