@darrion.kuhn
Dependency Injection is a design pattern used to achieve decoupling in object-oriented programming. In PHP, you can use Dependency Injection by following these steps:
Here's an example implementation of the Dependency Injection pattern in PHP:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
interface LoggerInterface { public function log(string $message); } class FileLogger implements LoggerInterface { public function log(string $message) { // Write the message to a file } } class User { private $logger; public function __construct(LoggerInterface $logger) { $this->logger = $logger; } public function register() { // Register the user $this->logger->log('User registered'); } } $fileLogger = new FileLogger(); $user = new User($fileLogger); $user->register(); |
In this example, we have an interface LoggerInterface
which defines the log()
method. We then create a FileLogger
class which implements the LoggerInterface
.
The User
class has a dependency on the LoggerInterface
. It accepts the dependency through its constructor and stores it in a private property. When the register()
method is called, the User
class logs a message using the injected logger.
Finally, we create an instance of the FileLogger
and pass it to the User
class when we create an instance of it. This way, the User
class is decoupled from the implementation details of the logger and can easily be tested or swapped out with a different logger implementation.