In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "what high-quality PHP code". In daily operation, I believe many people have doubts about what kind of high-quality PHP code they have. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "what high-quality PHP code there are?" Next, please follow the editor to study!
1. Do not use relative paths
It is common to see:
Require_once ('.. /.. / lib/some_class.php')
This approach has many disadvantages: it first looks for the specified php inclusion path, and then looks for the current directory. So too many paths are checked. If the script is contained by a script in another directory, its base directory becomes the directory where the other script is located.
Another problem is that when a scheduled task runs the script, its parent directory may not be the working directory. So the best option is to use an absolute path:
View sourceprint? Define ('ROOT',' / var/www/project/'); require_once (ROOT. '.. /.. / lib/some_class.php'); / / rest of the code
We define an absolute path and the value is written to death. We can also improve it. The path / var/www/project may also change, so do we have to change it every time? No, we can use the _ _ FILE__ constant, such as:
/ / suppose your script is / var/www/project/index.php / / Then _ _ FILE__ will always have that full path. Define ('ROOT', pathinfo (_ _ FILE__, PATHINFO_DIRNAME)); require_once (ROOT. '.. /.. / lib/some_class.php'); / / rest of the code
Now, no matter which directory you move to, if you move to an extranet server, the code will run correctly without change.
two。 Do not use require, include, include_once, required_once directly
You can introduce multiple files in the script header, such as class libraries, tool files, and helper functions, such as:
Require_once ('lib/Database.php'); require_once (' lib/Mail.php'); require_once ('helpers/utitlity_functions.php')
This usage is rather primitive. It should be more flexible. A helper function should be written to include the file. For example:
Function load_class ($class_name) {/ / path to the class file $path = ROOT. '/ lib/'. $class_name. '.php'); require_once ($path);} load_class ('Database'); load_class (' Mail')
What's the difference? The code is more readable. You can extend the function as needed, such as:
Function load_class ($class_name) {/ / path to the class file $path = ROOT. '/ lib/'. $class_name. '.php'); if (file_exists ($path)) {require_once ($path);}
You can do more: find multiple directories for the same file. It is easy to change the directory where the class files are placed, without having to modify them all over the code. You can use similar functions to load files, such as html contents.
3. Retain debug code for the application
In the development environment, we print database queries and dump problematic variable values, and once the problem is solved, we annotate or delete them. However, it is better to keep the debug code. In a development environment, you can:
Define ('ENVIRONMENT',' development'); if (! $db- > query ($query) {if (ENVIRONMENT = = 'development') {echo "$query failed";} else {echo "Database error. Please contact administrator";}}
In the server, you can:
Define ('ENVIRONMENT',' production'); if (! $db- > query ($query) {if (ENVIRONMENT = = 'development') {echo "$query failed";} else {echo "Database error. Please contact administrator";}}
4. Use cross-platform functions to execute commands
System, exec, passthru and shell_exec functions can be used to execute system commands. Each has a slight difference in behavior. The problem is that when on a shared host, some functions may be selectively disabled. Most novices tend to check which function is available first each time, and then use it. A better solution is to seal a function as a cross-platform function.
/ * * Method to execute a command in the terminal Uses: 1. System 2. Passthru 3. Exec 4. Shell_exec * / function terminal ($command) {/ / system if (function_exists ('system')) {ob_start (); system ($command, $return_var); $output = ob_get_contents (); ob_end_clean ();} / / passthru else if (function_exists (' passthru')) {ob_start (); passthru ($command, $return_var); $output = ob_get_contents () Ob_end_clean ();} / exec else if (function_exists ('exec')) {exec ($command, $output, $return_var); $output = implode ("\ n", $output);} / / shell_exec else if (function_exists (' shell_exec')) {$output = shell_exec ($command);} else {$output = 'Command execution not possible on this system'; $return_var = 1;} return array (' output' = > $output, 'status' = > $return_var) } terminal ('ls')
The above function will run the shell command, as long as a system function is available, which keeps the code consistent.
5. Write functions flexibly
Function add_to_cart ($item_id, $qty) {$_ SESSION ['cart'] [' item_id'] = $qty;} add_to_cart ('IPHONE3', 2)
Use the above function to add a single project. When you add an item list, do you want to create another function? No, as long as a little attention to different types of parameters, it will be more flexible. Such as:
Function add_to_cart ($item_id, $qty) {if (! is_array ($item_id)) {$_ SESSION ['cart'] [' item_id'] = $qty;} else {foreach ($item_id as $i_id = > $qty) {$_ SESSION ['cart'] [' iImid'] = $qty;} add_to_cart ('IPHONE3', 2); add_to_cart (array (' IPHONE3' = > 2, 'IPAD' = > 5))
Now, the same function can handle different types of input parameters. You can refer to the above example to ReFactor many of your code to make it smarter.
6. Intentionally ignore the php close tag
I wonder why so many blog posts about php suggestions don't mention this.
/ / super extra character after the closing tag
Index.php
Require_once ('super_class.php'); / / echo an image or pdf, or set the cookies or session data
In this way, you will get a Headers already send error. Why? Because "super extra character" has been output. Now you have to start debugging. This will take a lot of time to find the location of super extra. Therefore, get into the habit of omitting the closing character:
'; $xml = "0"; / / Send xml data echo $xml
You did a good job. But some improvements are needed.
$xml =''; $xml = "0"; / / Send xml data header ("content-type: text/xml"); echo $xml
Note the header line. The line tells the browser that it is sending content of type xml. So the browser can handle it correctly. Many javascript libraries also rely on header information.
Similar to javascript, css, jpg image, png image:
JavaScriptheader ("content-type: application/x-javascript"); echo "var a = 10"; CSSheader ("content-type: text/css"); echo "# div id {background:#000;}"
9. Set the correct character encoding for mysql connections
I have encountered that the unicode/utf-8 code is set in the mysql table, and the phpadmin will display correctly, but when you get the content and output it on the page, there will be garbled. The problem here lies in the character encoding of mysql connections.
/ / Attempt to connect to database $c = mysqli_connect ($this- > host, $this- > username, $this- > password); / / Check connection validity if (! $c) {die ("Could not connect to the database host:". Mysqli_connect_error ();} / / Set the character set of the connectionif (! mysqli_set_charset ($c, 'UTF8')) {die (' mysqli_set_charset () failed');}
Once you connect to the database, it is best to set the connection characterset. This is necessary if your application is to support multiple languages.
10. Use htmlentities to set the correct encoding options
Before php5.4, the default encoding of characters is ISO-8859-1, which cannot be output directly, such as diamond â, etc.
$value = htmlentities ($this- > value, ENT_QUOTES, CHARSET)
After php5.4, the default encoding is UTF-8, which will solve a lot of problems. But if your application is multilingual, you should still pay attention to the coding problem.
11. Don't use gzip to compress the output in your application, let apache handle it
Have you ever considered using ob_gzhandler? Don't do that. meaningless。 Php is only used to write applications. You should not worry about optimizing data transmission between servers and browsers.
Use apache's mod_gzip/mod_deflate module to compress content.
twelve。 Use json_encode to output dynamic javascript content
Php is often used to output dynamic javascript content:
$images = array ('myself.png',' friends.png', 'colleagues.png'); $js_code =''; foreach ($images as $image) {$js_code. = "$image',";} $js_code = 'var images = ['. $js_code. '];'; echo $js_code;//Output is var images = ['myself.png',' friends.png', 'colleagues.png',]; to be smarter, use json_encode: $images = array (' myself.png', 'friends.png',' colleagues.png'); $js_code = 'var images ='. Json_encode ($images); echo $js_code;//Output is: var images = ["myself.png", "friends.png", "colleagues.png"]
Elegant?
13. Check directory write permissions before writing a file
Make sure the directory is writable before writing or saving the file, and if it is not writable, output error messages. This will save you a lot of debugging time. In linux system, it is necessary to deal with permissions, improper directory permissions will lead to many problems, files may not be able to read and so on.
Make sure your application is smart enough to output some important information.
$contents = "All the content"; $file_path = "/ var/www/project/content.txt"; file_put_contents ($file_path, $contents)
This is generally correct. But there are some indirect problems. File_put_contents may fail for several reasons:
> > parent directory does not exist
> > the directory exists but is not writable
> > is the file locked by writing?
Therefore, it is better to have a clear check before writing the document.
$contents = "All the content"; $dir ='/ var/www/project'; $file_path = $dir. "/ content.txt"; if (is_writable ($dir)) {file_put_contents ($file_path, $contents);} else {die ("Directory $dir is not writable, or does not exist. Please check");}
After doing so, you will get a clear message of where the file is written and why it failed.
14. Change the file permissions created by the application
In a linux environment, permission issues can waste a lot of your time. From now on, whenever you create some files, make sure you use chmod to set the correct permissions. Otherwise, the file may first be created by the "php" user, but if you log in to work with other users, the system will refuse to access or open the file, and you will have to strive to obtain root permissions, change file permissions, and so on.
/ / Read and write for owner, read for everybody else chmod ("/ somedir/somefile", 0644); / / Everything for owner, read and execute for others chmod ("/ somedir/somefile", 0755)
15. Do not rely on submit button values to check form submission behavior
If ($_ POST ['submit'] = =' Save') {/ / Save the things}
Most of the above are true, except that the application is multilingual. 'Save' may mean something else. How do you tell them apart? Therefore, do not rely on the value of the submit button.
If ($_ SERVER ['REQUEST_METHOD'] = =' POST' and isset ($_ POST ['submit'])) {/ / Save the things}
Now you are free from the submit button value.
16. Define a static variable for a variable that always has the same value in a function
/ / Delay for some time function delay () {$sync_delay = get_option ('sync_delay'); echo "Delaying for $sync_delay seconds..."; sleep ($sync_delay); echo "Done";}
Replace with static variables:
/ / Delay for some time function delay () {static $sync_delay = null; if ($sync_delay = = null) {$sync_delay = get_option ('sync_delay');} echo "Delaying for $sync_delay seconds..."; sleep ($sync_delay); echo "Done";}
17. Do not use the $_ SESSION variable directly
Some simple examples:
$_ SESSION ['username'] = $username; $username = $_ SESSION [' username']
This can lead to some problems. If multiple applications are running in the same domain name, the session variable may conflict. Two different applications may use the same session key. For example, a front-end portal uses the same domain name as a background management system. From now on, use the application-related key and a wrapper function:
Define ('APP_ID',' abc_corp_ecommerce'); / / Function to get a session variable function session_get ($key) {$k = APP_ID. '.'. Key; if (isset ($_ SESSION [$k])) {return $_ SESSION [$k];} return false;} / / Function set the session variable function session_set ($key, $value) {$k = APP_ID. '.'. $key; $_ SESSION [$k] = $value; return true;}
18. Encapsulate tool functions into classes
Suppose you define a lot of tool functions in a file:
Function utility_a () {/ / This function does a utility thing like string processing} function utility_b () {/ / This function does nother utility thing like database processing} function utility_c () {/ / This function is...}
The use of these functions is scattered throughout the application. You might want to encapsulate them in a class:
Class Utility {public static function utility_a () {} public static function utility_b () {} public static function utility_c () {}} / / and call them as $a = Utility::utility_a (); $b = Utility::utility_b ()
The obvious benefit is that if a function with the same name is built into php, conflicts can be avoided.
Another view is that you can maintain multiple versions of the same class in the same application without causing conflicts. This is the basic benefit of encapsulation, without it.
19. Bunch of silly tips
Using echo instead of print
Use str_replace instead of preg_replace unless you absolutely need it
> > do not use short tag
Simple strings replace double quotation marks with single quotation marks
> > remember to use exit after head redirection
> > do not call functions in a loop
> > isset is faster than strlen
> > the formatting code in the beginning as one
> > do not delete parentheses for loops or if-else
Don't write code like this:
If ($a = = true) $axicountcounting +
This is definitely WASTE. Write as follows:
If ($a = = true) {$axed countdown;}
Don't try to shorten the code by omitting some syntax. It's about keeping your logic short.
Use a text editor with highlighted syntax. Highlighting grammar can help you reduce errors.
20. Using array_map to quickly process arrays
Let's say you want to trim all the elements in the array. Beginners may:
Foreach ($arr as $c = > $v) {$arr [$c] = trim ($v);}
But it is easier to use array_map:
$arr = array_map ('trim', $arr)
This will request a call to trim for each element of the $arr array. Another similar function is array_walk. Please refer to the documentation to learn more skills.
21. Validate data using php filter
You must have used regular expressions to validate email, ip addresses, etc. Yes, everyone uses it that way. Now, we want to try something different, called filter.
Php's filter extension provides an easy way to validate and check input.
twenty-two。 Mandatory type checking
$amount = intval ($_ GET ['amount']); $rate = (int) $_ GET [' rate']
This is a good habit.
23. If necessary, use profiler such as xdebug
If you use php to develop large applications, php takes on a lot of computation, speed will be a very important indicator. Use profile to help optimize the code. You can use xdebug and webgrid.
24. Handle large arrays carefully
Large arrays and strings must be handled with care. A common error is that the array copy causes memory overflow and throws Fatal Error of Memory size information:
$db_records_in_array_format; / / This is a big array holding 1000 rows from a table each having 20 columns, every row is atleast 100 bytes, so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; / / 2MB moresome_function ($cc); / / Another 2MB?
This is often done when importing or exporting csv files. Don't assume that the above code will often cause scripts to crash due to memory limitations. It's fine for small variables, but it must be avoided when dealing with large arrays.
Be sure to pass it by reference or store it in a class variable:
A = get_large_array (); pass_to_function (& $a)
After doing so, pass the variable reference to the function (instead of copying the array). View the document.
Class A {function first () {$this- > a = get_large_array (); $this- > pass_to_function ();} function pass_to_function () {/ / process $this- > a}}
Unset them as soon as possible, so that memory can be released, reducing the burden of scripts.
25. Use a single database connection from beginning to end
Make sure your script uses a single database connection from beginning to end. Open the connection correctly at the beginning, use it until the end, and finally close it. Do not open a connection in a function like this:
Function add_to_cart () {$db = new Database (); $db- > query ("INSERT INTO cart.");} function empty_cart () {$db = new Database (); $db- > query ("DELETE FROM cart.");}
Using multiple connections is a bad thing, they slow down the application because it takes time and memory to create a connection. Use singleton mode for specific cases, such as database connections.
At this point, the study of "what high-quality PHP code is available" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.