O
O
ObehanProger2019-02-26 06:21:11
OOP
ObehanProger, 2019-02-26 06:21:11

Why do you need to change the implementation of an interface?

Studying the topic of interfaces and dependency injection, I understood how all this is done and what is needed so that you can easily change the implementation of the interface, but it remains unclear why you need to change the implementation of the interfaces? Give examples preferably in laravel

Answer the question

In order to leave comments, you need to log in

3 answer(s)
W
Wentixon, 2019-02-27
@Wentixon

Everything is very simple! I will give an example on laravel, but the framework, of course, has nothing to do with this.
For example, Laravel has a caching package. Here is its interface. But of course, the implementation of caching can be completely different, you can configure it using the configuration. In one project, you can use some kind of redis, in another memcached, for example, and in tests, an array at all. In every modern framework there is a service container that can give you the desired implementation upon request of the desired interface (the implementation is tied to the interface in service providers).
Now imagine that you are making a service (class) and it needs to cache something. And do it like this

class RemoteApi {
    public function _construct(RedisCache $cache)
    ....
}

I think you can see for yourself what the problem is. This class will only work with radishes. Now imagine that there are a lot of such classes that use the radish cache. Then, when changing the cache storage, you will have to change and redo all of them, since their interfaces may be different.

N
Northern Lights, 2019-02-26
@php666

dependency injection, I understood how all this is done and that it is necessary so that you can easily replace the implementation of the interface, but it remains unclear why you need to change the implementation of the interfaces
words are in bold. not to change, but to replace one implementation with another - this is how to put spare part A instead of spare part B on a conditionally identical threaded connection. and not to do peeling. so clearer?
Give examples
https://ru.wikipedia.org/wiki/%D0%92%D0%BD%D0%B5%D... - substitution in the database configuration object example, as an example. you can instantiate a bunch of objects to work with the database, but with different connections to different databases.

D
Dmitry, 2019-02-26
@Compolomus

An example in the same Laravel, see how interfaces are substituted when working with different databases
An example is not from Laravel
There is, for example, a cacher, it can have different storage
Here is a list of implementations of one interface
https://github.com/topics/psr-16

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question