O
O
OnlyMyQuestion2019-10-22 18:46:12
PHP
OnlyMyQuestion, 2019-10-22 18:46:12

How to implement struct interface after string parsing?

Good afternoon. I want to implement loose coupling between components: Parser, Service.
Parser - parses the input string and converts it into a structure that different Services can work with through the interface, some will display information in different formats based on the input data, some will perform some calculations, etc.
The structure received by the parser consists of elements of three types:
- Collection (May contain other Collection, Element1, Element2)
- Element1
- Element2
Each type - has different properties and methods:
Collection
- getChilds()
- getOprion()
Element1
- getOprion2()
- isOption3()
Element3
- getOprion4()
At first I thought to use Composite, but in this case this option is not suitable, to implement different logic - you need to implement different entity classes inheriting the interface, but this option is not flexible, and still I want to distinguish so that the structure given by Parser does not have logic, but all actions occurred in separate Service.
The only option that comes to mind is:

<?php

interface Parser
{
    public function parse(string $input): Collection;
}

interface Collection
{
    /**
     * @return (Collection|Element1|Element2)[]
     */
    public function getChildren(): array;
    public function getOption(): bool;
}

interface Element1
{
    public function getOption1(): bool;
}

interface Element2
{
    public function getOption2(): string;
    public function getOption3(): string;
}

class Service
{
    public function do(Collection $collection)
    {
        foreach ($collection->getChildren() as $child){
            if($child instanceof Collection){
                //...
            }

            if($child instanceof Element1){
                //...
            }

            if($child instanceof Element2){
                //...
            }
        }
    }
}

How long is this option? In which direction can you look?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question