DEV Community

Discussion on: Design Patterns in PHP 8: alternative implementations

Collapse
 
suckup_de profile image
Lars Moelleken

Traits are maybe helpful to not repeat code parts in a project, but it can easily prevent you to follow other interesting patterns like "Composition Over Inheritance" or "KISS" or "Open/Closed" because a trait in PHP is more or less code that will be copied into the class on runtime. The problem will only come up if you over-use traits or if you extend a class with traits, a quick solution would be to use an interface for every trait: e.g.: 3v4l.org/CfuF7#v8.1.8

Some hints for your code example:

  • do not use mixed types for array-keys
$db1 = Database::getInstance(1);
$db1->connect();

$db2 = Database::getInstance('1');
$db2->connect();

if ($db1 === $db2) {
    echo ":(";
}
Enter fullscreen mode Exit fullscreen mode
  • if you do not need NULL do not use it

e.g. array_key_exists will throw a warning on the first run because NULL is the default value for the static property "instance". You could just use an empty array as default so that you do not need to handle the NULL type.

PS: I already wrote that on my last comment ;) but I think it's important to know if someone is starting using Singleton Patterns -> you maybe do not need this at all because you can move this decision into your container e.g.: container.thephpleague.com/4.x/def...

Collapse
 
suckup_de profile image
Lars Moelleken

Here is also an interesting article about php traits: matthiasnoback.nl/2022/07/when-to-...