DEV Community

Cover image for Design Patterns in PHP 8: Interpreter

Design Patterns in PHP 8: Interpreter

Max Zhuk on September 05, 2023

Hello, fellow developers!🧑🏼‍💻 In the realm of software development, design patterns play a pivotal role in crafting efficient and scalable applica...
Collapse
 
xwero profile image
david duymelinck • Edited

The example doesn't add much value to the code just write echo 3+5; echo 3-5; and you got the same result.
The pattern as you show it also adds limitations, like only two arguments for the non-terminal classes.

I created an example that makes the grammar building more front and center.

<?php

interface BooleanGrammar {
    public function result(string $context): bool;
}
// Terminal classes
abstract class Node implements BooleanGrammar {
    public function __construct(private string $data) {}

    public function result(string $context): bool {
        return str_contains($context, $this->data);
    }
}

class Person extends Node {}

class Relationship extends Node {}
// Non-terminal classes
class HomogeneousGroup implements BooleanGrammar {
    private $persons = [];

    public function __construct(Person ...$persons) {
        $this->persons = $persons;
    }

    public function result(string $context): bool {
        foreach($this->persons as $person) {
            if($person->result($context)) {
                return true;
            }
        }

        return false;
    }
}

class PersonHasRelationship implements BooleanGrammar {
    public function __construct(private Person $person, private Relationship $relationship) {}

    public function result(string $context): bool {
        return $this->person->result($context) && $this->relationship->result($context);
    }
}
// tests
$areSingle = new HomogeneousGroup(new Person('me'), new Person('myself'));

var_dump($areSingle->result('me')); // true
var_dump($areSingle->result('i')); // false

$meRelationship = new PersonHasRelationship(new Person('me'), new Relationship('single'));

var_dump($meRelationship->result('me, single')); // true
var_dump($meRelationship->result('me, married')); // false
Enter fullscreen mode Exit fullscreen mode

I hope that this gives people a better idea on how to use the design pattern.