Zachęcam do przejrzenia wszystkich: Wzorce projektowe PHP
Idąc po najniższej linii oporu:
a) Value Object
class Email
{
private $email;
public function __construct($email)
{
if (strpos($email, '@') === false) {
throw new InvalidArgumentException('This does not look like an email');
}
$this->email = $email;
}
public function __toString()
{
return $this->email;
}
}
b) Adapter
abstract class Logger
{
private $formatter;
public function getFormatter()
{
if($this->formatter === null) {
$this->formatter = new NullFormatter(); // NullObject Pattern, patrz niżej
}
return $this->formatter;
}
public function setFormatter(FormatterInterface $formatter)
{
$this->formatter = $formatter;
}
public function log($level, $message) {
$log = $this->getFormatter()->format($message, $level, time());
$this->logInternal($log);
}
protected abstract function logInternal($message);
}
final class FileAdapter extends Logger
{
private $filename;
public function __construct($filename)
{
$this->filename = $filename;
}
protected function logInternal($message)
{
file_put_contents($this->filename, $message);
}
}
// final class SyslogAdapter extends Logger {}
// final class StreamAdapter extends Logger {}
// final class SentryAdapter extends Logger {}
// itd..
c) Null Object
interface FormatterInterface {
public function format($message, $type, $timestamp);
}
final class NullFormatter implements FormatterInterface {
public function format($message, $type, $timestamp)
{
return $message;
}
}
final class FileFormatter implements FormatterInterface {
private $format = "[%s][%s] %s";
public function format($message, $type, $timestamp)
{
return sprintf($this->format, date('Y-m-d H:i:s', $timestamp), $type, $message) . PHP_EOL;
}
}
Teraz gdziekolwiek w aplikacji, gdzie masz emaila:
$logger = new FileAdapter('test');
$logger->setFormatter(new FileFormatter());
$emailStr = "niepoprawny email";
try {
$email = new Email($emailStr);
} catch (Exception $e) {
$logger->log('ERROR', $e->getMessage() . ": " . $emailStr);
}
Nawiasem mówiąc dochodzi jeszcze wzorzec strategia (wydaje mi się, że można to pod to podciągnąć), a tymi strategiami są formatery.