Skip to content

Instantly share code, notes, and snippets.

@asgrim
Created September 6, 2013 07:45
Show Gist options
  • Save asgrim/6460739 to your computer and use it in GitHub Desktop.
Save asgrim/6460739 to your computer and use it in GitHub Desktop.
<?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;
}
}
<?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');
}
}
@asgrim
Copy link
Author

asgrim commented Sep 6, 2013

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 and Zend\I18n\Translator\TranslatorAwareTrait (among others): I'm just wondering if there's a better way?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment