Home >php教程 >PHP开发 >Rethinking PHP programming methods (Part 1)

Rethinking PHP programming methods (Part 1)

黄舟
黄舟Original
2016-12-21 10:50:351156browse

A few years ago, PHP5 changed from a process-oriented language to an object-oriented language, which caused a huge stir in various technical forums. Many people asserted that PHP would destroy itself, but soon after the dust settled, most people switched from not supporting PHP to supporting it. It has also transformed from being jokingly called a children's toy in the 4.0 era to becoming the third largest language after Java and C. Being involved in the whole debate, I thought I had a complete understanding of object-oriented, and gradually began to fully adopt object-oriented programming. After 2008, I even started writing programs only under the zend framework.

But the work experience in recent months has made me reflect, and I began to rethink the most famous question of the year: "If it is really completely object-oriented, why don't we use JAVA directly? Why do we need two JAVA?" Yes , One of the reasons for using PHP is that we do not necessarily have to be object-oriented. All programming technologies and programming concepts are just means. Meeting customer needs in the shortest time is our goal. It is undoubtedly wrong to talk about any technology without this goal. A very typical example is the open source forum In the program, everyone in PHPER respects PHPBB, but scorns the technical content of DISUCZ's code. However, when it comes to actually building a forum, which of us uses PHPBB? Most of the forums in China are owned by DISCUZ. In the past two years or so, I have been stuck on object-oriented and wasted a lot of time. This is a serious mistake I made.

So, I decided to reorganize my understanding of PHP programming. In the future, when selecting projects, I can choose a more appropriate architecture instead of just following technology. Welcome everyone to make bricks.

1. The role of functions

To this day, any friend who is not a computer major should have learned a computer language. In China, it is usually basic. If you are lucky, it may also be C, branch statements and Loop statements are a compulsory part of it, and if you don't learn functions well, you will probably be careless and pass. Even if there is no such thing as a function in the world, the program can still complete all functions (what a pity, I have just seen such a project in the past few months).

So, what do we need functions for? Countless textbooks tell us that it is for reusability. Yes, after a function is written, if you use the same function next time, you can just call it directly without having to write it again. This is the original intention and basic function of function invention. However, if we expect a function to be less commonly used, should we not use the function? No, even if we adopt process-oriented programming, we still need to use functions as much as possible, subdivide the functions as much as possible, and write an independent function for each function. Using functional programming has the following obvious advantages:

Clear logic. No matter how complex a function is, when it is subdivided and subdivided into multiple single functions, the logic of each single function is very simple. We can easily fill in the code according to the logic without having to worry about it. ;

Easy to test. Writing a program using functions actually creates a natural interruption for the program. We can quickly know which piece of code has an error. Every programmer should know that the time we spend testing code is usually twice or even three times the time we spend writing code.

Easy to read. After a program has been written for a period of time, customers find problems when using it, or need to change functions. Programmers may not be able to remember clearly even the code they wrote themselves, and when reading a program mainly written by functions , the main program is basically an outline, and we can quickly find the corresponding functions along the main program's context.

Easy to reuse. Usually, a function must have been tested when it is completed. As long as the test is more careful at the time, you can assume that the function is correct in the future. You can call it according to the function description at any time without paying attention to the details.

Quick modification. Sometimes we cannot avoid some functional modifications. When you call the same functional function in multiple programs, as long as you modify this function, everything will change at the same time, and you no longer need to modify it one by one.

Because of the above advantages, using functions for process-oriented programming is a method recognized by everyone. I have never seen anyone questioning it in any forum.

2. Code comments

Different from the habits of many people, I like a lot of comments, and they are comments that comply with the phpdocument standard. In this way, when I or my colleagues use professional editors such as zend studio or netbeans When the code is opened in the browser, if you enter the first letter, the functions and methods I wrote will automatically pop up, and then you can see the function functions, usage, parameter requirements and return format I commented in Chinese. Every programmer hopes to have as many code comments as possible, but many people rarely write comments. I learned some comments in forums and QQ groups, and found that this is probably not caused by laziness. They don’t write comments or rarely write comments. Writing notes is more due to the fear of unemployment and lack of basic self-confidence, so that it is expected that it will be difficult for others to take over to ensure the stability of one's position.

3. Replace functions with classes

