MOPP : Day 8 : Make Programs, not scripts

With the evolution of php and maturity of its’ object orientation, our code should become less and less mangled. One way to organize our applications and make them much more manageable is to stop thinking of our web applications as scripts and start making programs.

For one thing, drop the ending delimeter ‘?>’ from your include files. This is an old trick, but it really is important. It makes sure that your output stays untarnished, which is expecially important if you are doing output buffering or dealing with sessions. Any new lines and white space after the ‘?>’ is automatically sent to output. This whitespace could be added from your editor accidentally when it is saved or transfered, so this is a very helpful tip.

Another thing is in your class files, you should be using correct OOP. Google design patterns and identifiers. Make sure your private methods are private, protected methods are protected and final properties are final. Do not get ‘public’ crazy everywhere. Also static methods and properties are essential to learn if you are unaware, since we now have late static binding in version 5.3.

I know one of the great things about php is that it does not care about data types, however we should know what our data is, and what format it should be in. We have plenty of type-hinting and casting in PHP, so now is a time to use them. I even hear we are going to be getting return type hinting soon, so there is no reason for you not to become aquainted with it. This also helps us in debugging and maintaining as we know what each variable is intended to be. If you are unsure of type-hinting, please take some time to look it up and understand what it is.

Even if you are not using an MVC architecture, we should still be separating our view logic from everything else. I am against the masses when I say this but it is perfectly fine to have PHP and HTML together in the same script, but you should do so neatly, and try not to echo any kind of html from php. You should setup the elements in html and plug in the dynamic data with a simple line of php.

Go through some tutorials for ‘C’ and ‘C++’ programming, and use the ideas and structure to help your php applications conform to a more clean and optimized scale than what you already were doing.


Leave a Reply