Last active
December 18, 2015 13:28
-
-
Save MattKetmo/5789695 to your computer and use it in GitHub Desktop.
Inject logger in objects using dependency injection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require __DIR__.'/vendor/autoload.php'; | |
use Psr\Log\LoggerInterface; | |
use Psr\Log\NullLogger; | |
use Monolog\Logger; | |
interface LoggerAwareInterface | |
{ | |
public function setLogger(LoggerInterface $logger); | |
} | |
// Foobar is an example of object using a logger | |
class Foobar implements LoggerAwareInterface | |
{ | |
protected $logger; | |
public function __construct() | |
{ | |
$this->logger = new NullLogger(); | |
} | |
public function setLogger(LoggerInterface $logger) | |
{ | |
$this->logger = $logger; | |
} | |
public function doFoo() | |
{ | |
$this->logger->debug('I\'m doin foo!'); | |
// Doin some foo process... | |
} | |
} | |
// Extend the DIC to do the hook | |
class Container extends Pimple | |
{ | |
protected $logger; | |
public function __construct($debug = false) | |
{ | |
if ($debug) { | |
$this->logger = new Logger('test'); | |
} | |
} | |
public function offsetGet($id) | |
{ | |
$object = parent::offsetGet($id); | |
// Here is the hook: inject the logger | |
if (null !== $this->logger && $object instanceof LoggerAwareInterface) { | |
$object->setLogger($this->logger); | |
} | |
return $object; | |
} | |
} | |
$container = new Container(true); // try to change it to false | |
$container['foo'] = $container->share(function() { | |
return new Foobar(); | |
}); | |
$container['foo']->doFoo(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment