Object-oriented and process-oriented in PHP

Source: Internet
Author: User
Tags end extend new features variables pdflib pear version variable
objects | procedures

Brief introduction
"True Genius has the ability to correctly assess uncertain, risky, and contradictory information." --Churchill "

When you use many programming languages, you can usually only use one of the object-oriented or process-oriented programming methods. In PHP, you are free to choose or mix. Most PHP programmers now use a process-oriented approach, because parsing a Web page itself is very "procedural" (from one label to another). Embedding process code in HTML is straightforward and natural, so PHP programmers often use this approach.

If you're just in touch with PHP, writing code in a process-oriented style is probably your only option. But if you regularly go to the PHP forums and newsgroups, you should see an article about "objects." You may also have seen a tutorial on how to write object-oriented PHP code. Or you may have downloaded some out-of-the-box libraries and tried to instantiate them and use class methods-although you may not really understand why these classes work, or why you need to use object-oriented methods to implement functionality.

Should the "object-oriented" style or "process oriented" style be used? Each side has its own supporters. Such arguments as "objects are inefficient" or "very good objects" are also heard. This article does not attempt to easily determine which of the two methods has an absolute advantage, but to find out the pros and cons of each method.

The following is a process-style code example:

<?php
Print "Hello, world."
?>


The following is an object-oriented style code example:

<?php
Class HelloWorld {
function Myprint () {
Print "Hello, world."
}
}
$myHelloWorld = new HelloWorld ();
$myHelloWorld->myprint ();
?>


If you want to know something about "object-oriented" basics, use Google search, and there are a lot of wonderful articles on the web.

Who writes code like this?
To understand why this topic has become a flashpoint for the forum, let's look at some of the more extreme examples of each faction. Let's look at "Process Mania" and "Object Mania". See if their point of view sounds a bit familiar.

Process Mania
Process mania has been criticized by computer teachers in class, as this approach does not use more abstract implementations. and support the process-oriented perspective "it can work!" "Can not improve its programming level and grade." After graduation they may find a job, write drivers, file systems or other biased programming, with their focus on speed and refinement of the code.

An extreme example of "process Mania" is the rejection of objects and the rejection of abstraction. They are always thinking about how to get the program to run faster, regardless of whether others can read their code. They often regard programming as a contest rather than as a team activity. In addition to PHP, their favorite programming language is C and assembler. In the PHP world they may develop PECL modules that contribute to efficient code.

Object Mania
Object enthusiasts are keen to write code at any time using an object-oriented style. They have not really considered whether this approach will affect the execution efficiency of the program. Sometimes it makes people feel that they enjoy abstract design concepts rather than real-world code. They are often very likely to be project managers or document writers.

Object enthusiasts point out that if there are no abstract design methods we are still using 0 and 1 for programming. They like to use pseudo code to describe the problem. An extreme example is an object fanatic who even knows that sometimes sacrificing efficiency still uses the object. In addition to PHP, their favorite language is Java and Smalltalk. In the PHP world, they may develop the Pear module, contributing to the documentation that is very good, easy to maintain code.

Don't be radical and sarcastic.
Do you know why the forums are always full of prejudices? Your experience, your attitude towards new things may be the reason. As programmers, we need to be constantly aware of these biases and learn new things with an open mind.

What's your coding propensity?
Consider what preferences or tendencies you have when writing PHP code. Usually these preferences are more obscure. Sometimes you may have the same preference in every project. I personally tend to be "elegant", but I don't want to define "elegant" code here, which should appear in another article. However, theoretical preferences are not necessarily suitable for actual projects-they are, on the contrary, often a form of prejudice.

The tendency of the theory
• Provide a complete solution with a minimum number of lines of code
• Consideration of issues at the problem level

That sounds like a good idea. But how do you measure the "least number of lines of code"? Do you want to count the code comments? Do we have to string each line up and separate it with semicolons? What about curly braces? It is clear that the idea is wrong.

Explain again what is the "problem level". Does this mean that every concept in our program needs to build a class? Or you need to keep each part of the problem in each individual file, and create a complex file tree to correspond to real-world problems. That's the idea--Prepare a file or class for each idea!

It is clear that these generalizations become laughable. But there are more subtle proofs in reality. Is it often that programmers insert a line of complex, powerful, but not annotated code in a team collaboration? This is certainly frustrating for those who take over the maintenance of the code. Conversely, does your bureaucratic self-righteous upper-level programmer often "rampage", building interfaces and classes? Those interfaces and classes not only limit the programmers responsible for implementation, but also limit efficiency and flexibility, causing customers to be overwhelmed by the need to extend the program. These are the subtle proofs of all these tendencies.

Actual tendency
At the beginning of a project, you should first look for the actual coding purpose and direction. What is the goal of achieving this project? The following is probably the answer.

• Fast development, quick release
• Run as fast as possible
• Easy to maintain, improve and extend
• Publish an API


The first to second direction tends to use a procedural style, while the last two tend to use object-oriented style.

When is a certain way more effective?
Now let's try to evaluate the advantages of each approach in reality.

Process-oriented cases
A fundamental argument about the advantages of PHP's process-oriented programming is that PHP is an interpretive language-meaning that, unlike other languages, it will not be compiled into an executable package, but interpreted and executed immediately. It is a scripting language and is stored in a text file (exceptionally, if the Zend Compilation tool is used).

Another objection to using object-oriented encoding in PHP4 and later versions is that the object's functionality is not well designed in earlier versions of PHP. As Rasmus once said: "It is only after the event to think of the added function." This means that the efficiency of an object is a problem in PHP4 and earlier versions. But when the PHP5 comes out, the situation will change.

The following are the two most popular PHP programs--oscommerce and phpMyAdmin. The main use of the process-oriented coding method. They build up quickly and run quickly. Both are naturally embedded in HTML methods.

OsCommerce
OsCommerce actually uses a lot of objects, but most of the functionality is done through "processes." I've hack oscommerce to add some custom features that are very useful to customers. This process is cumbersome, because many of the process code in the oscommerce, not using a templating system, and designed in a multilingual version, so it takes a certain amount of time to get started. But it works, in fact it's 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. As a result, there are a number of useful functional modules available to many other developers now.

phpMyAdmin
phpMyAdmin directly uses only one class: The Mimer SQL Validator class, which relies on mail_mime, Net_dime, and SOAP in pear packages. This may be due to the convenience of development: the use of ready-made code that can achieve the purpose. In addition, everything is process oriented, and HTML and PHP code are mixed together.

phpMyAdmin is a tool I use almost every day to do less complex processing of a small number of datasheets. Sometimes I even encourage my clients to use it as a back-end management tool (and I will limit their permissions, of course). phpMyAdmin's performance was great and fast. Sometimes I want to extend phpMyAdmin as a back-end management tool in some projects, and use some of its new features such as data query bookmarks to easily show to my customers and editors. With each new version of the launch, phpMyAdmin more and more practical, more and more powerful features.

Process-oriented summary
The above two programs that use process-oriented styles have very good documentation and code comments. The development framework provided by OsCommerce can increase maintainability and scalability. But neither provides an API and does not extend the program to another system.

If you want to integrate oscommerce into a billing program, it takes a lot of time and effort, like extending phpmyadmin into a back-end management tool for customers to use. However, from the point of view of their design, they really did well in their respective fields.

Object-oriented case
The view that supports object-oriented styles is focused on extensibility and encapsulation. Writing code in an object-oriented way does not generate documentation for your code, but it can encourage you to add documents to it. And, in order to be easy to expand, you might write an API. PHP5 promised to make object-oriented programming more enjoyable. I jokingly called it the "Java 2" version in PHP because it integrates many of the features in Java, like interfaces, object-oriented models, try-catch statements, and so on. But even when the object-oriented support is not

In the PHP4 of force, many outstanding object-oriented applications still appear.

Smarty
Smarty is used to build sites with complex forms and based on templates. Recently, I've written an online exam system that completely changes the "skin"-you can completely change the interface and style of the entire site without changing any of the underlying code and functionality. 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 simply insert it like this:

