• Index
  •  » Articles
  •  » Choosing the best tool: Object oriented and procedure programming in PHP

Choosing the best tool: Object oriented and procedure programming in PHP

Choosing the best tool: Object oriented and procedure programming in PHP

The audience of the article

This article is meant for the PHP-beginners who would like to have an idea of object oriented and procedure approach to the programs writing.

The readers are supposed to have the basic knowledge of PHP and classes.

Introduction

Unlike many other languages PHP gains the possibility to use both object oriented and procedure approach when programming. The most PHP-programmers use the last one on default as far as web-pages are also handled in the procedure approach (one tag, then another, then the following one and so on). A code written in the procedure approach is much easier to combine with HTML and so programmers often develop their own style based on such approach.

If you are new to PHP you are likely to have used only the procedure programming by now. Nevertheless if you’ve already examined resources devoted to PHP in search for new solutions and methods you should have met different messages devoted to object float or you may have found different manuals on writing an object-oriented code in PHP. Maybe, you have downloaded some libraries using classes, learned creating objects or call their methods. At this you may have never realized completely why it makes sense to apply the object oriented approach in some cases.

The both approaches have their advantages and drawbacks making their followers exchange some simple remarks like ‘Objects are bad!’ or ‘Objects are good!’. This article doesn’t intend to persuade the reader to use one of these approaches but it is meant to examine advantages and drawbacks of each approach.

Here is an example of the procedure code printing a string

<?php 

print "Hello, world."

?>  

And this is the example of the object oriented code which serves the same purpose:

<?php 

class helloWorld 
  function 
myPrint() { 
    print 
"Hello, world."
  } 

$myHelloWorld = new helloWorld(); 
$myHelloWorld->myPrint(); 

?>  

We are to mention at once that this article isn’t an attempt to define object oriented programming as programming implying usage of classes. To get the basic information about principles of object oriented programming it’s recommended to use Google. At the moment there are enough good (and some bad) articles concerning the theme.

Who writes a code like this?

To realize how the theme examined became the reason of several ‘religious wars’ let’s analyze a couple of extreme examples from the both sides. First we’ll have a look of a ‘Procedure Fanatic’ and then that of an ‘Object Fanatic’. Maybe someone of them is already familiar to the reader.

‘Procedure Fanatic’

A ‘Procedure Fanatic’ has been always criticized by his informatics teacher for bad usage of the abstract approach when doing his tasks. The argument he cited as his excuse: “But it doesn’t function!” didn’t improve his marks. Later on such a programmer chooses as his data domain such tasks as writing of drivers, file systems and other low-level programs where his accent on speed and brevity brings him acknowledgement.

The extreme example of a ‘Procedure Fanatic’ is complete negation of objects and criticism of abstraction as such. Such programmers always want to make their code fast without taking care about people who are going to read this code afterwards. They often treat process of programming as a kind of competition not as a team development. They enjoy taking part in different complicated contests on code writing. Their favorite languages along with PHP are C and Assembler. In PHP they may be occupied with PECL-modules writing making code rational and effective.

‘Object Fanatic’

An Object Fanatic has recently discovered object oriented programming and now he is ready to apply it wherever possible! He doesn’t realize productivity problem by the approach used by him completely. Sometimes abstract design conceptions seem to be more important for him than the code itself. Maybe such a programmer has good chances to build a career of a project manager or technical writer.

Object fanatics like blaming the procedure ones with the fact that without abstractions world would still keep programming by means of nulls and ones. They are famous on their speaking on pseudocode. An extreme example of such programmers are people who use objects without taking into account questions of productivity, elegance and even readability of their own code. Their favorite programming languages along with PHP are Java and Smaltalk. As a rule, in the PHP-community they are occupied with PEAR-modules development creating well-documented code which is easy to attend.

“They will never meet”

Why are forum pages full of biased statements? The reason is that your unique experience which has been gathered during work over a project and as a result you develop your own ‘philosophy’ which determines the way you search for the new ideas. As programmers you should beware of such prejudices staying opened for learning something new. As computer scientists we should be able to throw away these prejudices to find better problem solutions in the concrete situation.

What are your goals?

Think for a moment about the question which goals you set for yourself when writing some PHP-program. These goals are often expressed rather obscurely and sometimes are indicated in the task. You may keep to these goals in any of your projects. One of such goals which are supported by the author of this article is elegance. But the definition of the elegance won’t be given here as far as it can be a theme of the separate article. There are other goals which are more abstract and not always correspond with the solutions that are good for a project – for the concrete tasks which you face. In fact, such goals can be prejudices in the case given.

Abstract goals

  • To offer such solution which contains as few code strings as possible
  • To think about a problem on the level of the problem

