In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "what are the ways to improve the quality of PHP code". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what are the ways to improve the quality of PHP code?"
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 containing path, and then looks for the current directory.
Therefore, too many paths will be 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:
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);}
More can be done:
Find multiple directories for the same file
The directory where the class files are placed can be easily changed 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 (' 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:
JavaScript
Header ("content-type: application/x-javascript"); echo "var a = 10"
CSS
Header ("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 connection if (! 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',]
A smarter approach is to 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
$_ 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 absolutely 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. Can be used
Xdebug and webgrid.
24. Handle large arrays carefully
Large arrays and strings must be handled with care. The common error is that the array copy causes memory overflow and throws Fat.
$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 more some_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 bad, they slow down the application because it takes time and memory to create a connection.
Singleton mode is used for specific cases, such as database connections.
twenty-six。 Avoid writing SQL directly and abstract it.
I took the trouble to write too many of the following sentences:
$query = "INSERT INTO users (name, email, address, phone) VALUES ('$name','$email','$address','$phone')"; $db- > query ($query); / / call to mysqli_query ()
This is not a strong plan. It has some disadvantages:
> > manually escape the value every time
> > verify that the query is correct
> > query errors take a long time to identify (unless checked with if-else every time)
> > it is difficult to maintain complex queries
So use function encapsulation:
Function insert_record ($table_name, $data) {foreach ($data as $key = > $value) {/ / mysqli_real_escape_string $data [$key] = $db- > mres ($value);} $fields = implode (',', array_keys ($data)); $values = "'". Implode ("','", array_values ($data)). "'"; / / Final query $query = "INSERT INTO {$table} ($fields) VALUES ($values)"; return $db- > query ($query);} $data = array ('name' = > $name,' email' = > $email, 'address' = > $address,' phone' = > $phone); insert_record ('users', $data)
Did you see that? This makes it easier to read and expand. The record_data function handles escaping carefully.
The biggest advantage is that the data is preprocessed into an array and any syntax errors will be caught.
The function should be defined in a database class, which you can call like $db- > insert_record.
Check out this article to see how to make it easier for you to deal with the database.
Similarly, you can write update,select,delete methods. Try it。
twenty-seven。 Cache the content generated by the database to a static file
If all content is fetched from the database, it should be cached. Once generated, save them in a temporary file. The next time the page is requested, it can be taken directly from the cache without having to check the database.
Benefits:
> > saves php time to process pages and executes faster
Fewer database queries means less mysql connection overhead
twenty-eight。 Save sessio- in the database
The base tag is very useful. Suppose your application is divided into several subdirectories, all of which include the same navigation menu.
Www.domain.com/store/home.php
Www.domain.com/store/products/ipad.php
On the home page, you can write:
Home Ipad
But in your ipad.php, you have to write:
Home Ipad
Because the catalogue is different. It's too bad that there are so many different versions of navigation menus to maintain.
Therefore, please use the base tag.
Home Ipad
Now, this code behaves the same in all directory files of the application.
thirty-one。 Never set error_reporting to 0
Turn off non-identical error reporting. E_FATAL errors are very important.
Ini_set ('display_errors', 1); error_reporting (~ E_WARNING & ~ E_NOTICE & ~ E_STRICT)
thirty-two。 Pay attention to the platform architecture
The length of integer is different in 32-bit and 64-bit architectures. So some functions, such as strtotime, behave differently.
On a 64-bit machine, you will see the following output.
$php-an Interactive shell php > echo strtotime ("0000-00-0000: 00:00");-62170005200 php > echo strtotime ('1000-01-30');-30607739600 php > echo strtotime (' 2100-01-30'); 4104930600
But in 32-bit machines, they will be bool (false). Check here to learn more.
thirty-three。 Don't rely too much on set_time_limit
If you want to limit the minimum time, you can use the following script:
Set_time_limit (30); / / Rest of the code
Rest easy? Note that any external execution, such as system calls, socket operations, database operations, etc., is not under the control of set_time_limits.
Therefore, even if the database takes a lot of time to query, the script will not stop execution. It depends on the situation.
thirty-four。 Use extended libraries
Some examples:
> > mPDF-- pdf documents can be generated through html
> > PHPExcel-- read and write excel
> > PhpMailer-- easily handle sending messages containing nearby messages
> > pChart-- generate reports using php
Use open source library to complete complex tasks, such as generating pdf, ms-excel files, reports, etc.
thirty-five。 Use the MVC framework
It's time to use a MVC framework like codeigniter. The MVC framework does not force you to write object-oriented code. They only separate php code from html.
Make a clear distinction between php and html code. There are benefits in teamwork, designers and programmers can work at the same time.
Object-oriented functions can make it easier for you to maintain
The built-in function has done a lot of work, and you don't need to write it over and over again
It is necessary to develop large applications
> > many suggestions, techniques and hack have been implemented by the framework.
thirty-six。 Check phpbench frequently.
Phpbench provides some benchmark results for the basic operation of php, which shows how small syntax changes can make a big difference.
Check the comments on the php site, ask questions to IRC, often read the open source code, use Linux development.
Thank you for your reading, the above is "what are the ways to improve the quality of PHP code?" after the study of this article, I believe you have a deeper understanding of the methods to improve the quality of PHP code, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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.