PHP experts (continuously improving)

Source: Internet
Author: User
Tags php and mysql wordpress version

PHP is an efficient network programming language. It is a preferred language for web programmers because of its flexible programming and fast running. A recent authoritative survey showed that 31.6% of websites now use PHP as the main server programming language.
However, it is not easy to become a PHP programming expert. As many people think, as long as they can quickly write a few simple codes to solve a complicated problem, they are PHP programmers, real PHP experts also need to consider more other issues. The following three principles should be followed by a mature PHP programmer in programming.
1. Laziness is gold
2. write beautiful code
3. The pursuit of program speed rather than programming speed
1. Laziness is gold
Be a lazy programmer? This is a strange idea! This is because the busiest person in the world may be a computer programmer. But it is because programmers are too busy that they should learn to be lazy during programming.
For a programmer, there are two lazy Methods: First, boldly use the code of someone else's program to integrate the code into your own program or project. The second is to write some useful code to create a function library, which can be easily written in the future, saving a lot of repetitive work, so you can naturally be a little lazy.
Both of these methods are very suitable for PHP programmers.
First of all, PHP is a language born and grown in a free and open environment. There are thousands of programmers around the world who are constantly striving for PHP perfection and are willing to share their talents and code with others. Every day, you can find a lot of excellent program code from some PHP websites, email lists, and newsgroups. In this way, I do not encourage you to wait all day for others to write code for you, but you can "stand on the shoulders of great people" and fully carry forward "ism ", smart Application of others' program code can save you a lot of time. Second, in PHP, you can easily create your own function library, which saves you a lot of trouble when writing programs later.
Below I will introduce several common functions, some of which come from some open source projects on the Internet and some of which are selected from the mail list. If you can add them to your own function library, sooner or later you will find yourself benefiting.
1. Common Database processing functions
Compared with other CGI functions, one of the advantages of PHP is its powerful database processing capability. However, in PHP, some specific functions are used for different databases for special processing, and common database processing functions are missing. This greatly reduces the portability of program code, which also brings a lot of inconvenience to beginners.
On the Internet, many programmers solve this problem through encapsulation. They have compiled unified functions to deal with any popular databases-MySQL, which is popular in the Linux World, and sqlserver, which is widely used on Windows platforms. I personally like to use these functions, because some simple functions such as "query" and "next_record" can be used directly, you do not need to consider the complex things such as database connection and database handle, and do not need to consider what type of database is used.
If you need these functions, you can access the following urls:
Http://phplib.netuse.de/
Http://phpclasses.UpperDesign.com/browse.html/package/20
Http://phpdb.linuxbox.com/
2. Variable debugging Functions
Debugging PHP programs has always been a headache. It does not have an integrated compilation and debugging environment like other advanced languages such as VB, and do not want Perl to run in a Linux or DOS environment. In fact, we can use echo statements flexibly to debug PHP.
The following functions allow you to view the types and values of any variables in the program 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. = "& nbsp ;";
}
$ Str. = $ var. =>;
$ Str. = ss_as_string ($ Val, $ column + 1 )."
N ";
}
For ($ I = 0; $ I <$ column; $ I ++ ){
$ Str. = "& 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 ;";
}
Global $ var;
$ Str. = $ var. =>;
$ Str. = ss_as_string ($ var, column + 1 )."
N ";
}
For ($ I = 0; $ I <$ column; $ I ++ ){
$ Str. = "& nbsp ;";
}
Return $ Str .);
}
}
Function ss_as_string (& $ 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 (". $ thing .")";
}
Elseif (is_string ($ thing )){
Return "string (". $ thing .")";
}
Else {
Return "unknown (". $ thing .")";
}
}
When necessary, simply add the following code to the program to view the types and values of the variables used in the Program (including arrays and objects:
Echo ss_as_string ($ my_variable );
Using the following statement, we can directly view the values of all the variables in the program:
Echo ss_as_string ($ globals );
3. functions that control log information
Another important method for debugging PHP programs is to view log information. If you can easily control the log information level and the log information display content, 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
Return 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, the log information can be recorded and displayed only when the log level is lower than the preset level value. For example, add the following statement to the program:
Ss_log_set_level (Info );
When running a PHP program, only log information at the error and info level can be recorded and displayed, while debug-level information is ignored. In addition, you can set the displayed information. The 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 statement to clear log information at any time:
Ss_log_reset ();
4. speed test functions

To optimize the code, we need a method that can test the code running time to select the best code. The following function can test the time required to run the 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 (! Isset ($ ss_timing_stop_times [$ name]) {
$ Stop_time = explode (, microtime ());
}
Else {
$ Stop_time = $ ss_timing_stop_times [$ name];
}
$ Current = $ stop_time [1]-$ ss_timing_start_times [$ name] [1];
$ Current + = $ stop_time [0]-$ ss_timing_start_times [$ name] [0];
Return $ current;
}
Now we can easily check the execution time of any piece of code. We can even use multiple timers at the same time, you only need to set different parameters as the timer name when using the above functions.
5. debug and optimize database operations
For databases, the running speed is crucial. Although many books and articles teach you how to quickly run databases, all methods must be tested in practice. Next, we will combine the query () function in the phplib function library with the functions described above to compile a new query () function. Compared with the original function, this function adds the runtime monitoring 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;
}

2. write beautiful code
1. Separate background programs from front-end programs
When writing a PHP program, some code is used to process some transactions, such as database operations and mathematical operations. Other code is only displayed as the result of transaction processing, for example, some PHP code that uses echo statements to display results in HTML format on a Web browser and the HTML code that directly embeds the PHP program. First, we should clearly distinguish the two types of code, the former is called the background program, and the latter is called the front-end program.
Because PHP is an embedded programming language, that is to say, all PHP code can be embedded into HTML code, which brings a lot of convenience for programming. However, if PHP code and HTML code are mixed in a long program, this will make the program messy, not conducive to program maintenance and reading. Therefore, we need to try to port the PHP code in these programs mixed with HTML code, and encapsulate the code into a function in a special file, then, use the include statement in the HTML code to include these files, and call these functions at the appropriate location.
On the one hand, this method makes HTML code and PHP code easy to read, and on the other hand, because HTML code needs to be constantly updated, and this separation method can ensure that the background program will not be destroyed.
Different from front-end programs, background programs are more stable, structured, and rarely changed. Therefore, they should be carefully designed and managed. In fact, it is worthwhile to invest a lot of time in the design of a program. "planting trees now and enjoying the cold in the future" will make it easy to use the background program compiled in the future design work.
2. flexible use of include files
As mentioned above, background programs should be arranged in a series of include files. The include statement can be used to dynamically load the included files as needed, or the auto_prepend_file command can be used in the PHP. ini file to automatically load the files in advance.
If the latter method is used, although the benefits have been achieved once and for all, there are also some shortcomings that deserve our attention. The following code shows that it takes some time to parse a large file inclusion:
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-row file. It takes 0.6 seconds to parse the file. For a large website, this speed is not negligible.
Another disadvantage of using include files is that if a statement in a file is incorrect, the PHP program of the entire website cannot run. So be careful when using it.
In fact, the inclusion file can be parsed only when necessary. The following code parses the ABC. inc file only when the program needs it:
If (defined (_ liba_inc) return;
Define (_ liba_inc, 1 );
/*
* Code...
*/
?>
3. Use object-oriented programming methods
PHP is also an object-oriented language. The object-oriented programming method is a software design method highly praised by excellent programmers, in PHP programming, we can give full play to the advantages of object-oriented language and encapsulate the objects in programming. In the previous code, we used an object-oriented method. For example, when managing a database, we encapsulated the query () function into the database class, which greatly facilitates code management, added the readability of the program.
3. Pursuing program speed, not programming speed
During website construction, the program running speed and website download speed are important factors that affect the success or failure of the website. As a web programmer, you should pay more attention to the code running speed. The methods described below increase the code running speed to varying degrees.
1. Use embedded HTML code instead of PHP echo statements.
Because PHP is an embedded WEB programming language, HTML code and PHP code can be embedded into each other. However, many programmers are worried that the PHP interpreter will be called multiple times when "" is used too much in HTML code to reduce the running speed of PHP code, therefore, we would rather use PHP echo statements to output HTML code rather than directly using HTML code. But the opposite is true. Every PHP page only calls the PHP interpreter once to explain all the PHP code. Therefore, the PHP code is embedded only when necessary, and most of the time the HTML code is used to input the result directly, this will not only reduce the program running speed, but also reduce the resolution of echo statements, which can often improve the code running speed.
The following code proves our conclusion. In this Code, we used the time test function described above.

Use str-replace instead of ereg-replace
Programmers who are familiar with Perl programming are more willing to use ereg_replace to complete string replacement, because the usage of ereg_replace in PHP is similar to that of pattern matching in Perl. However, the following code proves that replacing ereg_replace with str_replace can greatly improve the code running speed.

Test the running speed of str_replace and ereg_replace

// This code tests the running speed of str_replace.

Emphasis;?>

For ($ I = 0; I I <1000; $ I ++ ){
Str_replace (I>, B>, $ string ).
;
}
?>

// This code tests the running speed of ereg_replace.

 

For ($ I = 0; I I <1000; $ I ++ ){
Ereg_replace (<([/] *) I >,</1B>, $ string ).
;
}
?>

 

 

// Print the result

Conclusion

Time when str_replace is used-

Time when ereg_pattern is used-
Run the above Code and the result is:
Time when str_replace is used-0.089757
Time when ereg_pattern is used-0.248881
From the running results, we can see that using str_replace to replace ereg_replace as a string replacement function greatly improves the code running speed.
3. Pay attention to string references.
Like many other programming languages, PHP can use double quotation marks (/"/") to reference strings, or single quotation marks (). However, in PHP, if double quotation marks are used to reference a string, the PHP parser will first analyze whether there is any reference to the variable in the string. If there is a variable, the variable will be replaced. If it is a single quotation mark, it is not so complex-directly display all strings contained in single quotation marks. Obviously, using single quotes to reference string variables in PHP programming is faster than using double quotes.
4. Avoid joint operations in the database
Compared with other Web programming languages, PHP databases are very powerful. However, running a database in PHP is still a very time-consuming and laborious task. Therefore, as a web programmer, we should minimize the number of database queries, at the same time, appropriate indexes should be created for the database. Another thing worth noting is that when using PHP to operate a database, try not to use the union operation of multiple data tables. Even though the union operation can enhance the database query function, but it greatly increases the burden on the server.
To illustrate this problem, let's take a look at the simple example below.
Two data tables Foo and big_foo are created in the database. In the data table Foo, there is only one field that contains all the natural numbers from 1. The data table big_foo also has only one field, but contains all the natural numbers from 1 to 1,000,000. Therefore, in terms of size, big_foo is equal to foo and it performs Union operations.
$ Db-> query (/"select * From Foo /");
Secs 0.032273
$ Db-> next_record ();
Secs 0.00048999999999999
$ Db-> query (/"insert into Foo values (null )/");
Secs 0.019506
$ Db-> query (/"select * From Foo as A, foo as B /");
Secs 17.280596
$ Db-> query (/"select * From Foo as A, foo as B where a. ID> B. ID /");
Secs 14.645251
$ Db-> query (/"select * From Foo as A, foo as B where a. ID = B. ID /");
Secs 0.041269
$ Db-> query (/"select * From big_foo /");
Secs 25.393672
From the above operation results, we can find that the speed of joining two data tables with 1000 records is not much faster than that of a large data table with 1000000 records.
5. Note the difference between include and require.
In PHP, The include () and require () functions are the same, but there are some differences in usage. Include () is a conditional inclusion function, while require () it is an unconditional include function. For example, in the following example, if the variable $ somgthing is true, it will contain the file somefile:
If ($ something ){
Include (/"somefile /");
}
However, no matter what value $ something takes, the following code will include the file somefile into the file:
If ($ something ){
Require (/"somefile /");
}
The following interesting example fully demonstrates the differences between the two functions.
$ I = 1;
While ($ I <3 ){
Require (/"somefile. $ I /");
$ I ++;
}
In this Code, each loop contains the same file. Obviously, this is not the original intention of the programmer. From the code, we can see that this code will include different files in each loop. To complete this function, you must turn to the include () function ():
$ I = 1;
While ($ I <3 ){
Include (/"somefile. $ I /");
$ I ++;
}
6. Note the difference between ECHO and print.
The ECHO and print functions in PHP are basically the same, but there are also slight differences between the two. Print can be used as a common function in PHP Code. For example, after executing the following code, the value of the variable $ res will be 1.
$ Ret = print/"Hello World /";
This means that print is available in some complex expressions, but Echo is not. Similarly, the echo statement runs slightly faster than the print statement in the code, because the echo statement does not require any value to be returned.
(This is not CMS, It is blog)
Although WordPress is a very good blog software for PHP and MySQL, it can be used as a CMS system. From the latest official Wordpress version upgrades, we can see that our staff are moving WordPress towards a small formal CMS.
------------------------------------------------------------------------

 

PHP programming style:

In many cases, the most valuable feature of PHP may be that its weakest link is its loose syntax. PHP can be widely used because it enables many inexperienced web developers to create powerful applications without having to think too much about planning, coherence, and documentation.
Unfortunately, many PHP source codes are bloated and difficult to read or even maintain. I deeply understand this, because I have already written a lot of such code .; -)
To avoid the above situation and many other situations. A lot of core PHP developers and group members came together and started pear, a project focusing on adding PHP extensions and plug-in repositories. It is unknown till now that documents and other things from the pear project are rarely and hard to understand. This article attempts to tell developers what they (Pear group) have done.
An important factor determining code maintainability is the code format and comments. All code of a project should be organized throughout the process. I am very persistent in the Construction of code libraries. I think programmers should do the same.
(1) indent
All the code of the developer should be written in indent mode. This is the most basic measure to improve code readability. Even if you do not comment on your code, indentation is intended for others to understand.
Your code is also very helpful.
For example:
While (hour $ x If (Bytes $ A = 1 ){
Echo A was equal to 1;
} Else {
If (Bytes $ B = 2 ){
// Do something
} Else {
// Do something else
}
}
}
The pear draft standard requires four spaces for indentation instead of tabs. I personally do not agree with this idea. I think I will continue to use the tab key. I think using tabs can make the file smaller than multiple spaces. Smaller files can be explained, uploaded, and downloaded more quickly. The use of tab is a big one, that is, when you watch other people's code, you can set the number of spaces for the tab key by yourself. I usually use the tab key with eight spaces, but recently I changed it to four spaces. I just liked to reformat the code.
(2) control structure
This depends largely on your taste. I can still see that many of the control structure codes do not contain branch statements, resulting in poor readability. If you use if statements without branches, not only will the readability become worse, when others modify your program, many bugs may occur. See the following example:
Bad example:
If (cost $ A = 1) echo a was equal to 1;
This is very hard to identify. It works normally, but the code is not appreciated by others except you.
Examples of improvements:
If (Bytes $ A = 1)
Echo A was equal to 1;
At least this code can be understood, but it still does not have good maintainability. What if I want an additional event to happen when Pipeline $ A = 1, or if I want to add a branch? If later programmers forget to add the keyword "Large arc" or "else", a bug will occur in the program.
Perfect example
If (cost $ A = 1) & (cost $ B = 2 )){
Echo A was equal to 1;
// You can easily add other codes.
} Elseif (cost $ A = 1) & (cost $ B = 3 )){
// Other operations
}
Note that there is a space after if and elseif. This separates this statement from the function call. In addition, although there are no statements in the elseif Execution Section, only comments exist, on the surface, it seems redundant, but it gives a very convenient prompt to the programmers who want to maintain the program in the future, and it is very helpful to add functions.

---------------------------------------------------------------

PHP knowledge required to become a PHP master
Every PHP developer should be familiar with the following five things before developing a web application:

1. Framework

The framework is one of the most important issues in PHP development. There are many ways to develop Web applications using PHP. There are many open-source frameworks that can be used to help rapid development and maintain higher consistency and effectiveness. The better frameworks include CakePHP, symfony, and codeigniter. Many frameworks also follow the MVC design pattern. If you have worked in this pattern, you will be familiar with it. After a while, you can even create a framework based on your own needs.

2. template engine

If you are not using a framework to execute a specific design pattern, you want to use the template engine. Whether you create or use an existing template (such as smarty) by yourself, the template engine will make your logic code independent from the HTML page (and related CSS/JS ). This greatly simplifies your code, makes modifications to the entire program fast and simple, and makes it easier for non-developers to modify your program.

3. code reuse

As I mentioned before, PHP is the best language for code reuse. From many small and medium documents to the entire database class, PHP developers can freely choose to reuse existing code when needed. In fact, you can build the entire application without writing a line of code.

4. Do not re-start to find some items

Obviously, only a few PHP developers know that PHP has many advantages. Forget the new library or complex code routines-first look at the PHP manual. For example, have you ever heard of number_format (), parse_url (), wordwrap (), or bbcode_parse ()? Take a look at the entire function reference, select a category, and you will surely find something.

5. IRC is a pleasant task.

When you have a complicated problem that cannot be solved, you can go to IRC. Many experienced developers are fascinated by the unofficial PHP support channel. You need an IRC client. If you use Firefox, chatzilla is a good plug-in. When you need help, stick your code with IRC: // irc.freenode.net/php as the header. Post your questions and wait patiently. Some kind of enthusiastic people (or multiple) will give you answers. When you get the answer, consider other questions that need help. For PHP's huge function library, no one is a battle; on IRC, gathering everyone's knowledge can solve any problem.

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.