It sounds great, doesn’t it? But what is meant with the expression ‘as few code strings as possible’? Are the comments taken into account? Should we join up the entire code into one string separating it with semicolons? And what about braces? Some prefer to leave an optional string for them. According to the goal set this all will be a direct task breaking. And what about ‘thinking about a problem on the level of the problem’? Does it mean we should create a class for each conception used in solution? Or should we place each sub-task into a single file and create a composed tree displaying the real structure? That’s it – a file and a class for each idea!

It’s obvious that such summarizing becomes nonsense when made into a principle. But there are finer displays of the same problem. How often do programmers working in a team invent a one-string-solution and insert it into the code without any comment only in order to confuse their team-mates who are going to attend it afterwards? And conversely, how often a bureaucratized chief programmer falls into a trance creating such interfaces and classes which not only make lives of his subordinates who realize this code more difficult but also limit the productivity and flexibility of the program itself in case when the final customer needs optional functionality. These all are just inconsiderable displays of these very prejudices which work subconsciously within heads of our ‘too much human’ programmers.

Practical goals

The problem can be solved with such a code which first considers practical goals set before a project. So what are the goals of a concrete project? Here are some variants:

  • Write it fast and release often.
  • Make it work as fast as possible.
  • Make it easy to attend, distribute and extend.
  • Publish a program interface (API).

The first two goals have a bent for the procedure approach by the time when the last ones – to the object oriented approach.

Which approach is the most correct?

Now let’s try to judge about practical advantages of each method.

Procedure approach

The main argument in favor of the procedure approach is the fact that PHP is an interpreter. This means that unlike many other languages it isn’t compiled into a binary code for accomplishment but is interpreted and accomplished ‘at a jump’. This is a scripts’ language and each script is saved like an ordinary text (of course, with the exception for the Zend compiling tools).

Another argument against usage of object oriented approach in PHP4 is the fact that such functionality hasn’t been considered thoroughly in this and earlier versions. According to the PHP-authors, support of the object oriented programming has been added after finishing the main works over the language’s core. From this follows that usage of objects in PHP4 isn’t as rational and effective as it could be. However this situation is going to change with the release of the new version PHP5.

Such popular applications as osCommerce and phpMyAdmin are written using procedure approach. They’ve appeared fast enough and possess relatively high working speed. The both projects are closely tied to HTML which combines with PHP without any limitations.

osCommerce

osCommerce contains some objects but the most work is done in the procedure style. The author of this article had to correct code several times adding the necessary for customers functionality (sometimes it was so necessary that the fact it hadn’t been foreseen from the very beginning was rather astonishing). Anyway it should be mentioned that the process of changing wasn’t trivial. The most of the procedure code needed a lot of time for its examining and comprehension as far as the code itself was mixed up with the templates’ system and also has been projected using different language notations.

Now it works fast with the most sites occupied with e-commerce. It also should be mentioned that osCommerce-community has a forum and some kind of structure for development of the new modules and extensions. Correspondingly many useful ‘plug-ins’ may be found for the system.

phpMyAdmin

phpMyAdmin uses directly only one class: Mimer SQL Validator which in case of phpMyAdmin depends on PEAR-parcels Mail_Mime, Net_DIME and SOAP. Such solution is likely to be based on the conviction: ‘it serves its purpose well so we are to use it’. In all the rest the application code seems to be written in the procedure style and we again face the close connection of HTML and PHP.

phpMyAdmin is a tool for daily use. Even more than this the author encourages his customers to use phpMyAdmin as a content administration system for simple modifications (of course, their rights should be limited properly). phpMyAdmin works very well and taking into account the things it has to do it also works very fast. The author often extends phpMyAdmin for some applications making it into an administrating system and improving such its features as selected requests in order to enable customers to create selections fast and easily and edit them as well. The code itself should be well attended as far as the product examined is developing into a more practical tool with the release of each new version.

Procedure approach: Conclusion

Procedure parts of the both applications are well documented. In case of osCommerce gaining of some framework for applications development also benefits supporting and extension of this product. However there is nothing like API enabling to extend the product up to something which differs strongly from the original.

Much effort will be needed to make osCommerce into an accountant application and even more to make phpMyAdmin into a customizable system for the content administration. Nevertheless the both these products do the work for which they have been created very well.

Object approach

One of the main arguments in favor of object oriented approach is extensibility and modularity of the code got. The fact of programming using the object oriented style itself cannot comment a code or create documentation but it can encourage you to do this. And once your striving for extensibility of the code created may result into writing of a real program interface (API) for your application.

PHP 5 promises to make process of object oriented programming much more pleasant. With some irony the new version can be compared with the release of ‘Java 2’ as far as it includes a row of such features as interfaces, link model of objects and structure try/catch which have already shown themselves in Java. But even for PHP 4 and the earlier versions the examples of successful objects’ applying may be found.

One of the most successful ones is considered to be Smarty which is a system of templates enabling separation of the PHP-code from content. Another useful example is freely distributed PDF-generator which is completely written in PHP and is named FPDF. The both program products practice such approach which separates HTML-code from PHP. It’s especially important to mention the fact that the both programs may be extended up to other useful applications.

Smarty

Smarty is a tool for creation of complex forms and sites based on templates. In most cases Smarty is the most suitable tool when you need to build a system prototype with completely customizable appearance. The appearance of a site can be changed completely without having any influence upon functionality which stands behind this. To simplify the process of appearance changing for designers the author has created an individual tags’ system as an extension of Smarty tags’ system. Thus, for instance, by entering at the top of a page such a directive

 [navigation horizontal separated by " | "]  

A horizontal navigation block separated with "|" symbols appears on the site. As far as Smarty already possesses a well-developed mechanism of displaying the data contained within variables the process described implies displaying of complex Smarty-tags into simple directives for design only.

More detailed about it you may read on http://simpletags.sourceforge.net and http://simplequiz.sourceforge.net.

As far as Smarty represents a class and all its methods are well-documented its functionality may be easily extended. Besides that Smarty offers the level for separation of the scope of other variables used in PHP by making a template transmit only the variables you are going to use. Such an ‘ecological inspectors over the variables’ enables creating a reliable working connection between designers creating templates and programmers who render data for them.

FPDF

FPDF is a perfect tool. If you are disappointed with the constantly changing API to pdflib and don’t want to pay for a well-supported application, if you cannot manage the extensions from the PHP-version with which you work (as it happens in case of a hosting with common resources), you should think about usage of this freely distributed and completely written in PHP PDF-generator.[1].

This class is well-documented including a lot of pleasant examples of creation and placement of text and graphics in the document. For the already mentioned on-line teaching site the author used FPDF for the dynamic creation of courses graduation certificates using fonts of True Type family and graphics with 300 dpi resolution. Those optional seconds which are needed for call of a class and PDF-operations’ accomplishment are almost imperceptible on the background of the fact that sometimes it takes some minutes to download a PDF-file itself. Seeing that by low-speed connections the optional time spent on creation and sending a PDF-file sometimes proves to be less than downloading of a static analog.

Besides that, as far as FPDF is based on the object oriented approach it can be extended. Many methods aren’t realized completely and simply exist in the form of a structure which can be extended by you, for instance, for creation of your own catchwords (headings) within a single class.

Object approach – conclusion

Both Smarty and FPDF offer a well-documented interface for the extension of their main class. Including all the methods and data in a class is in such a case a well-considered solution. Similar functionality could be achieved using ordinary functions and global variables but it would be difficult to extend afterwards. Besides that it would be impossible to create some substances with equal functionality as it could be done with objects. Such objects can set up style of the PDF- or HTML-document which you create. Thus you may publish the same data in different formats.

The applications described above are wonderful example of object oriented approach usage for creating a useful library.

What and when should you apply?

We’ve examined examples of timid approaches’ usage for different purposes and went into examples of effective applying of these approaches in the real applications. But should we do if our goals demand usage of the both approaches?

General testing of the productivity of object and procedure code will give you a rather abstract idea of what you can expect from a concrete application created by you. Instead of testing like this you’d better choose such method of estimation which suits you the best for real estimation of the concrete code on some part of it. Check your functions against the possibility to use common resources. Think over necessity of the extension for such functions. Think over how much writing of a class will help you to make your code extensible. Beside all the rest you are to divide your goals according to their priority. Consider them. If you use practical approach from project to project to define effectiveness of an object oriented or a procedure code, you are granted an unbiased and supported by your experience solution. Remember: using PHP you always get a chance. You can always combine the both approaches.

Why do you need the both approaches?

Returning to the fanatics of the object and procedure approaches we shouldn’t forget about their services.

  • We’ll thank ‘object’ programmers for practicality and extensibility of Smarty and FPDF
  • We’ll also thank ‘procedure’ programmers for high speed and reliability functioning in osCommerce and phpMyAdmin.

In fact these acknowledgments trace back to the PHP-basics.

Both PECL and PEAR have deserved enough fame and criticism. The both projects can be a good illustration of differences between procedure and object oriented programming.

PECL renders extensions for PHP which are written in C using procedure approach and are oriented to the speed and conciseness of a code. Often it is transfer of the already existing applications with LGPL-license (Lesser General Public License). Thus within a period of some years a lot of interesting functions has been added to PHP. Besides that you shouldn’t forget that PHP itself is written in C.

PEAR also has made a lot for appearing of many useful and interesting classes from creation of Excel-tables up to changing of DNS-entries. Using PEAR-libraries you’ll save a lot of time and will be able to create such functionality which makes you exclaim: “I had no idea that PHP can do such things!”

Conclusion

The author hopes that this article has given you the chance to judge about utility of each programming approach and, that is even more important, provided you information and wish for thorough studying of this project. Think about your goals, test real templates and treat radical judgments with some irony. The both approaches have their advantages. And so you are to go and write some strings of a good code!


 

  • Top