Last active
February 6, 2018 12:26
-
-
Save bcremer/9cf6c5a9870e215cf96804390b5f2b89 to your computer and use it in GitHub Desktop.
Only ever return implementations of an interface as an anonymous class coming from a factory.
This file contains hidden or 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 | |
/** | |
* https://twitter.com/Ocramius/status/959405445260726272 | |
* only ever return implementations of an interface as an | |
* anonymous class coming from a factory. | |
*/ | |
namespace Example; | |
use Psr\Log\LoggerInterface; | |
use Psr\Log\NullLogger; | |
require __DIR__ . '/vendor/autoload.php'; | |
interface StringModifier | |
{ | |
public function modify(string $name): string; | |
} | |
final class UpperCaseStringModifier | |
{ | |
private function __construct() {} | |
public static function create(LoggerInterface $logger): StringModifier | |
{ | |
return new class ($logger) implements StringModifier { | |
private $logger; | |
public function __construct(LoggerInterface $logger) | |
{ | |
$this->logger = $logger; | |
} | |
public function modify(string $name): string | |
{ | |
$this->logger->debug('some log'); | |
return strtoupper($name); | |
} | |
}; | |
} | |
} | |
$logger = new NullLogger(); | |
$stringModifier = UpperCaseStringModifier::create($logger); | |
echo $stringModifier->modify('Ocramius is crazy'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment