Posts Tagged ‘MVC’

PHP Optimization

February 12th, 2009
Comments Off

Many developers don’t really put much thought into code optimization. Frankly, their applications don’t see enough traffic for optimization to be much of an issue. However, regardless of your application’s actual needs and whether or not you are having speed issues, there are some good habits that you can develop that will either help you in a bind or just ensure that all of your applications are finely tuned machines.

Optimization can be frustrating at times. I am quite familiar with server systems, however, I do not consider myself a full-fledged systems admin. The more I learn, the more I realize I don’t know. I do know that finding the right balance between server and code optimization takes skill. Too much customization in either direction can make the code or server difficult to manage. Sometimes, throwing more hardware at the problem can do the trick, but this is usually just temporary as the problem usually multiplies itself by the number of servers your application is running on. Inversely, good optimization improves performance across all the servers the application is running on.

Typically, I figure that if a particular change makes something overly difficult to manage, then it probably is not worth doing, because there are usually other people involved and there is too much room for mistakes. I will sometimes break this rule for my own personal stuff since I am the only one involved. You need to decide at what point it becomes to difficult. Good documentation goes a long way.

Here are some of the things (using PHP as the example) that I will often do to optimize things at the software level, without going too far.

  • It’s good practice to use literal strings wherever possible. Using the doublequotes tells the parser to expect potential interpretable values in the string, slowing down processing just a bit. This can add up with HTML intensive applications.
  • Keep code files from getting too large. If two chunks of code are rarely used together split them into separate files so that PHP doesn’t have to load more code than necessary.
  • Keep file inclusions to a minimum. Inclusions require additional disk reads and adds more time to processing. Don’t go overboard and sacrifice code organization in the process… includes can be your friend. If the include makes sense, do it. MVC development often ignores this because of the nature of the methodology, but it is still a good practice to keep in mind whether using MVC or not.
  • Try to convert any uses of division to multiplication. Division eats up processing, especially if iterated several times. Example: instead of $var / 10 do $var * .1
  • Utilize break or continue to control code flow in loops, etc… If you review enough of your code, there are probably some areas where you are using a for() or foreach() that are running beyond their necessary iterations. In other words, you run the loop to accomplish a certain task or value, but the loop continues to run through all possible interations, even after the task or value is complete. Either find ways to use while() or use break or continue where possible.
  • Sometime a caching application can help ease unnecessary processing. TurkMM or APC can dramatically improve PHP processing speeds by keeping realtime code compiling to a minimum.
  • Other types of caching can be done using Memcached or other similar code. This type of caching can cache files, database results, large data objects, etc… If there is any data that requires processing that doesn’t change much between pages or between users, this type of caching can drastically speed up response times. This is not only helpful for bypassing unnecessary processing, but it can also limit your application’s need to hit the database. Memcached can be used on many levels of the application to reduce processing and web service request overhead. For example, a list of users may not change very often, so there isn’t a need to retrieve a fresh list upon every request. You could cache the list for 2 hours, for instance, and your application would only have to query the database for the list once every 2 hours, instead of every page load.
  • Only use SSL where necessary. SSL encryption slows the response of your application.
  • A browser will hold on to the connection with the webserver as long as it is waiting to receive data, hence requiring the webserver, in this case Apache, to standby until everything is processed and ready to send. In some cases, your data may not require the user to review anything afterward, so it may be a good thing to consider forking your code into multiple threads. This can be tricky, but if done properly, Apache will respond to the user faster, leaving connections open for other users and allowing the code to finish in it’s own time. There are also functions in PHP that allow you to check if the user’s browser is still responding to the connection and close the connection if needed.
  • When a database is involved, use good SQL and data handling processes. I won’t go into a lot of SQL specifics here, but the following are things to consider:
    • Only request the data you need from the database. The more data that is requested, the more that has to be sent across the wire and get parsed by the application.
    • When your application is done processing a large data set, it should release the result set to free up memory for other operations. If only parts of the data are needed for processing later in the request, those parts of the data can be copied to another data object while the original object is cleared. Most applications don’t work with large enough data sets to have this concern, but when you do, you’ll find that automatic garbage collection won’t be enough.
    • Most modern databases will allow you to combine multiple operations into a single SQL request. Taking advantage of this can GREATLY minimize your application’s overhead of going back and forth to the database. For example, you can combine multiple SELECT queries using UNIONs. You can do conditional INSERTs when you might normally do a SELECT, check the logic in your code, then do an INSERT. Take advantage of subqueries. Also, in some cases it can be beneficial to do a few large queries early in your application and avoid the several smaller ones that might be required later.
    • Take advantage of query caching and preparing if your database and code support this functionality.
    • When possible, have the database be on the same machine as the application. This introduces some scalability challenges (to be discussed at another time), but can be worth the effort, even with large, distributed applications. This will keep your code-to-database processing times VERY fast.
  • Keep what your store in sessions to a minimum. You can also use Memcached as a custom session handler between servers to replace database sessions across multiple servers, for improved performance.
  • When possible, “minify” your JavaScript, CSS and HTML. Keep the output to a minimum and write your code so that the browser will take optimal advantage of cached CSS, JavaScript and HTML
  • PHP is an interpreted scripting language. When it comes down to it, it can only move so fast. For larger applications that do a lot of processing, it can greatly decrease the system load to offload major processing to a program written using a compiled language such as C, C++, or yes, even Java. You can build an RPC interface to the compiled app using JSON, SOAP or XMLRPC. Service communication may take some overhead, but the compiled app will more than make up for it. Using this method allows you to keep your interface code flexible using PHP while gradually putting any labor-intensive operations on to something more suitable.

Doing any or all of these things will benefit your applications greatly and still keep your code manageable. This doesn’t address all of the innovative things you can do on the UI and client-side of an application to improve performance. Of course there is always more you can do, but this should get you started.

Development, PHP , , , ,

Smarty For Dummies

September 5th, 2008
Comments Off

Are Smarty Templates really that useful? Well, I have my opinions, but decide for yourself. I hope you’ll do a doubletake after reading this.

For a long time now, I’ve avoided using Smarty Templates as much as possible. Perhaps it’s the cheesy assuming name, or perhaps it’s that I like to keep my applications simple to deploy and free of unneeded dependencies. More than anything, I think it’s because templating has been a solved problem for me for some time now and I didn’t have the desire to fix what was not broken. 

A while back, I had the opportunity (tongue in cheek) to use Smarty Templates for an existing project I was working on, and I was able to evaluate its functionality, its proposed NEW paradigm and how it integrates into the development process. Now, by no means am I a Smarty expert now and I don’t know everything about its benefits, but for better or for worse, I have formed an opinion that seems to adequately describe the “reality” of Smarty Templates. They pretty much work about how I expected. No surprises there, but here are some things to think about. 

  • Smarty Templates are simply one way of implementing a template based system into a website. It adds another layer of processing to your development. It has the benefit of caching parts of the design so that processing is lessened.
  • The main idea behind any templating system or CMS is to provide separation between the various layers of development: design, site structure, basic logic, core libraries, etc… Some systems provide some basic separation and others provide many layers of separation. Smarty Templates aim to resolve a lot of the problems that come about with having multiple roles working on a site: designer, interactive developer, programmer, etc… Separation of these roles can often be difficult. I think much of this comes down to a core problem with the PHP community as a whole. PHP has become a very popular language but has also been adopted by a lot of people that are not programmers by trade. Thus, the lack of standards and experienced developers is not at the same level that you might find in other web or application language communities. Smarty Templates, although seen by many as a godsend, seems to be a temporary solution for a community that for the most part lacks the structure and standardization to solve the problem in a more appropriate way.
  • Smarty Templates allow you to build backend code, allows designers to build templates, and then allows the developers to hodge-podge them all together with a series of inclusions. This, like much of the PHP code I see on the web, lends itself to disasterous application structures and does not enforce a paradigm. I’m all for flexibility, but all Smarty Templates have done is add another arbitrary level of confusion on top of what is usually already messy code.
  • I understand that Smarty Templates is supposed to shelter core logic from the designer, allowing them to use a “templating language” to create the display. However, the Smarty language itself uses programming methodologies to display data. So, not only do you have programming on top of programming, but the designer still has a way to destroy the interface from lack of knowledge, understanding and perspective. If the interface looks wrong or breaks in some fashion, where do you go to fix the problem?
  • Smarty Templates were obviously created from a developers perspective. I am a developer with a design background and I have to say that with good understanding of both perspectives the lines between design and development are blurred with Smarty Templates. A developer can simply develop less logic and assume that the designer will take care of the rest with the variables he has access to, or a developer could limit the designer by only making available the core necessary values. The point is that, this line is blurry and just adds yet another level of abstraction with which internal standards must be enforced. Not so ironically, although developers have told me that they use Smarty Templates to allow the site to scale and to allow the designers to maintain the templates, I have never seen a situation where the roles were separated. The developer creates the PHP, then the same developer has to go in and modify the templates, bypassing the whole proposed benefit of using Smarty Templates in the first place.
  • With some more forethought, developers can create very structured and modular code, that with the proper API’s and CSS integration, can give the designer all the control necessary while still protecting data. Ideally, you would have a robust CMS, that allows your designers to have control over certain components, while still being able to deploy your core logic and modules. Then, for areas of the site that need more flexibility, you could use Smarty Templates within the CMS for those designers with a bit more technical skill and allow them to control sections of the page with Smarty Templates, not the entire site structure.
  • Although Smarty Templates can be useful if standards and structure is enforced, it seems as though it’s just another bandwagon thing that gets adopted out of pure social acceptance before the needs and resources of the project are adequately assessed.

I know that some of you may LOVE Smarty Templates and I understand that it may play a crucial role in your development, but please keep in mind that I am always ready and willing to use technologies that TRULY benefit my development (I’ve used Smarty on blogs for instance). This isn’t the place for flaming, but perhaps you can share something that I have missed. 

If I think really hard about what my needs are as a developer, Smarty kinda makes sense. The problem is that Smarty Templates seem to be the result of a desparate developer who’s fed up with designers messing up his apps, and/or who simply hates HTML (or all of the presentation layer for that matter) and doesn’t want to do anything but pump out logic. I don’t see how Smarty Templates benefit the designer or the project management process. I know, I know…. there are all the arguments about separation of presentation, from logic, from data, etc…. blah, blah, blah. Smarty is no more a clean separation of these layers than adding more frivolous layers of management to an organization to make it more effective. Smarty attempts to make the separation, but it’s not clean. The designers job should be completely separate from any kind of backend logic, allowing them to focus on HTML, graphics, CSS, etc… Smarty Templates don’t enforce this separation as HTML can be done by the designer, or a Smarty variable can contain HTML. So where is this separation they speak of? The second a developer includes HTML into any Smarty variable, the notion that the designer has full control over the UI goes right out the window and all you’re left with is another blurry layer of logic….. logic that cannot adequately communicate errors or debug info back to the backend logic. 

Ideally, if you want a cleaner separation of code and design, consider using or creating an MVC style framework which more strictly enforces this separation and allows for constrained usage of Smarty Templates or similar templating code. Zend Framework, Code Igniter and Cake are a few worth looking at.

I’m not trying to deter people from using Smarty Templates. I want to make it clear that I am simply urging you to use them as a tool to aid and not replace proper development. I see the value that Smarty Templates has the potential to bring to the table and will probably continue to use it for some things in my development. However, in the meantime, I am jumping off the wagon until it becomes something that I cannot live without.

PHP , , , ,

Sponsored Links

agile ajax black hat Cake PHP centering clifford stoll css cuckoo's egg energy energy drinks espionage flash Flex hacker jquery modular MVC objects optimization performance PHP script timer smarty smarty templates stylesheet up-time uptime variable scope web 2.0 Zend Framework