Finally let’s talk about the basic methods of object-oriented programming. In classes, we call variables attributes and functions called methods. Every time foreigners come up with a new concept, they always like to do some new naming. The advantage of this is , when we mentioned properties and methods, we always seemed more knowledgeable than those who talked about variables and functions. Of course, in essence, they are exactly the same thing.

Why use classes? According to my personal understanding, initially, this is mostly due to the scope of variables. The security of global variables has been mentioned in the introductory tutorial of C language. Not only is it easy to create loopholes and be hacked, but more often, when you write your own code, you will also have various expectations because of the same name of the global variable. No trouble. If you pass each variable with parameters, it will be cumbersome. Thanks to a great programming tool like Netbeans, I actually don't have to enter these variables manually, I just look at them in displeasure. Obviously it is a variable used by most functions or at least a group of functions, but it always feels uncomfortable to have to pass values ​​repeatedly. So, there are classes, and, after PHP5.0, the scope of attributes (variables) and methods (functions) can be defined in detail in the class.

At the same time, another basic benefit of using classes is that you can group functions. When there are enough functions, it will be difficult to find them. Separate the functions by class. Those methods that are only called by other functions and do not need to be called directly by users can simply be made private to prevent colleagues from accidentally calling them. In this way, a The public function library is completely decomposed into multiple classes.

Many times, the basic functions of a class are of universal value. We can copy a class from one project to another without worrying about anything going wrong. This is because it does not have its own attribute values ​​and scopes. function group cannot do this.

One issue that needs to be clarified here is that many people mistakenly believe that dividing a function library into multiple functions will speed up program execution. Their understanding is that each page only calls the function library or class that they use. , the file size is smaller and the speed is naturally faster. In fact, the actual situation is the opposite. We all know that when we use computers, the speed may be slower when opening a WORD file for the first time, but the speed will be much faster when opening it for the second time shortly after closing. This is because that WORD files and the WORD software itself are cached in memory. In the same way, no matter how big a function library is, it is cached when the page is called for the first time, and it will naturally be much faster when it is opened again. At the same time, if a page originally contains a function library, if After decomposition, it becomes necessary to include multiple files, and file seeking takes more time than loading. Therefore, even if the page is opened without caching, decomposing a function library will reduce the execution speed of the program; in addition, classes The instantiation also takes a certain amount of time. Of course, with today's computer hardware, these speed losses are completely negligible. Therefore, the development of hardware is also one of the foundations for the popularity of object-oriented programming.

So, in process-oriented programs, we will still use classes. Of course, in process-oriented programs, classes are only needed in three situations:

The project is large enough, and a function library will When it makes people faint;

When we find that a certain function we wrote is universal;

When we call a class we wrote before or an open source class published by others online.

After using simple classes, you still cannot claim that your website is object-oriented. I just added "(Part 1)" after the title of this post. That is to say, in the rest of this article, we will still only talk about the technologies that can be used in process-oriented. Of course, they are also suitable for Object-oriented. I will express my understanding of object orientation in the next post.

4. Templates

The famous smarty, even if you have never used it, you must have heard of it. I first got to know it through xoops. At that time, I only made a simple message board. Learning SMARTY can be said to have taken a lot of effort. I remember that the best SMARTY online tutorial I found at that time was Big Brother’s smarty tutorial. I finally understood it. After a while, the brothers in Joy International Village collaborated to translate the entire smarty document, but at that time, I decided to give up. Smarty, because I insist that there is no difference between {$x} and c863f84193f84abe9bd10ecc8ce5f014. The so-called template, include, is enough. In order to save a few letters, I use such a big thing. It's quite unworthy. Well, here is an explanation of how to use simple PHP templates that I, oh, still use sometimes today:

文件demo.php:    
48    
49    view plaincopy to clipboardprint?    
50    <?php     
51    $userName=&#39;张三&#39;;      
52    include_once &#39;templates/demo.phtml&#39;;      
53    ?>    
54    <?php    
55    $userName=&#39;张三&#39;;    
56    include_once &#39;templates/demo.phtml&#39;;    
57    ?>    
58    文件demo.phtml:    
59    
60    view plaincopy to clipboardprint?    
61    <html>      
62    ......      
63    <body>      
64    你好,<?php  echo $userName;?>      
65    </body>      
66    </html>     
67    <html>    
68    ......    
69    <body>    
70    你好,<?php  echo $userName;?>    
71    </body>    
72    </html>

Look, no technology is used, isn’t it just a template? For a while, every time there was a discussion on smarty in the forum, I always wanted to promote my idea. Unfortunately, people were quiet and there was no response. Until the year before last, cakephp was introduced to China. The template technology used was very similar to my idea. Soon, After that, zend launched its own framework, which also used PHP as a natural template. In the same year, smarty was no longer developed as a core sub-project of PHP. If you visit http://smarty.php.net, you can see A reminder:

76

77 Smarty is no longer a subproject of the PHP project, and has subsequently moved to its own domain: www.smarty.net

78

79 Therefore, it is absolutely necessary to separate pages and programs. , however, template technology represented by smarty is not necessary. Unless you are doing open source programs or self-service website building, there is no way to control the security of templates. Otherwise, there is no need to use templates at all.

80

81 5. Generating static pages VS caching + pseudo-static

82

83 When I first started building a website with PHP, the first CMS system I used was called 9466 article, which used the static HTML generation technology I was amazed. Although the version at that time still had many functional deficiencies, I still spent a lot of effort to modify and learn it, and posted my modifications online. The amazing thing is that I just googled "9466 "slime modified version", there are actually many websites that provide downloads. In 2006, I made a website for a company, the URL is http://www.nbssdz.com, this time I wrote the CMS from scratch, and I also used it. Generate static page technology. However, now, I no longer use this technology. Open source programs such as joomla, phpwind, discuz and zend framework have given us another technology demonstration: pseudo-static.

84

85 There are two benefits of generating static pages. One is to increase website access speed and reduce server load. The other is to optimize search engines and allow search engines to include more pages of this site. The disadvantage of static pages is, of course, "static". It sounds like nonsense, but many dynamic functions cannot be implemented on static pages, such as displaying different content according to different user permissions. Therefore, pseudo-static is becoming popular now. The function of pseudo-static, as the name suggests, is to forge static URLs for dynamic pages to attract search engine inclusion. My website http://www.10000j.com is written based on zend framework, so it naturally has pseudo-static function. Of course, by default The URL directory format is too deep and is not conducive to inclusion. I will take the time to make changes after the year. My other website work: http://czj.kiloweb.cn has optimized the directory format. You can see that the link format is Customization is very flexible. Of course, the server load of pseudo-static is not only higher than that of static pages, but also higher than that of ordinary dynamic pages. Therefore, we must use caching flexibly to improve website response speed. Even so, pseudo-static still does not have an advantage in terms of response speed.

86

87 Therefore, for traditional content publishing categories with few functional requirements and websites with overloaded servers, we can still use the technology of generating static pages, while for websites that have permissions, click counts, etc. and require long-term maintenance To increase functionality or even for websites with independent servers, pseudo-static technology should be used. After all, some functions cannot be realized by static pages. Even if some functions can be "find a way" to achieve them (such as through ajax and iframe), the time cost of "finding a way" is too high.

88

89 6. Ajax

90

91 Ajax is an exciting technology, but the inconvenience of AJAX is that the amount of code on the website has greatly increased. In a recent project, because the page used gb2312, and the load() function of the jquery framework I used only supported utf8, I had to use iframe, and then I found out - well, this is a bit magical, after using it for so many years Iframe, after using jquery for nearly two years, I discovered that iframe is actually not bad, and it allowed me to write a lot less code. In the past year or so, I have used jquery to do a lot of things that made my boss depressed: I made some special effects that customers have never asked for, just because they are technically more dazzling, which wastes a lot of time and makes people who don’t understand jquery The artist and boss have no way to modify it themselves. So, what I want to say is that ajax is a very good thing, and jquery is the first-class ajax framework. However, good things should not be abused. You should start from the actual situation and only use them when there is a need, rather than asking me what I said before. Time is like that, you have to use it if there is a need, and you have to use it if there is no need to create a need.

92

93 7. xml and json

94

95 The advantage of frequenting the forum is that you can always keep abreast of the development trends of popular technologies. For example, one day the year before last, many people suddenly started to propose using json instead of xml. I support this suggestion with both hands. In addition to improving access speed, using json will also greatly improve development efficiency. json_encode()

96 , json_decode(), just two simple functions, can easily convert PHP arrays and json directly, which is far more convenient than simplexml and dom. Therefore, most of the time, we are neither making Google's sitemap nor RSS. We are just passing values ​​to jquery. Just use json. There is no need to use xml.


The above is the content of Rethinking PHP Programming Methods (Part 1). For more related content, please pay attention to the PHP Chinese website (www.php.cn)!




















Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn