Skip to content

Instantly share code, notes, and snippets.

@teroyks
Last active August 8, 2019 14:39
Show Gist options
  • Save teroyks/5f20c08fc6ebc8b3b56ca59fff897bcb to your computer and use it in GitHub Desktop.
Save teroyks/5f20c08fc6ebc8b3b56ca59fff897bcb to your computer and use it in GitHub Desktop.
PHP closure usage example
<?php
$myReport = new MyReport;
$myReport->report();
// 2019-08-08: MyReport started
// 2019-08-08: using logReport
// 2019-08-08: Reporting: First report
// 2019-08-08: Reporting: Second report
<?php
/**
* Does the actual logging.
*/
class Log
{
/**
* Writes a message to the log.
*
* @param string $msg
*/
function add(string $msg)
{
$now = date('Y-m-d');
error_log("$now: $msg");
}
}
<?php
/**
* Creates a report using the Reporter class.
*
* Defines that logging should be done using the Log object.
* Passes a logger closure to the Reporter object.
* Reporter doesn't know or care about the type of the logger object.
*/
class MyReport
{
/** @var Log Logger object */
private $log;
function __construct()
{
/** @var Log log */
$this->log = new Log;
$this->log->add('MyReport started');
}
/**
* Creates a report.
*/
function report()
{
/**
* Wraps logging a message.
*
* @param string $message
*/
$logReport = function (string $message) {
$this->log->add($message);
};
$logReport('using logReport');
$reporter = new Reporter($logReport);
$reporter->report('First report');
$reporter->report('Second report');
}
}
<?php
/**
* Reports on stuff (TBD).
*
* Logs reported stuff using given logger closure.
* Does not know anything about the used logging class.
*/
class Reporter
{
/** @var Closure Function that does the logging */
private $loggerFunc;
/**
* Reporter constructor.
*
* @param Closure $logger Logging function (message: string): void
*/
function __construct(Closure $logger)
{
$this->loggerFunc = $logger;
}
/**
* Reports on stuff.
*
* @param string $msg Message to report
*/
function report(string $msg)
{
$log = $this->loggerFunc;
$log("Reporting: $msg");
// do actual reporting
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment