Skip to content

Instantly share code, notes, and snippets.

@madfriend
Created March 15, 2012 20:08
Show Gist options
  • Save madfriend/2046553 to your computer and use it in GitHub Desktop.
Save madfriend/2046553 to your computer and use it in GitHub Desktop.
Lazy Strings class
<?php
// accepts default string and test function.
// test function is tweaked everytime object of class LazyStrings is casted to string,
// if test function returns FALSE/NULL default string is returned, otherwise the result of
// test.
class LazyString {
private $_default, $_tweak;
public function __construct($default_string, $tweak) {
list($this->_default, $this->_tweak) = array($default_string, $tweak);
}
public function __toString() {
if ($this->_tweak instanceof Closure) {
$result = call_user_func($this->_tweak);
return ($result!==NULL && $result!==FALSE) ? $result : $this->_default;
}
// TODO: accept callbacks in strings ('checkMyVariable') and arrays of
// two types: array($someObj, 'method') and array('someClass', 'someStaticMethod')
return $_default;
}
}
@madfriend
Copy link
Author

This is extremely useful in the following case:

<?php

// some Closure which generates HTML from MD
$myDescriptionFieldPreprocessor = Options::get('someModel.description.preprocessor'); 

$myMarkdownDescription = new LazyString($someModel->fetchOne(/*...*/)->description, $myDescriptionFieldProcessor);

// And.. forget about the routine of generating HTML from Markdown! 
// It will be done implicitly (while rendering the template, as an example)
?>

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