P
P
Pavel Konkin2018-06-26 14:45:33
PHP
Pavel Konkin, 2018-06-26 14:45:33

What is the typical solution to apply in this situation?

Good afternoon. Please tell me a variant of the correct design of such an architecture or help me decide on a pattern.
It is necessary to implement a similar class architecture. Naturally, now it is implemented with an error, but the meaning is clear. It is necessary that each concrete class takes an instance of the corresponding class as an argument.

abstract class Animal
{
    abstract public function say();
}

class Wolf extends Animal
{
    public function say()
    {
        return 'woooof';
    }
}

class Bear extends Animal
{
    public function say()
    {
        return 'aaagrh';
    }
}

abstract class Hunter
{
    abstract public function hunt(Animal $animal);
}

class WolfHunter extends Hunter
{
    public function hunt(Wolf $wolf)
    {
        return 'where is a wolf?';
    }
}

class BearHunter extends Hunter
{
    public function hunt(Bear $bear)
    {
        return 'where is a bear?';
    }
}

Thanks in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Grishin, 2018-06-26
@vesper-bot

The principle L from the SOLID list is violated here, the hunt () functions must take Animal as input, and process any Animal (in their own way, but any). And so, to combine unrelated classes, it is correct to use interfaces - if it is required, i.e. you need to make it like var hunters:array of Hunter. (PHP doesn't seem to know how to interface - then check with if ($animal is Wolf){...}) And if you don't need it, implement independent pairs of classes.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question