DEV Community

Cover image for PHP Tips | Exploring the Factory Pattern 🤖
Raziel Rodrigues
Raziel Rodrigues

Posted on • Edited on

6 1 1 1

PHP Tips | Exploring the Factory Pattern 🤖

Hello!

Today I will share with you one of most used design patterns specially inside PHP applications and frameworks, this pattern is called factory and is widely used.

First of all, the patterns can be divided into three big groups: creation, behavior, and structural.

The factory pattern belongs to the creation concept, which is a way to have new instances of objects. With this approach, we can create reusable code that is more legible and has fewer problems with code duplicity since we will encapsulate the logic inside one class.

Factory Pattern 🤖

This pattern comes with the idea of having a class which is a boilerplate location to build your objects, holding every way to create the object and avoiding the propagation of different object creation through your code.

Image description

"You and your friend are working with the same entity, and then he is creating the entity without the first name in lowercase. In your case, this is mandatory. Then you are creating different instances in different files, and maybe you cannot know that because you didn't do the code review, so with that, you will have a bug later on."

This pattern helps to solve this kind of problem. The implementation can be something like:

class User
{
    private int $id;
    private string $firstName;

    public function setId(int $id): User
    {
        $this->id = $id;
        return $this;
    }


    public function getId(): int
    {
        return $this->id;
    }


    public function setFirstName(string $firstName): User
    {
        $this->firstName = $firstName;
        return $this;
    }

    public function getFirstName(): string
    {
        return $this->firstName;
    }
}


class UserFactory
{

    public function __construct(
        private int $id,
        private string $firstName
    ) {
    }

    public function create(): User
    {
        return (new User())
            ->setId($this->id)
            ->setFirstName(strtolower($this->firstName));
    }
}


Enter fullscreen mode Exit fullscreen mode

Afterward, you call this class in both places, applying the rules you need in only one place:

$user1 = (new UserFactory(time(), 'JhOn Cena'))->create();
echo 'ID - ' . $user1->getId() . 'NAME - ' . $user1->getFirstName() . PHP_EOL;

$user2 = (new UserFactory(time(), 'UNDERTAKER'))->create();
echo 'ID - ' . $user2->getId() . 'NAME - ' . $user2->getFirstName() . PHP_EOL;
Enter fullscreen mode Exit fullscreen mode

With that, you avoid potential misuses of the code, and everybody knows where to see the logic of this particular object.

I suggest you to dive in new materials about that this course from ZEND is for free and is a nice way to learn more also refactoring guru has a lot of examples 🔥

References:

https://refactoring.guru/design-patterns/factory-method/php/example#example-1
https://en.wikipedia.org/wiki/Factory_method_pattern#Example_implementations
https://training.zend.com/learn/course/316/play/921:79/php-objects-object-oriented-programming-software-design-patterns

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay