JasonDaly.name

PHP, Ruby, Symfony, Rails, Doctrine, MooTools. Web Development.

Posts tagged with "markdown"

March 10, 2010

Markdown and Doctrine_Record - Re-Parsing Data Only When Necessary

To prevent user-generated content formatted with Markdown from being re-parsed by the Markdown parser every time it is called to be rendered as HTML, it is best practice to store the parsed/converted HTML version of the original Markdown text alongside the original Markdown markup. The parsing of this user-generated content can only be done as necessary using Doctrine’s preSave event listener.

First, the schema for the table can be very simple.

Message:
  columns:
    message:
      type: text
      notnull: true
    raw_message:
      type: text
      notnull: true

The raw_message field will contain the Markdown text as entered by the user. The message field will contain the converted HTML equivalent of the user-generated Markdown syntax.

When saving the record with Doctrine, only the raw_message field needs to be set manually.

$message = new Message();
$message->setRawMessage($some_posted_form_message);

$message->save();

Finally, in the Message class (an implementation of Doctrine_Record), a preSave() event listener is added to conditionally parse the user-generated Markdown into HTML and store it to the message field.

class Message extends BaseMessage {

  public function preSave($event){
    if (!$this->exists() || array_key_exists('raw_message', $this->getModified())) {
      $markdown = new MarkdownExtra_Parser();
      // strip all HTML tags
      $value = htmlentities($this->raw_message, ENT_QUOTES, 'UTF-8');

      $this->message = $markdown->transform($value);
    }
  }

  // ...

}

Now, whenever a Message is saved, if the raw_message field value has been changed, it will be re-parsed, converted to HTML and stored into the message field.

Tags: markdown Doctrine Doctrine_Record PHP