PHP master road] Repost [

xiaoxiao2021-03-06  107

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.

Lazy is gold

2. Write a beautiful code

3. Pursue the speed of the program, not the speed of programming

First, lazy is gold

Do you have 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. Universal Database Processing Function

One of the advantages of php compared to other CGI functions is to have very powerful database processing capabilities. 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 debug function

The debugging of the PHP program has always been a headache. It is neither a integrated compilation debug environment like a high-level language such as VB, and does not want Perl to run directly in the Linux or DOS environment. 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 S_Array_as_String (& $ Array, $ Column = 0) {

$ Str = "Array (ARRAY)

N ";

While (List ($ VAR, $ VAL) = Each ($ array) {

For ($ I = 0; $ i <$ column 1; $ i ) {

$ Str. = "& Nbsp; & nbsp; & nbsp; & nbsp;

}

$ Str. = $ VAR. ==>;

$ Str. = SS_AS_STRING ($ VAL, $ Column 1). "

N ";

}

For ($ I = 0; $ i <$ column; $ i ) {

$ Str. = "& Nbsp; & nbsp; & nbsp; & nbsp;

}

Return $ STR.

}

Function SS_OBJECT_AS_STRING (& $ Object, $ Column = 0) {

IF (Empty ($ Object-> ClassName) {

Return "$ Object";

}

Else {

$ Str = $ Object-> ClassName. "

N ";

While (List (, $ VAR) = Each ($ Object-> Persistent_slots) {

For ($ I = 0; $ i <$ column; $ i ) {

$ Str. = "& Nbsp; & nbsp; & nbsp; & nbsp;

}

Global $$ VAR;

$ Str. = $ VAR. ==>;

$ Str. = Ss_as_string ($$ VAR, Column 1). "

N ";

}

For ($ I = 0; $ i <$ column; $ i ) {

$ Str. = "& Nbsp; & nbsp; & nbsp; & nbsp;

}

Return $ STR.

}

}

Function SS_AS_STRING (& $ Thing, $ column = 0) {

IF (is_Object ($ thing) {

Return SS_Object_as_string ($ Thing, $ Column);

Elseif (is_ARRAY) {

RETURN SS_ARRAY_AS_STRING ($ Thing, $ Column);

}

Elseif (is_double) {

Return "Double (". $ think. ")

}

Elseif (is_long ($ thing) {

Return "long (". $ think. ")

}

Elseif (is_string) {

Return "String (". $ thing. ")

}

Else {

Return "Unknown (". $ think. ")

}

}

When you need, you can simply add one of the following code to view the types and values ​​of the variables used in the program (including arrays and objects):

Echo ss_as_string ($ my_variable);

With the following statement, we can directly view the values ​​of all variables in the program:

Echo ss_as_string ($ globals);

3. Control log information

Another important way to debug PHP programs is to view 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;

$ S_log_levels = array (

None => 0,

Error => 1,

INFO => 2,

Debug => 3);

Function SS_LOG_SET_LEVEL ($ level = error) {

Global $ s_log_level;

$ Ss_LOG_LEVEL = $ level;

}

Function SS_LOG ($ Level, $ Message) {

Global $ S_LOG_LOVEL, $ ss-log-filename;

IF ($ s_log_levels [$ s_log_level] <$ s_log_levels [$ level]) {

/ / Do not display log information

Return False;

}

$ Fd = fopen ($ s_log_filename, "a ");

FPUTS ($ FD, $ level. - [.ssage_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, an additional 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 level 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 functions can test the time required to run the code:

Function SS_TIMING_START ($ name = default) {

Global $ s_timing_start_times;

$ S_timing_start_times [$ name] = evtern (, microtime ());

}

Function SS_TIMING_STOP ($ name = default) {

Global $ s_timing_stop_times;

$ SS_TIMING_STOP_TIMES [$ Name] = EXPLODE (, microtime ());

}

Function SS_TIMING_CURRENT ($ name = default) {

Global $ s_timing_start_times, $ s_timing_stop_times;

IF ($ ss_timing_start_times [$ name])) {

Return 0;

}

IF ($ ss_timing_stop_times [$ name])) {

$ STOP_TIME = EXPLODE (, microtime ());

}

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;

}

You can now easily check the execution time of any code, or even use multiple timers at the same time, just set different parameters as the name of the timer when using the above functions.

5. Debug and optimize the operation of the database

For databases, running speed is critical. 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. Separate the background program with the front-end program

When writing a PHP program, some code is used to handle some transactions, such as operational databases, mathematical operations, etc., and some of the other codes are only displayed by transaction processing, such as some use echo statements to display results in HTML format. PHP code on the web browser and HTML code that directly embeds in 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. "Now planting a tree, after the cool", in the future design work will easily use the scripted background program written now.

2. Flexible use of included files

As mentioned earlier, the background program should be arranged in a series 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 when the program needs:

IF (Defined (__liba_inc) return;

Define (__liba_inc, 1;

/ *

* Code ...

* /

?>

3. Use object-oriented programming methods

PHP is also an object-oriented language, object-oriented programming method is a well-known software design method that excellent programmers, which can fully utilize the advantages of object-oriented languages, and package the objects in the program. In the previous code, we use object-oriented methods, such as when managing the database, we encapsulate the query () function into the database class, which greatly facilitates the management of the code, increasing the readability of the program.

Third, pursue the speed of the program, not the speed of programming

In the construction of the website, the speed of program running and web download speed is an important factor in the success or failure of relationships. 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 fact is just the opposite. 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.

Use Str-Replace instead of EREG-Replace

Players who are used to using Perl more willing to use EREG_REPLACE to complete strings because of the use of EREG_REPLACE in PHP and the usage matching of PERL. 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>, , $ string).

;

}

?>

// Print results

in conclusion

Time to use Str_Replace -

Use EREG_Pattern time -

Run the above code, the result is:

Time to use Str_Replace - 0.089757

Time to use EREG_PATTERN - 0.248881

From the result of the run, we can see that using Str_Replace replaces EREG_REPLACE as a string replacement function, greatly increases the running speed of the code.

3. Note the reference to the string

PHP and 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 the PHP's operation is still a very expensive thing, so as a web programmer, try to minimize the database query operation, and should establish an appropriate index for the database. Another thing that is worth noting is that when using a PHP to operate the database, do not use the combination of multiple data sheets as much as possible, although the joint operation 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 sheets 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.00048999999999999 SECS

$ DB-> Query ("INSERT INTO Foo Values ​​(NULL));

0.019506 SECS

$ Db-> query ("SELECT * FROM FOO 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 the above operation, we can find that for two data sheets with 1000 records, the speed is not much faster than a 100,000-record large data sheet.

5. Note the difference between include and Require

In the PHP becoming, include () is the same as the require (), but there are some different uses, including the condition contains a function, and request () is unconditional containing functions. For example, in one of the following examples, if the variable $ somgthing is true, the file Somefile is included:

IF ($ something) {

Include ("Somefile");

}

But regardless of $ something, the following code will contain the files Somefile to enter the file:

IF ($ something) {

Require ("somefile");

}

This interesting example below fully illustrates the difference between the two functions.

$ I = 1;

While ($ I <3) {

Require ("Somefile. $ I");

$ I ;

}

In this code, when each cycle, the program will contain the same file. Obviously this is not the original intention of the programmer, from the code we can see that this code wants to include different files in each cycle. If you want to complete this feature, you must help the function include ():

$ I = 1;

While ($ I <3) {

INCLUDE ("Somefile. $ I");

$ I ;

}

6. Note the difference between ECHO and PRINT

The functionality of Echo and Print in PHP is basically the same, but there is a fine difference between the two. In the PHP code, print can be used as a normal function, for example, the value of the variable $ RES will be 1 after execution of the following code.

$ RET = Print "Hello World";

This means that Print can be used in some complex expressions, while Echo can't. Similarly, the running speed of the ECHO statement in the code is slightly fast than the Print statement, because the ECHO statement does not require returns to any value.

转载请注明原文地址:https://www.9cbs.com/read-124605.html

New Post(0)