Making an object-oriented messageboard

Owing to the vast amount of functionality you can cram into something so seemingly simple as a messageboard, it's a prime candidate for object-orientated programming. For example, rather than writing lots of complex code to print out the message index, wouldn't it be much easier to write this:

$mb = new messageboard("general");
$mb->setStyle($mb::StyleThreaded);
$mb->setLimit(50);
$mb->print();

Naturally you need to write all the back-end code to do those things, but you'll find it actually saves you a huge amount of work to program APIs to access your data rather than wading in with custom SQL each time. For example, we could print a summary of new posts in a given messageboard with code like this:

$mb = new messageboard("general");
$mb->setStyle($mb::StyleGuestbook);
$mb->setLimit(5);
$mb->print();

As you can see, we've got a huge amount of code re-use here, which maximises productivity while minimising errors. All the code above was for a non-OOP messageboard, but all you need to do is find the common processes and abstract them to functions in order to convert it - it should take you maybe two hours if you give it a try, but the time savings for maintaining that code make the effort well worth it.

 

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Creating thumbnails >>

Previous chapter: Messageboard v2

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.