Category Archives: PHP

Smarty for PHP – Caching

I never thought I would need to worry about caching. Hardware these days is fast. But the more I thought about efficiency the more I realized that my pages don’t change that frequently so why go through the overhead of connecting to a database on every page load? Or for that matter, why load a static file, unserialize something stored, recalculate the ‘year’ in the copyright tag. For that matter, why perform any of these tasks every time the page is loaded when they may change infrequently? Well, luckily Smarty has caching built-in and I found a use for it.

From the Smarty web site:
Here’s where I get happy. I never thought I would need to worry about caching. Hardware these days is fast. But the more I thought about efficiency the more I realized that my pages don’t change that frequently so why go through the overhead of connecting to a database on every page load? Or for that matter, why load a static file, unserialize something stored, recalculate the ‘year’ in the copyright tag. For that matter, why perform any of these tasks every time the page is loaded when they may change infrequently? Well, luckily Smarty has caching built-in and I found a use for it.

From the Smarty web site:

Caching: Smarty provides fine-grained caching features for caching all or parts of a rendered web page, or leaving parts uncached. Programmers can register template functions as cacheable or non-cachable, group cached pages into logical units for easier management, etc.

Wow. Seems like a lot is covered. I can cache the whole page if I want. I can cache the whole page EXCEPT for a dynamic element like a banner ad, or I can register a dynamic function that picks a random Amazon.com book in the midst of an otherwise static page – all while keeping to Smarty’s idea of separating the logic and presentation.

Database queries and caching with Smarty

In a recent project I had to put a full-text search form on a web site. This wasn’t easy because it was searching through HTML files – a mini Google if you will. The trouble was the function that creates the ‘headline’ clip from the page (that highlights the search terms) seemed to be very slow. After asking mailing lists and spending days in the manual I could not get the problem solved. I had a deadline to meet and could not change it.

What I did was implement the current version of the search – problem and all – and used Smarty caching to save load on the system (and save my bottom). Luckily there was an HTML list (links) of popular queries, and a mechanism to record the queries. I used a script to regenerate those queries and use Smarty to cache the results. The only time we had to connect to the DB and perform the query was the first time a search was performed. This was a lifesaver, and it dropped the time to query down to a value that was barely perceptible. Mainly because it rarely had to query the db!

Further Database Queries and Smarty

Another benefit of Smarty caching can be recognized when you have complex queries. We must all work within boundaries. Sometimes you don’t get the chance to select a better DB system, or add hardware. In other words, you work with what you have and find a way to make it better.

I once had to write a page for an e-commerce store that would display the top sellers. Not just top sellers, but three columns of top sellers. There was the top sellers this week, top sellers this month, and top sellers of all time. These changed because of frequent specials and of course, the time spent in the store made a difference in the rank. It was hard to push a product introduced a month ago and put on special this week unless it showed up in the list of top sellers for this week.

But how do you go about that? Performing the SQL queries is easy enough but getting a result back is hard. Really, there is no reason to perform this query 2000 times a day as people drift in and out of the store. The problem is, the store was on a shared host with a dedicated remote database. There was time associated in the connect of course but even more important was the 3 complex queries. Also, they chose a shared host meaning they could not just throw money at the hardware to speed up their queries.

The only problem query in this scenario was the all time best sellers top list. Of course we have no trouble with the others because indices on the right columns make those a snap. But how about sorting through sales records for 6 years and getting a rank for the top sellers? Owch. That can take a long time. Well, a long time from the perspective of a web surfer.

Four seconds to be exact. Can you imagine that? Can you imagine a few people at the same time making that query? That’s the kind of thing that makes machines grind to a halt. You’ll see that type of thing in some of the recent content management systems (CMS) that don’t use any caching. I recently tested one that could only support about 4 users at a time on modest hardware because of their extensive use of, in my opinion, many unnecessary queries.

With Smarty though, this query becomes a non-issue. I ran a script early in the morning that erased the cache for that page and requested it again which regenerated the cache page. You can do this with a simple call to wget or lynx. Problem solved. One query a day is all it took. And because the page showed top sellers for this week and this month there was no need to have it in real time. Even if it was in real time there is no reason to think a sale today would affect sales from the last 6 years in such a dramatic way that it would push an item up the list all the way from the bottom to the top. But even if you wanted the ‘this week’ top sellers list in real time, or a list for the best sellers today, you would just include a dynamic block in Smarty, and only that section would be generated on that page load, the rest of the real hard queries would be cached.

With that in mind, Smarty caching took a script that I wasn’t even able to execute due to the time involved, and turned it into a vital part of the store that helped increase visibility for the top selling items. It also took that 4 second query down to a page load time of 0.4 seconds.

Database connects

As mentioned above, the shared host used a remote database. That’s a great thing to do actually, but it can kill you on the connect. Of course the connect is what kills you on most databases as long as everything else is up to par.

But why connect to the database at all? If your content is cached you don’t need to, again saving that overhead and speeding up your display that much faster. If you do need to connect to a database to record some statistics or similar, you can do it after the page is sent to the browser by putting your database connect and your subsequent queries in the part of your script AFTER the call to $smarty->display() – meaning the page has already been sent to the browser.

Summary

Smarty has a multi-faceted approach to caching. Smarty first takes your template page and caches that as a PHP file. That means it doesn’t have to parse the template on every request. If you choose to use the other caching features, Smarty will then cache the actual output of your page, saving all of the overhead of dynamic files, but allowing you the ability to update the cache whenever you want.

Even if you don’t intend to use caching in any large way it is still a good idea to use Smarty to get acquainted with the idea of an intermediate cache. The Smarty cache will reduce the load on your hardware enabling you to enhance the end-user experience and decrease your dependence on bigger, more expensive hardware. It also allows you to grow your site(s) and traffic without having to worry about hitting the wall and taking the system down during a growth spurt, which can potentially harm revenue. In other words, a Smarty cache let’s you plan for the future. And as you’ve seen in my recent case, Smarty cache can help you get out of a bind when you are dependent on other developers and a timeline.

In short, there simply is no reason not to use a cache. Smarty allows you to implement only as much or as little caching as you like. As a professional PHP or web programmer you need to be efficient as well as effective, and part of being efficient means caching infrequently updated dynamic content.

Smarty for PHP – evil?

I was reading some PHP blogs last night just to pass the time when I came across one entitled something like “Smarty is evil.”

After reading the post I concluded that the author gave Smarty a fair shake, and indeed, acknowledged that this was his own opinion based on a first impression during a very short time examining the Smarty Templating system for PHP. In my opinion, I would consider this author to be a fair designer with logic because he is able to discern his own emotional opinion from the true facts. A trait hard to find in those who work with computers who are many times very opinionated and highly defensive. Kudos to the author for getting past that.

What disturbed me though, was the comments. A large number of comments, and the consensus of the commenter’s on the original post was that yes, Smarty is evil. For the most part, no one acknowledged having any more experience with Smarty than the author. Owch! Any one of those commentators would likely make a designer or programmer of questionable ability.

Let’s examine some of the comments (arguments against Smarty) and look at the facts of the Smarty Template system for PHP. For the record, I’ve been using Smarty since nearly it’s inception (about 7 years at the time of writing).

Using a templating languages with PHP makes no sense.

I guess that depends what type of coder you are. And what type of employee or contract worker you’d be. And how much time you enjoy spending maintaining your code.

I worked as a full-time PHP programmer for a web host. For the most part I was assigned a project and told to ‘go.’ The thing I dreaded was having to edit some of the legacy code. This following scenario is very typical working with people who think they are ‘programmers.’ Their entire public site, everything you see, the marketing literature, the sign up form, the credit card processing, the SQL queries, the mailing list…..everything….was contained in ONE FILE – the index.php file.

I’ve seen this done everywhere since then and can’t believe people actually do this. I had to stare down a 10,000 line minimally commented mega-file including PHP and HTML and try to determine where a particular element was. Some people would call this ‘job security’ for the idiots that wrote it, but most people would just balk at their abilities.

The bottom line is, this is the kind of garbage you see with PHP. People using it from the perspective of ‘personal homepage’ and applying it to ‘online business web application mega-project.’ You need a different mind set when working with a customer control panel than you do if you are just trying to display the current date on your homepage. That’s why the above comment, “Using a templating languages with PHP makes no sense” is absolute bunk.

Escaping in and out of php with the short open tags is fine for some things but in the above stated file it was sheer nonsense. We perform some logic in php, then escape out of PHP to print it, then back into PHP in the middle of the HTML to echo a variable, then out of PHP to HTML, then out of HTML to PHP to perform more logic. It is a mess, and it is eating the time of programmers who think this is the way we do business.

Smarty does the opposite. It follows a very nice model that allows you to separate your logic from your display. The way it was meant to be. I’ve used Smarty on the command line to generate a dynamic e-mail for a mailing list, I’ve generated .smil files, and I’ve used it to generate HTML and it works great. Tracking down errors is very quick because you can look at one file for the logic, and the other file for the display. But the error you found is not in both, it’s in one or the other and you know by looking at the results where it is. Another nice thing is that it removes that mammoth 100k of HTML from your code and puts it somewhere else. Your logic becomes very short and scan-able. How nice that is.

What’s moronic is that people go to all this trouble building templating systems when all you really need is extract(). Sad, really.

I don’t think I want to get into that one.

The authors of the book ‘Web Application design with PHP 4’ had a good idea when they basically said, don’t try to roll your own templating system when a good one already exists. Bottom line, you didn’t think of everything, and you don’t have the team of designers they did, and in the case of the comment above, you didn’t think of security like they did. Rolling your own is ok if you are a student looking to experiment, learn, analyze and debug. Rolling your own is not ok when you have limited time, a boss or a client to answer to and an actual project to complete – you know, the reason you are using the template system in the first place.

Smarty is really a waste of time.

Quite contrary.

I have been working with Smarty for 7 years now, pretty much since it’s introduction and I can say, in every instance, Smarty has reduced the time it takes to develop an app. Even something as simple as a contact form interface, a single page with two possible outcomes.

Yes, Smarty takes time to learn, but didn’t PHP? If I was developing Smarty I would have done things a little different to reduce the time on the learning curve, and maybe that’s a possibility in the future. But indeed, a template system in general and Smarty in particularly is not a waste of time, and will speed up your development time thanks to the separation of logic and display. Once you consider Smarty’s incredible template and page caching mechanisms you’ll see it saves you resource time as well.

Why? I don’t really know, but I can tell you that when you don’t have the possibility of escaping PHP into HTML whenever you want you tend to think more in Data Structures. You create a real, formatted data structure and pass it along to the template via Smarty. When you do that, you tend to have better, more reusable code. More reusable code tends to mean less time programming.

The other thing I’ve found is that a shorter file size means less code, means easier scanning. There have been several studies done on formatting and productivity and it is easy to see why this works. If you can scan your code then you don’t have to spend time thinking ‘what is going on here?’ With no escapes in and out of PHP and HTML your brain doesn’t shift either. It stays in one mode the whole way and that, albeit subconsciously, seems to speed you up. In many of the scripts I do now, the logic takes up less than one screen on my editor, and that is sheer joy.

Summary

Overall I’ve been very happy with the Smarty Template Engine for PHP and I will continue using it on each project I do. In fact, on one project I was in such a rush that I chose to leave it off. Big mistake. It took me longer to complete. Less than a week after the project was finished and went live I was coming back to re-do it in Smarty. I’ve been using it for about 7 years and I keep choosing it again and again. If you enjoy shorter code, separate logic and display, caching and super fast applications with low overhead then Smarty is your choice for PHP.