PHP design patterns (Creational : part 2)
Let’s continue in our exploration of PHP data structures.
In the first episode, we talked about the “simple factory” pattern.
Now, we’ll go into a slightly more advanced structure.
Let’s talk about the Factory method:
The point of this pattern , can be compressed into one word : delegation.
Let’s imagine that just got an access to play to your favorite heroic fantasy video game.
Imagine there are 2 classes of characters to chose from :
- Warriors
- Druids
You decided to share the access of your account to two of your friends.
One of your friends like to play Warriors , while the other one likes to play Druids.
Here the character classes :
interface Character {public function attack();
}class Warrior implements Character {public function attack(){echo 'the warrior attacks';}
}class Druid implements Character {
public function attack(){ echo 'the Druid attacks'; }}
Let’s use an abstract class , representing the idea of delegation.
abstract class player{ abstract protected function createCharacter(): Character; public function attack(){ $character = $this->createCharacter();
$character->attack();
}}class friendA extends player{ protected function createCharacter(){ return new Warrior();
}}class friendB extends player{ protected function createCharacter(){ return new Thief(); }}
Now, you have 2 different friends, allowed to perform actions as a player. But even though they structurally use similar functions, they implement these functions in different fashions. They actually build distinct characters.
$friendA = new FriendA();$friendA->attack(); //Output : the warrior attacks$friendB = new FriendB();$friendB->attack(); //Output : the Druid attacks