36 Counts of improving PHP code quality (next)

Source: Internet
Author: User
18. Encapsulating tool functions in a class


If you define a number 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 dispersed 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 PHP has a function with the same name, you can avoid collisions.


Another view is that you can maintain multiple versions of the same class in the same application without causing a conflict. This is the basic benefit of encapsulation, without it.


Bunch of Silly tips


>> use echo instead of print


>> use Str_replace instead of preg_replace, unless you absolutely need


>> do not use the short tag


>> simple string with single quotation mark instead of double quotation mark


Remember to use exit after >>head redirect


>> do not call functions in loops


>>isset is faster than strlen.


Formatted code as in >>


>> do not delete loops or if-else parentheses


Don't write code like this:


if ($a = = true) $a _count++;


This is absolutely waste.


Written:


if ($a = = true)

{

$a _count++;

}


Do not attempt to omit some syntax to shorten the code. But to make your logic brief.


>> use a text editor that has a highlighted syntax display. Highlighting syntax can help you reduce errors.


20. Using Array_map to quickly process arrays


For example, you want to trim all the elements in the array. Novice May:


foreach ($arr as $c = $v)

{

$arr [$c] = Trim ($v);

}


But using Array_map is easier:


$arr = Array_map (' Trim ', $arr);


This applies the call trim for each element of the $arr array. Another similar function is Array_walk. Check out the documentation to learn more tips.


21. Validating Data Using PHP filter


You must have used regular expressions to verify email, IP address, and so on. Yes, everyone uses it that way. Now, we want to make a different attempt, called filter.


The filter extension of PHP provides a simple way to validate and check input.


22. Mandatory type checking


$amount = intval ($_get[' amount ');

$rate = (int) $_get[' rate '];


It's a good habit.


23. If required, use profiler such as Xdebug


If you use PHP to develop large-scale applications, PHP takes a lot of computation, and speed is a very important indicator. Use profile to help optimize your code. can be used


Xdebug and WebGrid.


24. Handle large arrays with care


For large arrays and strings, you must handle them with care. A common mistake is the occurrence of an array copy causing memory overflow, throwing fatal error of the Memories size information:


$db _records_in_array_format; This is a big array holding $ rows from a table each have a columns, every row is atleast 10 bytes XX * = 2MB

$CC = $db _records_in_array_format; 2MB more

Some_function ($CC); Another 2MB?


This is often done when importing or exporting a CSV file.


Do not assume that the above code will often cause the script to crash due to memory limitations. There is no problem with small variables, but it must be avoided when dealing with large arrays.


Ensure that it is passed by reference or stored in a class variable:


$a = Get_large_array ();

Pass_to_function (& $a);


When you do this, 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 quickly as possible, freeing up memory to relieve the burden of scripting.


25. Use a single database connection from start to finish


Make sure that your scripts use a single database connection from start to finish. Open the connection correctly at the beginning, use it until the end, and then close it. Do not open the connection in the function as follows:


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, and they slow down the app because creating a connection takes time and memory.


A singleton pattern, such as a database connection, is used for specific situations.


26. Avoid writing SQL directly, abstract


Too much to write too many of the following statements:


$query = "INSERT into users (name, email, address, phone) VALUES (' $name ', ' $email ', ' $address ', ' $phone ')";

$db->query ($query); Call to Mysqli_query ()


This is not a plan to build strong. It has some drawbacks:


>> manually escape values each time


>> Verify that the query is correct


>> query errors can take a long time to identify (unless checked with if-else each time)


>> difficult to maintain complex queries


So use the 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 it? This makes it easier to read and expand. The Record_data function is handled with care for escaping.


The biggest advantage is that the data is preprocessed into an array, and any syntax errors are captured.


The function should be defined in a database class, and you can call it like $db->insert_record.


Check out this article to see how you can make it easier to work with databases.


Similarly, you can also write Update,select,delete methods. Give it a try.


27. Cache the database-generated content in a static file


If all the content is obtained from the database, they should be cached. Once generated, they are saved in a temporary file. The next time the page is requested, it can be taken directly from the cache without having to look up the database.


Benefits:


>> save time on PHP processing pages, execute faster


>> fewer database queries means less MySQL connection overhead


28. Save the session in the database


There are many limitations to the file-based session strategy. Using a file-based session cannot be extended to the cluster because the session is saved in a single server. But the database can be accessed by multiple servers, which solves the problem.


There are many more benefits of saving session data in a database:


>> handles username recurring login issues. The same username cannot be logged in two locations at the same time.


>> can be more prepared to query online user status.


29. Avoid using global variables


>> using Defines/constants


>> using functions to get values


>> using classes and accessing through $this


30. Using the base tag in the head


Never heard of him? Please see below:



The base tag is very useful. Suppose your app is divided into subdirectories, all of which include the same navigation menu.


www.domain.com/store/home.php


www.domain.com/store/products/ipad.php


In the home page, you can write:


Home

Ipad


But in your ipad.php you have to write:


Home

Ipad


Because the directory is different. There are so many different versions of the navigation menu to maintain, very bad AH.


Therefore, use the base tag.


Home

Ipad


Now, this code is consistent across the app's catalog files.


31. Never set the error_reporting to 0


Close the non-phase error report. It is important to e_fatal errors.


Ini_set (' display_errors ', 1);

Error_reporting (~e_warning & ~e_notice & ~e_strict);


32. Pay attention to the platform architecture


Integers are different in length in 32-bit and 64-bit architectures. Therefore, some functions, such as strtotime, behave differently.


In a 64-bit machine, you will see the following output.


$ php-a

Interactive Shell

php > Echo strtotime ("0000-00-00 00: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). See here for more information.


33. Do not 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


Do you have peace of mind? Note that any external execution, such as system calls, socket operations, database operations, etc., is not under set_time_limits control.


Therefore, even if the database spends a lot of time querying, the script will not stop executing. Subject to availability.


34. Using the extension library


Some examples:


>>mpdf--can generate PDF documents from HTML


>>phpexcel--Read and write Excel


>>phpmailer-Easily handle sending messages that contain nearby


>>pchart--Generate reports using PHP


Use the open Source library for complex tasks such as generating PDFs, ms-excel files, reports, and more.


35. Using the MVC framework


It's time to use an MVC framework like CodeIgniter. The MVC framework does not force you to write object-oriented code. They only separate PHP code from HTML.


>> clearly distinguishes between PHP and HTML code. There are benefits in team collaboration, and designers and programmers can work at the same time.


>> Object-oriented design functions that make it easier for you to maintain


>> built-in functions do a lot of work and you don't need to write them repeatedly


>> development of large applications is a must


>> Many suggestions, tips and hack have been implemented by the framework


36. Always Look at Phpbench


Phpbench provides some benchmark results for basic PHP operations, and it shows how the minor grammatical changes in some badges lead to huge differences.


Review the comments on the PHP site, ask questions to IRC, read open source code, and use Linux development.

  • 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.