Skip to content

Instantly share code, notes, and snippets.

@elishaukpong
Last active August 7, 2021 08:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elishaukpong/13f0a05a965fc6e4d81f7db5eb1999e6 to your computer and use it in GitHub Desktop.
Save elishaukpong/13f0a05a965fc6e4d81f7db5eb1999e6 to your computer and use it in GitHub Desktop.
I have been thinking of where/how to utilise this concept in a day to day development and i realised this can be utilised in our abstract factory methods design pattern and it's composition. Check on the abstract factory on my other gists to get understanding
<?php
class Food
{
}
class AnimalFood extends Food
{
}
class CatFood extends Food
{
}
abstract class Animal
{
protected string $name;
public function __construct(string $name)
{
$this->name = $name;
}
abstract public function speak();
public function eat(AnimalFood $food)
{
echo $this->name . " eats " . get_class($food);
}
}
class Dog extends Animal
{
public function eat(Food $food) {
echo $this->name . " eats " . get_class($food);
}
public function speak()
{
echo $this->name . " says woh woh! \n";
}
}
class Cat extends Animal
{
/**
* @param CatFood $food
*/
public function eat(AnimalFood $food) {
echo $this->name . " eats " . static::class;
}
public function speak()
{
echo $this->name . " says meow! \n";
}
}
abstract class AnimalShelter
{
abstract public function adopt($name): Animal;
}
class CatShelter extends AnimalShelter
{
public function adopt($name): Cat
{
return new Cat($name);
}
}
class DogShelter extends AnimalShelter
{
public function adopt($name): Dog
{
return new Dog($name);
}
}
$newAdoptedCat = (new CatShelter)->adopt('Ricky');
$newAdoptedDog = (new DogShelter)->adopt('Morty');
$newAdoptedCat->speak();
$newAdoptedDog->speak();
$newAdoptedCat->eat(new AnimalFood);
echo "\n";
$newAdoptedDog->eat(new Food);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment