#native_company# #native_desc#
#native_cta#

Building Web Apps with the Limonade PHP Framework Page 2

By W. Jason Gilmore
on May 3, 2011

Listing Blog Posts

Although Limonade is perfectly capable of talking to a database, I’d rather manage the entries in a series of text files, and use Limonade to retrieve and parse these files. Each file is named in accordance with the current date, such as 2011-04-12.txt. The following posts route will retrieve all of the file names found in a directory named entries, sorting the file names in reverse chronological order, and create user-friendly versions of those dates:

dispatch('/posts', 'posts');
function posts()
{
  // Retrieve all of the entries from the entries directory
  foreach (glob("entries/*.txt") as $filename) {
      $filenames[] = basename($filename, '.txt');
  }
  // Sort the files backwards according to date
  krsort($filenames);
  // Iterate over each file name and 
  // create a user-friendly version of the date
  foreach ($filenames AS $filename)
  {
    $date = new DateTime($filename);
    $dates[] = array('name' => $filename, 
                     'date' => $date->format('F j, Y'));
  }
  // Set the $dates variable to the view scope
  set('dates', $dates);
  return html('posts.html.php', 'layout.html.php');
}

Loading the /posts route produces output similar to that shown in Figure 2.

Limonade PHP Framework
Figure 2. Displaying Blog Entries with Limonade Framework

Displaying a Blog Entry

Each link has been formatted to look like this:

http://dev.example.com/view/2011-04-13

Therefore the only remaining task is to create the view route, passing the date into the route so we can retrieve the entry:

dispatch('/view/:date', 'view');
function view()
{
  $date = params('date');
  $entry = file_get_contents("entries/".$date.".txt");
  set('entry', nl2br($entry));
  return html('entry.html.php', 'layout.html.php');
}

Now click on one of the links and the entry will be displayed within the browser window!

Conclusion

The Limonade microframework makes building dynamic websites dead simple, capable of accomplishing quite a bit with a few scant lines of code. Are you doing anything interesting with Limonade? Tell us about it in the comments!

About the Author

Jason Gilmore is founder of the publishing, training, and consulting firm WJGilmore.com. He is the author of several popular books, including “Easy PHP Websites with the Zend Framework”, “Easy PayPal with PHP”, and “Beginning PHP and MySQL, Fourth Edition”. Follow him on Twitter at @wjgilmore.