Object-oriented and process-oriented in PHP
SubmittedJiashixiangOn 2006, August 10, PM. php Learning
Author: Robert Peake Translation: haohappy Source: PhP & more
Target readers
This article is intended for users who want to learn about object-oriented and process-oriented programming methods in PHP, including beginners and veterans. Assume that you are familiar with PHP and class usage to a certain extent.
Introduction
"True genius is capable of correctly evaluating uncertain, risky, and conflicting information. -- Qiu Gill"
When using many programming languages, you can only use object-oriented or process-oriented programming methods. In PHP, You can freely choose or mix. Currently, most PHP programmers use process-oriented methods, because parsing Web pages is very "procedural" (from one tag to another ). It is natural to Process Code during the embedded process in HTML, so PHP programmers usually use this method.
If you are new to PhP, writing code in a process-oriented style is probably your only choice. However, if you often go to PhP forums and newsgroups, you should see articles about "objects. You may also see tutorials on How to Write object-oriented PHP code. Or you may have downloaded some ready-made class libraries and tried to instantiate the objects and use the class method-although you may not really understand why these classes can work, or why do we need to use object-oriented methods to implement functions.
Should we use the "Object-Oriented" style or the "process-oriented" style? Both parties have their own supporters. Discussions like "objects are inefficient" or "objects are great" are also heard. This article does not try to determine which of the two methods has absolute advantages, but to find out the advantages and disadvantages of each method.
The following is a process-oriented code example:
<?php
print "Hello, world.";
?>
The following is an object-oriented code example:
<?php
class helloWorld {
function myPrint() {
print "Hello, world.";
}
}
$myHelloWorld = new helloWorld();
$myHelloWorld->myPrint();
?>
If you want to know some basic "Object-Oriented" knowledge, please use Google search, there are many wonderful articles on the Internet.
Who writes code like this?
To understand why this topic has become a fuse for the Forum, let's look at some extreme examples of each camp. Let's take a look at "process fanatics" and "Object fanatics ". Let's see if they seem familiar.
Process craze
The process craze was criticized by computer teachers in class because it did not use a more abstract implementation method. Support the process-oriented Viewpoint "it can work !" It cannot improve the programming level and grade. After graduation, they may find a job, write drivers, file systems, or other underlying-oriented programming, with their focus on speed and code refining.
The extreme example of the "process fanaticism" is to resist objects and abstract them. They are always thinking about how to make the program run faster, regardless of whether others can understand their code. They often regard programming as a competition rather than a team activity. Apart from PHP, their favorite programming languages are C and assembly. In the PHP world, they may develop the PECL module and contribute efficient code.
Fanatic object
Object enthusiasts are keen to use the object-oriented style to write code at any time. They have not really considered whether using this method will affect the execution efficiency of the program. Sometimes people feel that they prefer abstract design concepts rather than real code. They are usually project managers or document writers.
It is pointed out to the fans that, without an abstract design method, we are still programming with 0 and 1. They like to use pseudo-code to describe the problem. An extreme example is that object enthusiasts still use objects even if they know they sometimes sacrifice efficiency. Apart from PHP, their favorite languages are Java and smalltalk. In the PHP world, they may develop pear modules and contribute well-documented and easy-to-maintain code.
Don't be extreme or ironic
Do you know why forums are always filled with various prejudices? Your experience and attitude towards new things may be the cause. As programmers, we often need to pay attention to these prejudices and learn new things with an open mind.
Your coding preferences?
Consider your preferences or preferences when writing PHP code. These preferences are usually relatively obscure. Sometimes you may have the same preferences in each project. I personally tend to be "elegant", but I don't want to define how the code is "elegant" here, it should appear in another article. However, theoretical preferences are not necessarily suitable for actual projects-on the contrary, they are often biased.
Theoretical Tendency
• Provide a complete solution with the minimum number of lines of code
• Consider issues at the problem level
It sounds good. But how can we measure the "minimum number of lines of code? Do you want to include code comments? Do We Need To concatenate each line and only use semicolons to differentiate it? What about braces? Obviously, this idea is wrong.
Next, Let's explain what is "problem level ". Does this mean that a class needs to be created for every concept in our solution? Or do you need to maintain each part of the problem in each independent file and create a complex file tree to correspond to the problem in reality? That's the idea: Prepare a file or class for each idea!
Obviously, these summaries become ridiculous after the ultimate. But there are more subtle proofs in reality. Do programmers often insert a complex, powerful, but unannotated line of code when working in a team? This is undoubtedly very frustrating for those who take over and maintain the code. On the contrary, is it true that your bureaucratic self-righteous top-level programmers often create interfaces and classes in a "straight forward" manner? Those interfaces and classes not only restrict the programmers responsible for implementation, but also restrict the efficiency and flexibility, resulting in the customer's inability to request the Extended Program. These are the subtle proofs of the above tendencies.
Actual Tendency
At the beginning of a project, you must first seek the actual encoding purpose and direction. What is the goal of this project? Below is the answer.
• Fast development and fast release
• Run as quickly as possible
• Easy to maintain, improve, and expand
• Publish an API
The first and second directions tend to adopt procedural styles, while the last two tend to use object-oriented styles.
When is some method more effective?
Now let's evaluate the advantages of each method in reality.
Process-oriented cases
A fundamental argument for PHP's advantages in process-oriented programming is that PHP is an explanatory language-which means, unlike other languages, instead of being compiled into an executable package, it is interpreted and executed immediately. It is a scripting language and is stored in text files (except if Zend compilation tool is used ).
Another reason against using object-oriented encoding in PhP4 and earlier versions is that the object functions were not well designed in earlier versions of PHP. As Rasmus once said: "That is the feature that needs to be added after the event ". This means that in PhP4 and earlier versions, object efficiency is a problem. But after PhP5 is released, this situation will change.
The following two most popular PHP programs-oscommerce and phpMyAdmin-mainly use process-oriented encoding. They are quickly built and run quickly. Both of them naturally adopt the method of embedding HTML.
Oscommerce
Oscommerce actually uses many objects, but most of the functions are implemented through the "process. I used to hack oscommerce to add some user-defined functions that are very useful to customers. This process is quite troublesome because many Process Codes in oscommerce do not use templated systems and are designed to be multilingual, so it takes some time to get started. However, it can work. In fact, it is already running well on a large number of e-commerce sites. Oscommerce also provides a forum and a development framework for developing modules and plug-ins. Therefore, many functional modules provided by other developers are available.
PhpMyAdmin
PhpMyAdmin directly uses only one class: Mimer SQL validator class, depending on mail_mime, net_dime, and soap in the pear package. This may take into account the convenience of development: the use of off-the-shelf code that can achieve the purpose. In addition, everything is process-oriented, and HTML and PHP Code are also mixed.
PhpMyAdmin is a tool that I use almost every day. It is used to process a small number of data tables less complex. Sometimes I even encourage my customers to use it as a backend management tool (of course I will limit their permissions ). PhpMyAdmin is very good and fast. Sometimes I want to extend phpMyAdmin as a backend management tool in some projects. using some of its new features, such as data query statement bookmarks, can be easily displayed to my customers and edited. With the release of each new version, phpMyAdmin becomes more and more practical and powerful.
Process-oriented summary
The above two process-oriented programs have excellent documentation and code comments. The development framework provided by oscommerce can increase maintainability and scalability. However, neither of them provides APIs and cannot be extended to another system.
If you want to integrate oscommerce into a bill application, it takes a lot of time and effort, just like extending phpMyAdmin into a backend management tool for customers. However, from the perspective of their design purpose, they did well in their respective fields.
Object-oriented Cases
Support for Object-Oriented styles focuses on scalability and encapsulation. Writing code in an object-oriented way alone does not generate documents for your code, but it encourages you to add documents for it. In addition, you may write an API for ease of expansion. PhP5 promises to make object-oriented programming more enjoyable. I jokingly called it "Java 2" in PHP because it integrates many features in Java, such as interfaces, object-oriented models, and try-catch statements. However, even in PhP4, which has poor support for Object-Oriented applications, there are still many outstanding object-oriented applications.
Smarty
Smarty is used to build websites with complex forms and templates. Recently, I wrote an online examination system that can completely change the "skin"-you can completely change the appearance and style of the entire site without changing any underlying code and functions. To make it easy for designers to design new interfaces, I designed a custom tag library as an extension of the smarty tag library. You can insert it as follows:
[navigation horizontal separated by " | "]
Navigation is separated at the top of a page. Because smarty already provides a very powerful mechanism to express the data contained in variables, it is a simple process of ing complicated smarty labels to skin labels. For more information about this, see: http://simplequiz.peakepro.com/
The process of using a template is incredibly easy to expand by encapsulating smarty into a class with detailed documentation on its methods. At the same time, by forcibly passing only the variables you want to use to the smarty template method, smarty also provides a protective layer for PHP environment variables. This method helps to establish a secure and reliable working relationship between the smarty template designer and the programmer.
Fpdf
Fpdf is an excellent tool. If you are confused by the modified pdflib API, or do not want to pay for commercial solutions, or because of restrictions on shared hosts, unable to use the extension module-please consider using this free, pure PHP-built PDF generation tool.
This class has good documentation, including many good examples to illustrate how to layout text and images in PDF. In the same online learning site mentioned above, I use fpdf to dynamically generate PDF files, and use True Type fonts and DPI precision images. It does not take much time to instantiate the fpdf class in PHP and perform PDF operations, because the PDF itself may take several minutes to download. In fact, it takes more time to dynamically generate and transmit a PDF file than to transmit a static PDF file using a slow network connection. This is relative. In addition, because fpdf is class-based, it can be extended. In fact, although some class methods exist, they are not fully implemented yet and only serve as a framework. This allows you to create your own content (such as custom header and tail elements) in the subclass) provide the wizard.
Fpdf
Fpdf is an excellent tool. If you are confused by the modified pdflib API, or do not want to pay for commercial solutions, or because of restrictions on shared hosts, unable to use the extension module-please consider using this free, pure PHP-built PDF generation tool.
This class has good documentation, including many good examples to illustrate how to layout text and images in PDF. In the same online learning site mentioned above, I use fpdf to dynamically generate PDF files, and use True Type fonts and DPI precision images. It does not take much time to instantiate the fpdf class in PHP and perform PDF operations, because the PDF itself may take several minutes to download. In fact, it takes more time to dynamically generate and transmit a PDF file than to transmit a static PDF file using a slow network connection. This is relative. In addition, because fpdf is class-based, it can be extended. In fact, although some class methods exist, they are not fully implemented yet and only serve as a framework. This allows you to create your own content (such as custom header and tail elements) in the subclass) provide the wizard.
Object-oriented Summary
Both smarty and fpdf provide APIs with good documentation to expand the main class. This demonstrates the necessity of organizing methods and data within the class-sometimes the same function can be done using functions and global variables, but this is not easy to expand. In addition, using objects is very helpful for tracking and maintaining the style of PDF or HTML documents. You can publish the same data in different formats. Both smarty and fpdf are excellent examples of using objects to build flexible and practical class libraries.
Why are both required?
Back to our enthusiastic programmers, we began to praise them:
• We appreciate the practicality and scalability of Smarty and FPDF.
• We appreciate the running speed and good performance of osCommerce and phpMyAdmin.
This appreciation also includes some basic PHP development. Both PECL and PEAR have received a lot of praise and criticism. I think these two projects provide a good example to illustrate the differences between process-oriented and object-oriented programming.
PECl provides a PHP extension library, which is developed in C and process-oriented mode, focusing on speed and conciseness. These are usually transplanted from the existing LGPL software, and many of the interesting features have been added to PHP. After all, PHP is written in C.
PEAR has contributed many interesting classes, such as creating an Excel table or changing DNS records. Using the PEAR class library can save you a lot of time, or even allow you to develop without getting familiar with PHP-"I don't understand, but it can be used !".
Summary
I hope this article will help you better understand the two programming methods and, more importantly, encourage you to explore more specific details. I hope you will have your own ideas, test your project development preferences in actual development, summarize more practical cases, and write some comments on this article.
In short, each method has its own advantages. It is better to leave the debate to write some actual code!
About the author
Robert Peake taught a computer course at Berkeley before obtaining a poetry degree. I recently resigned as an IT manager, considering spending more time on my family and PHP. He lives in LA with his wife, Valerie. You can contact him via email: robert at peakepro.com
About translators
Edited by Haohappy and PHP & MORE, he has many translation works on Phpe.net, mainly involving PHP5 and OOP.