Created
September 6, 2013 07:45
-
-
Save asgrim/6460739 to your computer and use it in GitHub Desktop.
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 | |
namespace My\Logger; | |
use Psr\Log\LoggerInterface; | |
trait LoggerAwareTrait | |
{ | |
/** @var \Psr\Log\LoggerInterface */ | |
protected $logger; | |
/** | |
* Sets a logger. | |
* | |
* @param \Psr\Log\LoggerInterface $logger | |
*/ | |
public function setLogger(LoggerInterface $logger) | |
{ | |
$this->logger = $logger; | |
} | |
/** | |
* Gets a logger. | |
* | |
* @return \Psr\Log\LoggerInterface | |
*/ | |
public function getLogger() | |
{ | |
return $this->logger; | |
} | |
} |
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 | |
namespace My\Things; | |
use My\Logger\LoggerAwareTrait; | |
use Psr\Log\LoggerAwareInterface; | |
class MyClass implements LoggerAwareInterface | |
{ | |
use LoggerAwareTrait; | |
public function someMethod() | |
{ | |
$logger = $this->getLogger(); | |
$logger->info('foobar'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Everyone is telling me traits are bad. This is the only use case I've seen for traits. Is there a better way of doing this type of DI without using traits (or literally implementing setLogger/getLogger in EVERY class - copy and pasting basically).
I've seen this pattern used a few times, for example
Zend\ServiceManager\ServiceLocatorAwareTrait
,Zend\EventManager\ProvidesEvents
andZend\I18n\Translator\TranslatorAwareTrait
(among others): I'm just wondering if there's a better way?