PHP is an efficient network programming language because it has the advantages of writing flexible, rapid operation, and rapidly become the preferred language of web programmers. A fewer authoritative surveys show that there are now 31.6% of websites use PHP as the primary server-side programming language. However, it is not easy to be a PHP programming master. It is not as much as many people imagine, as long as you can quickly write a few simple code to solve a complex problem is PHP programming master, the real PHP master needs to consider more other issues. The following three criteria are criteria that a mature PHP programmer should follow in programming. 1. Lazy is gold 2. Writing a beautiful code 3. Pursue the speed of the program, not the speed of programming, is lazy to be a lazy programmer? This idea is too strange! Because the busiest person in this world may be a computer programmer. But it is because the programmer is too busy, so I should learn to be lazy when I have programmed. For a programmer, there are two lazy methods: one, boldly use the existing people's program code, integrate these code into your own procedure or project. Second, it is written some useful code to establish a library. When writing a program in the future, you can eliminate many repetitive labor, and you can naturally lazy. These two lazy methods are very suitable for PHP programmers. First, PHP is a language that is born and growing in a freely open environment. There are thousands of programmers around the world, they have been constantly struggling for PHP, they are willing to share their smart talents and their own code with others. You can find a lot of excellent program code from some PHP websites, mailing lists, newsgroups every day. In this way, I don't encourage you to wait for someone to write code for you, but you can "stand on the shoulders of the great man", fully promote "brought-to-the-counter", smartly applying other people's program code can save you a lot time. Second, in PHP, you can easily build your own library, so you can save a lot of trouble when you write a program later. The following author introduces several universal functions, some of these functions from some open source projects, some are selected from the mailing list. If you can join them to your own library, you will find yourself sooner or later. 1. One of the advantages of PHP is one of the advantages of PHP compared to other CGI functions than other CGI functions. However, in PHP, some specific functions are used for different databases to deal with, lack of common database processing functions. This greatly reduces the portability of program code, which also brought a lot of inconvenience to friends programming. On the Internet, many programmers have solved this problem through the package class. They have written unified functions to handle any popular databases - whether in the Linux world popular mysql or a wide popular SQL Server on the Windows platform. As far as I personally, I really like to use these functions because some simple functions such as "query", "next_record" can be used, without considering the connection of the database, the database handles these complex things, no need What database is considered to use. If you need these functions, you can get the following URLs: http://phplib.netuse.de/ http://phpclasses.upperDesign.com/browse.html/Package/20 http: // phpdb .linuxbox.com / 2. Variable debugging function PHP program debugging has always been a headache, it is neither a integrated compilation debugging environment like high-class languages such as VB, and you don't want Perl to be in Linux or DOS Environment. Run directly. In fact, we can complete the debugging of PHP through flexible use of the Echo statement.
The following functions allow you to view any variables in the program and their values at any time. Function SS_ARRAY_AS_STRING (& $ Array, $ Column = 0) {$ Str = "Array (N"; while (list ($ VAR, $ VAL) = Each ($ array) {for ($ I = 0; $ i < $ Column 1; $ I ) {$ Str. = "";} $ Str. = $ var. ==>; $ str. = ss_as_string ($ VAL, $ Column 1). "n";} for $ I = 0; $ I ) {$ Str. = "";} Return $ Str.);} Function SS_OBJECT_AS_STRING (& $ Object, $ Column = 0) {IF ($ Object- > classname)) {Return "$ Object";} else {$ Str = $ Object-> ClassName. "(N"; While (List (, $ VAR) = Each ($ Object-> Persistent_slots) {for ($ i = 0; $ I ) {$ Str. = "";} Global $$ VAR; $ Str. = $ var. ==>; $ str. = ss_as_string ($$ var, column 1). "N";} for ($ I = 0; $ I <$ column; $ i ) {$ Str. = "";} Return $ STR.);}} Function SS_ASTRING (& $ Thing, $ Column = 0) {if (is_object ($ thing)) {return ss_object_as_string ($ thing, $ column);} elseif (is_array ($ thing)) {return ss_array_as_string ($ thing, $ column);} elseif (is_double ($ thing ))) {Return "Double (". $ thing. ")";} elseif (is_long ($ thing) {Return "Long ("$ 11)";} elseif (is_string) {return "string (". $ thing. ")";} else {return "unknown (". $ thing. ") } When you need it, you can simply add the following code to view the types and values of the variables used in the program (including arrays and objects): echo ss_s_string; use the following statement, we can Directly view the values of all variables in the program: echo ss_s_string ($ global); 3. Controlling the function of log information Debugging another important way to view the log information. If it is convenient to control the level of LOG information and the display content of LOG information, it will bring more convenience to program debugging.
The following functions can be easily implemented. $ SS_LOG_LEVEL = 0; $ ss_log_filename = / tmp / ss-log; $ ss_log_levels = array (none => 0, error => 1, info => 2, debug => 3); function ss_log_set_level ($ level = error) { global $ ss_log_level; $ ss_log_level = $ level;} function ss_log ($ level, $ message) {global $ ss_log_level, $ ss-log-filename; if ($ ss_log_levels [$ ss_log_level] <$ ss_log_levels [$ level]) {/ / Do not display log information returnaf false;} $ fd = fopen ($ ss_log_filename, "a "); FPUTS ($ FD, $ level. - [.ss_timestamp_pretty ().] -. $ Message. "N"); fclose ( $ fd); Return True;} Function SS_LOG_RESET () {Global $ ss_log_filename; @unlink ($ ss_log_filename);} In the above function, there are four LOG level variables. When running a PHP program, only when the level of logs is lower than the preset level value, log information can be recorded and displayed. For example, the following statement is added to the program: SS_LOG_SET_LEVEL (INFO); then when running the PHP program, only the ERROR and INFO level log information can be recorded and displayed, and the information of the Debug grade is ignored. In addition, we can also set the information displayed, whose statement is as follows: SS_LOG (Error, "Testing Level Error"); SS_LOG (INFO, "Testing Level Info); SS_LOG (Debug," Testing Level Debug " ); You can also use the following statements at any time to empty log information: ss_log_reset (); 4. Speed test function
To optimize the code, we need a way to test the code run time, thereby selecting the optimal code. The following function of time may be required for the test run code: function ss_timing_start ($ name = default) {global $ ss_timing_start_times; $ ss_timing_start_times [$ name] = explode (, microtime ());} function ss_timing_stop ($ name = default) { global $ ss_timing_stop_times; $ ss_timing_stop_times [$ name] = explode (, microtime ());} function ss_timing_current ($ name = default) {global $ ss_timing_start_times, $ ss_timing_stop_times; if (! isset ($ ss_timing_start_times [$ name])) { return 0;} if {$ stop_time = explode (, microtime ()) (isset ($ ss_timing_stop_times [$ name])!);} else {$ stop_time = $ ss_timing_stop_times [$ name];} $ current = $ stop_time [1 ] - $ s_timing_start_times [$ name] [1]; $ current = $ stop_time [0] - $ ss_timing_start_times [$ name] [0]; Return $ current;} Now you can easily check the execution time of any piece of code, Even we can use multiple timers at the same time, just set different parameters as the name of the timer when using several functions described above. 5. Debugging and optimizing the operation of the database is critical to the database. Although many books and articles have been awarded some ways to quickly run the database, all methods must be inspected. Below we will integrate the query () function in the phplib library, and several functions described above, we will write into a new Query () function, and this function adds the monitoring function of the runtime compared to the original function. function query ($ Query_String, $ halt_on_error = 1) {$ this-> connect (); ss_timing_start (); $ this-> Query_ID = @mysql_query ($ Query_String, $ this-> Link_ID); ss_timing_stop (); ss_log (INFO SS_TIMING_CURRENT (). SECS -. $ query_string; $ this-> row = 0; $ this-> errno = mysql_errno (); $ this-> error = mysql_error (); if ($ HALT_ON_ERROR &&! $ this-> Query_ID) {$ this-> Halt ("Invalid SQL:". $ Query_string);} Return $ this-> query_id;}
Second, write a beautiful code 1. Some of the code is used to handle some transactions, such as operating databases, mathematical operations, etc., and some code is only transaction, such as operating databases, mathematical operations, etc. Displayed, for example, some PHP code on the web browser in the form of an HTML using the ECHO statement, and the HTML code that directly embeds the PHP program. First we should clearly refer to these two codes, refer to the former as a background program, refer to the latter as a front-end program. Because PHP is an embedded programming language, that is, all PHP code can be embedded in the HTML code, which has brought many conveniences. However, "the object must be reverse", if the PHP code and HTML code are mixed in a longer program, which will make the program messy, not conducive to the maintenance and reading of the program. So we need to transplant the PHP code in these programs in the HTML code as much as possible. Pack these code into a function in a special file, then use the include statement in the HTML code to include these files in the appropriate location. Call these functions. On the one hand, the HTML code and PHP code are easy to read. On the other hand, because the HTML code needs to be continuously updated, and this separation method can ensure that the background program will not be destroyed. Unlike front-end procedures, the background program is more pursuit of stability, structured, and very few changes, so we should carefully design and manage. In fact, in the design desk program, it is worthwhile to put a lot of time. 2. Flexible use of the included file As mentioned earlier, the background program should be arranged in a range of included files. The included file can be dynamically loaded when needed by the include statement, or in the php.ini file by using the auto_prepend_file command to pre-load. If the latter method is used, although it is good for all the benefits of life, there are some shortcomings worthy of our attention. One of the following paragraphs show us that a huge inclusion requires a certain amount of time: Require (TIMING.INC); SS_TIMING_START (); include (Test.inc); ss_timing_stop (); echo .ss_timing_current ().;?>> In the above code, Test.inc is a 1000 line containing file, the result shows that the resolution of this containing file is 0.6 seconds, for a large website, this speed is not negligible. Another disadvantage to use the included file is that if an error in a file is an error, the PHP program of the entire website will not be able to run. So use it and be careful. In fact, slightly handle the included file, you can make the included files only parsed when needed. The following code makes the abc.inc file only as parsing when the program needs: if (__liba_inc)) return; define (__liba_inc, 1); / * * code ... * /?> 3. Using object-oriented The programming method PHP is also an object-oriented language. The object-oriented programming method is an excellent programmer's very respected software design method. In PHP programming, it can fully utilize the advantages of object-oriented language, and the objects in the programming Package. In the previous code, we use object-oriented methods. For example, when you manage the database, we encapsulate query () functions into the database class, which greatly facilitates the management of code, and adds the readability of the program. Third, pursue the speed of the program, not the speed of programming, the program running speed and web download speed is an important factor in the success or failure of the relationship.
As a web programmer, you should pay more attention to the running speed of the code. The following methods described below increases the running speed of the code to varying degrees. 1. Use the embedded HTML code instead of the PHP's ECHO statement. Because PHP is an embedded Web programming language, HTML code and PHP code can be embedded with each other. However, many programmers worry that "" embedded PHP code will call the PHP interpreter multiple times in HTML code, thereby reducing the speed of the PHP code, so I would rather use the PHP's Echo statement to output HTML code, not directly Use HTML code. But the facts are just right. Each PHP page only calls a PHP interpreter to explain all PHP code, so it is only embedded in the PHP code when needed, and most of them use the HTML code input result, not only does not reduce the running speed of the program, but also Because the resolution of the ECHO statement is reduced, the running speed of the code can be improved. One of the following sections prove our conclusion. In this code, we used the time test functions previously described. Using Str-Replace instead of EREG-Replace habits Using PERL programming programmer more willing to use EREG_REPLACE to complete strings because of the usage of EREG_REPLACE and the Umage Matches in Perl in PHL. However, the following code is proved that using Str_Replace instead EREG_REPLACE will greatly improve the running speed of the code.
Test Str_Replace and EREG_REPLACE running speed
// This code test STR_REPLACE running speed
EMPHASIS;?>
For ($ I = 0; $ I <1000; $ I ) {STR_REPLACE (I>, B>, $ String).;}?>
// This code test EREG_REPLACE running speed
For ($ I = 0; $ I <1000; $ I ) {EREG_REPLACE (<([/] *) I>, <1b>, $ String).;}?>
// Print results
in conclusion
Time to use Str_Replace -
Using EREG_PATTERN - Run the above code, the result is: Time to use Str_Replace - 0.089757 Time to use EREG_Pattern - 0.248881 From Running Results We can see that using Str_Replace replaces EREG_REPLACE as a string replacement function, greatly improved code Running speed. 3. Note that the reference PHP of the string is the same as many other programming languages, you can use dual quotation marks ("") to reference strings or single quotes (). However, in PHP, if you use a double quotation number to reference a string, the PHP parser will first analyze the reference to the variable in the string, and the variable will be replaced. If it is a single quotes, it is not so complex-display all the strings that are included directly. Obviously, in PHP programming, if you use single quotes to reference string variables, it is quite more than using double quotes. 4. Avoid using joint operations in the database, PHP's database function is very powerful than other web programming languages. However, in PHP's operation is still a very cost-time, so as a web programmer, try to minimize the query operation of the database, and should establish an appropriate index for the database. Another thing that is worth noting is that when using a PHP Operating Database, the joint operation of multiple data sheets is not used as much as possible, although the federation can enhance the query function of the database, but greatly increase the burden on the server. To illustrate this problem, we can take a look at this simple example below. We created two data tables foo and BIG_FOO in the database. In the data sheet foo, there is only one field that contains all natural numbers between 1-1000. Data table BIG_FOO also has only one field, but includes all natural numbers between 1-1,000,000. Therefore, from the size, BIG_FOO is equal to FOO and its own joint operation. $ DB-> Query ("Select * from foo"); 0.032273 Secs $ db-> next_record (); 0.000489999999999 second $ db-> query ("INSERT INTO FOO VALUES (NULL)"); 0.019506 SECS $ DB-> Query ("Select * from foo as a, foo as b"); 17.280596 SECS $ db-> query ("SELECT * from Foo as a, foo as b where A.id> B.ID"); 14.645251 SECS $ dB- > query ("Select * from foo as a, foo as b where A.id = B.ID"); 0.041269 Secs $ db-> query ("Select * from big_foo"); 25.393672 SECS From above, we can find For two data sheets with 1000 records, the speed is not much faster than the large data sheet for a 100,000,000 records. 5. Note that the difference between INCLUDE and REQUIRE is in PHP, which is the same as the require (), but there are some differences in the usage. Include () is conditional containing functions, and request () is unconditional Contains a function.