Skip to content

Instantly share code, notes, and snippets.

@bcremer
Last active February 6, 2018 12:26
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bcremer/9cf6c5a9870e215cf96804390b5f2b89 to your computer and use it in GitHub Desktop.
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.
<?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