Skip to content

Instantly share code, notes, and snippets.

@armetiz
Created January 18, 2013 11:12
Show Gist options
  • Save armetiz/4563971 to your computer and use it in GitHub Desktop.
Save armetiz/4563971 to your computer and use it in GitHub Desktop.
Simple text formatter with name parameter
<?php
class TextBuilder {
private $template;
private $parameters;
public function __construct($template = null, array $parameters = null) {
$this->template = $template;
$this->parameters = $parameters ? $parameters : array();
}
public function setParameter($name, $value) {
$this->parameters[$name] = $value;
}
public function getParameter($name) {
if(array_key_exists($name, $this->parameters)) {
return $this->parameters[$name];
}
else {
return null;
}
}
public function getParameters() {
return $this->parameters;
}
public function setTemplate($template) {
$this->template = $template;
}
public function getTemplate() {
return $this->template;
}
public function render() {
if(is_null($this->template)) {
throw new \RuntimeException("Define a template first");
}
return str_replace(array_keys($this->parameters), $this->parameters, $this->template);
}
}
$textRender = new TextBuilder("Hello :name. How are you ? :name I need to talk to you");
$textRender->setParameter(":name", "john");
echo $textRender->render(); // Hello john
echo "\n";
$textRender = new TextBuilder();
$textRender->setTemplate("Hello :name. How are you ?");
$textRender->setParameter(":name", "john doe");
echo $textRender->render(); // Hello john
echo "\n";
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment