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.
"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));
}
}
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;
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
Top comments (0)