Skip to content

Instantly share code, notes, and snippets.

@mathiasgrimm
Last active December 23, 2016 11:41
Show Gist options
  • Save mathiasgrimm/7abad553a9be60971c36c4cdff11aad8 to your computer and use it in GitHub Desktop.
Save mathiasgrimm/7abad553a9be60971c36c4cdff11aad8 to your computer and use it in GitHub Desktop.
<?php
interface HandlerInterface
{
public function handle($message);
}
interface BufferedHandlerInterface extends HandlerInterface
{
public function flush();
}
interface LoggerInterface
{
public function log($message);
}
class FileHandler implements HandlerInterface
{
protected $filePath;
public function __construct($filePath)
{
$this->filePath = $filePath;
}
public function handle($message)
{
file_put_contents($this->filePath, $content, FILE_APPEND);
}
}
class BufferedFileHandler extends FileHandler implements BufferedHandlerInterface
{
protected $messages = [];
public function handle($message)
{
$this->messages[] = $message;
}
public function flush()
{
$messages = implode("\n", $this->messages);
parent::handle($messages);
$this->messages = [];
}
}
class Logger implements LoggerInterface
{
private $handlers;
public function addHandler(HandlerInterface $handler)
{
$this->handlers[] = $handler;
}
public function log($message)
{
foreach ($this->handlers as $handler) {
$handler->handle($msg);
}
}
}
class SomeService
{
private $logger;
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
public function doSomething()
{
for ($i=0; $i<1000000; $i++) {
// do something ...
$this->logger->log("Processing entry {$i}");
// .. somethin else
}
}
}
// index.php
$fh = new FileHandler('./logs/non-buffered.log');
$bfh = new BufferedFileHandler('./logs/buffered.log');
$logger = new Logger();
$logger->addHandler($fh);
$logger->addHandler($bfh);
$service = new SomeService($logger);
$service->doSomething();
$bfh->flush();
@archit12
Copy link

I have an idea, it could be stupid too.
Maybe have handle() and flush() in both Handlers and set a property bufferSize with $bufferSize = 1 in FileHandler and $bufferSize = some_value and call flush() in handle() once the buffer reaches the size?
for the last batch you'll have to call handle() after the end of the loop. This way the Service will call both the Handlers in the same way.

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