B
B
Bogdan Khvalko2022-01-21 12:37:52
PHP
Bogdan Khvalko, 2022-01-21 12:37:52

How to properly design class substitution?

I have several classes, let's say two:

class Keyboard {
  
    public function add(string $key):void
    {
        //реализация
    }
  
  
  //другие методы
}

class Message {
  
    public function send():bool
    {
        //реализация
    }
  
  //другие методы
}

I already use them in the project. And then suddenly I need to replace these classes with others, or rather not the class itself, but its implementation. Advise ready-made solutions.

Ps: initially I wanted to stir up a layer class and inherit it, but the question arose of how to implement a quick substitution.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Anton, 2022-01-21
@quitting

Replace classes with interfaces, pass an instance of the class that implements the interface as a parameter to the "handler". https://habr.com/ru/post/350068/

R
rPman, 2022-01-21
@rPman

In php, if you don't type check the object instances used, the methods are called by name as is, i.e. it is enough that the object instance class has methods with the same names that you use, and a compatible order of parameters, and everything will work.
Well, if you control the type everywhere, use the interface-implementation pattern, specifying the interface as types.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question