Writing your own

Templates are not something I generally recommend because there are a number of potential pitfalls that are all-to-easily fallen into. However, in order to make your life easier, I've put together a short list of the hints and tips I've learnt the hard way over the years so that you can learn from them:

  1. Start small, and work your way up. If you try to put together a list of all the different things you want to do at the beginning, you're likely to make the system more complex. Instead, think of the most important four or five template objects, then do the rest as you encounter a need for them.

  2. Using str_replace() for templates can be optimised by passing in the parameters as arrays.

  3. Use a code caching system or you'll regret it - templates are notoriously slow devices, and it's cheaper to get a decent code cache than it is to just buy more servers.

  4. Don't be afraid to split up your system into multiple smaller files for easier manageability; template systems have a tendency to get more complex with each code update, and anything that helps is a good thing.

  5. The best template systems I've seen have been object-oriented - it's an entirely personal decision how you code yours, but do consider OO first.

  6. If you can statically cache pages, do so. This makes for a big performance boost.

  7. Although it's possible to run complex regular expressions for your template interpretation, it causes a real speed hit: evaluate each one carefully.

 

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: Summary >>

Previous chapter: When not to use templates

Jump to:

 

Home: Table of Contents

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