[Navigation horizontal separated by "|"]

There is a separate navigation at the top of a page. Because Smarty has provided a very powerful mechanism to represent the data contained in a variable, this is a simple process of mapping a more complex smarty tag to a skin tag. For more information on this, please see: http://simplequiz.peakepro.com/
Because Smarty is encapsulated as a class, and its methods have very detailed documentation, the process of using the template becomes incredibly easy to extend. At the same time, Smarty also provides a protective layer for PHP environment variables by compelling you to explicitly pass the variable you want to use to the Smarty template. This approach helps to establish a secure, reliable working relationship between Smarty template designers and programmers.

FPDF

Fpdf is a very good tool. If you're confused by the Pdflib API you've changed to, or you don't want to pay for a commercial solution, or because of the limitations of shared hosts, you can't use extension modules-consider using this free, PHP-built PDF generation tool.

This class has good documentation, including many good examples to illustrate how to lay out text and pictures in a PDF. In the same online learning site mentioned above I use Fpdf to dynamically generate PDF files, using True Type fonts and 300dpi-precision images. Instantiating the Fpdf class in PHP and doing it in PDF does not take much extra time because the PDF itself may take several minutes to download. In fact, it takes more time to dynamically generate and transfer a PDF than to transfer a static PDF file with a slow network connection. It's all relative. Also, since Fpdf is based on a class, he can be extended. In fact, some classes of methods exist but are not fully implemented, only as a framework, which provides wizards for creating your own content in subclasses, such as custom kinsoku elements.

FPDF
Fpdf is a very good tool. If you're confused by the Pdflib API you've changed to, or you don't want to pay for a commercial solution, or because of the limitations of shared hosts, you can't use extension modules-consider using this free, PHP-built PDF generation tool.

This class has good documentation, including many good examples to illustrate how to lay out text and pictures in a PDF. In the same online learning site mentioned above I use Fpdf to dynamically generate PDF files, using True Type fonts and 300dpi-precision images. Instantiating the Fpdf class in PHP and doing it in PDF does not take much extra time because the PDF itself may take several minutes to download. In fact, it takes more time to dynamically generate and transfer a PDF than to transfer a static PDF file with a slow network connection. It's all relative. Also, since Fpdf is based on a class, he can be extended. In fact, some classes of methods exist but are not fully implemented, only as a framework, which provides wizards for creating your own content in subclasses, such as custom kinsoku elements.

Object-Oriented Summary
Both Smarty and Fpdf provide an API with good documentation to extend the main class. This illustrates the need to organize methods and data within a class-sometimes the same functionality can be done with functions and global variables, but this is not easy to extend. Also, using objects is very helpful for tracking and maintaining the style of a PDF or HTML document, and you can publish the same data in a different format. Smarty and fpdf are excellent examples of using objects to build flexible and useful class libraries.

Why are both ways necessary?
Back to our passionate program, we began to praise them:

• We appreciate the practicality and extensibility of smarty and Fpdf
• We appreciate the speed and good performance of oscommerce and phpMyAdmin

This appreciation also includes some basic development of PHP. Pecl and pear have received a lot of praise and criticism. I think these two projects provide a good example of how the differences between process-oriented and object-oriented programming are clarified.

PECL provides a PHP extension library, developed in C and process-oriented fashion, focusing on speed and concise refinement. Typically, these are ported from existing LGPL software, many of which have been added to PHP. After all, PHP is written in C.

Pear contributes a lot of interesting classes such as creating Excel tables or changing DNS records. Using the Pear class Library can save you a lot of time and even allow you to develop in a situation that is unfamiliar to PHP-"I don't understand, but it does!" ”。

Summarize
Hopefully this article will deepen your understanding of both ways of programming and, more importantly, encourage you to explore in more specific detail. I hope you will have your own ideas, and in the actual development test your project development trend, summed up more practical cases, do not sik to write some comments on this article.

In short, each way has its advantages, entangled in the debate rather than leave to write some actual code!



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.