Improve code quality Techniques

Source: Internet
Author: User

1. do not use relative paths

Often you will see:

Require_once ('.. /.. /lib/some_class.php ');

The method has many drawbacks: it first looks for the specified PHP include path , and then finds the current directory . therefore, too many paths are checked . If the script is included in a script from another directory, its base directory becomes the directory where the other script resides. Another problem: When a timed task runs the script, its parent directory may not be the working directory.
So the best option is to use absolute paths:

Define (' root ', '/var/www/project/'); require_once (Root. ‘.. /.. /lib/some_class.php ');

We have defined an absolute path, The value was written dead.. we can also improve it. Path/var/www/projectit could change ., so we're going to change it every time?? no, No., we can use__file__Constants, as:

Define (' Root ', PathInfo (__file__, Pathinfo_dirname)); require_once (Root. ‘.. /.. /lib/some_class.php ');

Now , no matter which directory you move to , such as a server that is moved to an extranet , the code will run correctly without changes .

2. Do not use require, include, include_once, Required_once directly in the program

such as: require_once (' lib/database.php ');

This is a very confusing notation. should be more flexible. .  You should write a class file . For example :

Class Loader {/** * load module, class name must be the same as defined in the file, without class, but the actual file name of the class is all lowercase * such as: * Loader::importapplib (' mall ', ' C     MS ');     */root_path/mall/framework/libraries/cms.class.php * * @param string $module * @param string $classname * @param string $ext * @return Boolean if the class does not exist after import, it will also return false */public static function Importapplib ($module, $CLA                Ssname, $ext = '. class.php ') {$result = Self::importbyapp ($module, "libraries.". Strtolower ($classname), $ext);        if (! $result) {return FALSE; } return Class_exists ($classname.    ' Class ', FALSE);     }/** * The function library file under load module * such as: * LOADER::IMPORTAPPFUNC (' mall ', ' search '); */root_path/mall/framework/function/search.php * @param string $module * @param string $file * @param string $ext * @return Boolean */public static function Importappfunc ($module, $file, $ext = '. php ') {return s Elf::importbyapp ($module, "function.    {$file} ", $ext);     }/** * by module, load class library files * such as: * Loader::importbyapp (' mall ', ' Framework.libraries.CMS ', '. class.php '); */root_path/mall/framework/libraries/cms.class.php * * LOADER::IMPORTBYAPP (' mall ', ' model.     User '); */root_path/mall/model/user.php * @param string $module * @param string $file * @param string $ext * @ret Urn Boolean */public static function Importbyapp ($module, $file, $ext = '. php ') {return Self::import ("{$mo Dule}.framework.    {$file} ", $ext); /** * Universal file load, system-wide, load class, library file * @param string $file class library file * requires a path relative to the system root directory, separated by. Delimited, such as mall.framework. FUNCTION.XXX Case Sensitive * @param string $ext file suffix names such as. Inc,. class.php,. PHP, etc., default to. php * @return Boolean */Public STA Tic function Import ($file, $ext = '. php ') {if (Strstr ($file, '. '))        {$file = Str_replace ('. ', Directory_separator, $file); } $_file = Realpath (Base_core_path. ‘/.. /‘ . $file. $eXT);        if (!file_exists ($_file)) {return false;                } require_once $_file;    return true; }}

3. Handle large arrays with care

For large arrays and strings , You must handle them with care . A common error occurs when an array copy causes a memory overflow , thrown Fatal Error of Memory size Information :

$db _records_in_array_format; This is a large array that holds 1000 rows and 20 columns from the table, each row is at least 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 a csv file .

Do not assume that the above code does not often cause the script to crash due to memory limitations . There's no problem with small variables . ,  but it's unavoidable when dealing with large arrays .

(1). Passing by reference ,

$a = Get_large_array ();p ass_to_function (& $a);

(2). or stored in a class variable :

Class A {    function First () {$this->a = Get_large_array (); $this->pass_to_function ();    }    function Pass_to_function () {//process $this->a    }}

In short, to unset them as soon as possible, let the memory release, reduce the burden of the script.

4. Error log

function Insert_member () {    if (! $model->insert ($data)) {Log::record ($model->geterror, Log::sql, ' Insert_ Member '); return false;    }}

Above is an Insert member information method, when inserting data failure, will record the reason of failure, facilitate quickly find the cause of failure

5. validating data
You must have used regular expression validation  email , ip address, etc. .  Yes everyone uses . .  now ,  We want to make a different attempt ,  filter.

the filter Extension of PHP provides a simple way to validate and check input .

  

Improve code quality Techniques

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.