Question

I was watching an OOP lesson with such code:

class UsersConstroller {

    protected $userService
    protected $logger

    public function __construct {

        UserService $userService,
        Logger $logger
     }

}

What this class does is pass other class in the constructor, then it will assign them to variable, and they will be used with $this inside the class.

Is it wrong not to pass those classes in the constructor, and instantiate them directly where needed in the class code, like this:

( new Logger )->logMessage("this is a message")

This way, passing a lot of instances of other classes to the class would be avoided.

Was it helpful?

Solution

What is described in the example you provided is called Dependency Injection and is generally considered a good practice.

Instantiating the objects of the class whenever you need them can result in degradation of performance, memory fragmentation and greater memory consupmtion in managed languages (it would take time for garbage collector to release some of those references). Not to mention that you would need to release that memory every time in unmanaged languages, which means there would be a big risk of memory leaks (somewhere you would forget to write delete logger).

As a matter of fact, I can see no valid scenario where something like (new Logger)-> logMessage("this is a message") would be used, apart from the situation where logger would be a local variable, i.e. without any impact on other methods of that class.

In this particular case, though, considering what logger tipically does, there is absolutely no scenario where doing something like this is a good practice. Logger class should be able to handle concurrent writing in the same log file from several threads. If you instantiate a new class each time, this would be very hard to achieve.

Licensed under: CC-BY-SA with attribution
scroll top