Answer the question
In order to leave comments, you need to log in
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
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)
....
}
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 interfaceswords 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 exampleshttps://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.
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 questionAsk a Question
731 491 924 answers to any question