Skip to content

Instantly share code, notes, and snippets.

@yckart
Last active January 31, 2016 06:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save yckart/7067361 to your computer and use it in GitHub Desktop.
Save yckart/7067361 to your computer and use it in GitHub Desktop.
Log.module - A lightweight logging wrapper around ProcessWire's session message/error

Makes it easier to log/render errors and messages.

log notices

<? $log->message('Foo is not equal to bar.'); ?>
<? $log->error('Bar is not equal to foo.'); ?>

render all notices

<?= $log->render(); ?>

render specific notices

<?= $log->render('messages'); ?>
<?= $log->render('errors'); ?>

custom markup

<?= $log->render('', '<p class="%s">%s</p>'); ?>

get notices as array

<? var_dump($log->messages); ?>
<? var_dump($log->errors); ?>
<?php
class Log extends WireData implements Module {
/**
* getModuleInfo is a module required by all modules to tell ProcessWire about them
*
* @return array
*
*/
public static function getModuleInfo () {
return array(
'title' => 'Log',
'summary' => 'A lightweight logging wrapper around session message/error.',
'href' => 'http://yckart.com',
'version' => 1,
'singular' => true,
'autoload' => true
);
}
/**
* Initialize the module
*
* ProcessWire calls this when the module is loaded. For 'autoload' modules, this will be called
* when ProcessWire's API is ready. As a result, this is a good place to attach hooks.
*
*/
public function init () {
$this->fuel->set('log', $this);
$this->addHookProperty('Log::errors', $this, 'hookNotices');
$this->addHookProperty('Log::messages', $this, 'hookNotices');
}
/**
* Shows all logged notices
*
* @param EventObject $event
*/
public function hookNotices ($event) {
foreach(wire('notices') as $notice) {
$type = $notice instanceof NoticeError ? 'errors' : 'messages';
if ($event->method === $type) {
$out[] = $notice->text;
}
}
$event->return = $out;
}
/**
* Logs a message
*
* @param string|integer $text
* @param integer $flags
*/
public function ___message ($text = '', $flags = 0) {
wire('session')->queueNotice($text, 'message', $flags);
}
/**
* Logs an error
*
* @param string|integer $text
* @param integer $flags
*/
public function ___error ($text = '', $flags = 0) {
wire('session')->queueNotice($text, 'error', $flags);
}
/**
* Render the logs
*/
public function ___render ($type = '', $markup = '<div class="%s">%s</div>') {
foreach(wire('notices') as $notice) {
$class = $notice instanceof NoticeError ? 'errors' : 'messages';
if (!$type || $type === $class) {
$out .= sprintf($markup, $class, $notice->text);
}
}
return $out;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment