php学习指南
http://www.binarytides.com/category/php-2/tutorial/
in this series we are going to look into some useful tips and techniques that can be used to improve and optimise your php code. note that these php tips are meant for beginners and not those who are already using mvc frameworks etc.
the techniques 1. do not use relative paths , instead define a root path its quite common to see such lines :
require_once('http://www.cnblogs.com/lib/some_class.php');
this approach has many drawbacks :
it first searches for directories specified in the include paths of php , then looks from the current directory.
so many directories are checked.
when a script is included by another script in a different directory , its base directory changes to that of the including script.
another issue , is that when a script is being run from cron , it may not have its parent directory as the working directory.
so its a good idea to have absolute paths :
define('root' , '/var/www/project/');require_once(root . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code
now this is an absolute path and will always stay constant. but we can improve this further. the directory /var/www/project can change , so do we change it everytime ? no instead we make it portable using magic constants like __file__ . take a closer look :
//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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code
so now even if you shift your project to a different directory , like moving it to an online server , the same code will run without any changes.
2. dont use require , include , require_once or include_once your script could be including various files on top , like class libraries , files for utility and helper functions etc like this :
require_once('lib/database.php');require_once('lib/mail.php');require_once('helpers/utitlity_functions.php');
this is rather primitive. the code needs to be more flexible. write up helper functions to include things more easily. lets take an 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');
see any difference ? you must. it does not need any more explanation.
you can improve this further if you wish to like this :
function load_class($class_name){ //path to the class file $path = root . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }}
there are a lot of things that can be done with this :
search multiple directories for the same class file.
change the directory containing class files easily , without breaking the code anywhere.
use similar functions for loading files that contain helper functions , html content etc.
3. maintain debugging environment in your application during development we echo database queries , dump variables which are creating problems , and then once the problem is solved , we comment them or erase them. but its a good idea to let everything stay and help in the long run
on your development machine you can do this :
define('environment' , 'development');if(! $db->query( $query ){ if(environment == 'development') { echo $query failed; } else { echo database error. please contact administrator; } }
and on the server you can do this :
define('environment' , 'production');if(! $db->query( $query ){ if(environment == 'development') { echo $query failed; } else { echo database error. please contact administrator; } }
4. propagate status messages via session status messages are those messages that are generated after doing a task.
...
code like that is common. using variables to show status messages has limitations. they cannot be send via redirects (unless you propagate them as get variables to the next script , which is very silly). in large scripts there might be multiple messages etc.
best way is to use session to propagate them (even if on same page). for this there has to be a session_start on every page.
function set_flash($msg){ $_session['message'] = $msg;}function get_flash(){ $msg = $_session['message']; unset($_session['message']); return $msg;}
and in your script :
status is : ...
5. make your functions flexible function add_to_cart($item_id , $qty){ $_session['cart'][$item_id] = $qty;}add_to_cart( 'iphone3' , 2 );
when adding a single item you use the above function. when adding multiple items , will you create another function ? no. just make the function flexible enough to take different kinds of parameters. have a closer look :
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'][$i_id] = $qty; } }}add_to_cart( 'iphone3' , 2 );add_to_cart( array('iphone3' => 2 , 'ipad' => 5) );
so now the same function can accept different kinds of output. the above can be applied in lots of places to make your code more agile.
6. omit the closing php tag if it is the last thing in a script i wonder why this tip is omitted from so many blog posts on php tips.
this will save you lots of problem. lets take an example :
a class file super_class.php
//super extra character after the closing tag
now index.php
require_once('super_class.php');//echo an image or pdf , or set the cookies or session data
and you will get headers already send error. why ? because the super extra character has been echoed , and all headers went along with that. now you start debugging. you may have to waste many hours to find the super extra space.
hence make it a habit to omit the closing tag :
thats better.
7. collect all output at one place , and output at one shot to the browser this is called output buffering. lets say you have been echoing content from different functions like this :
function print_header(){ echo site log and login links
;}function print_footer(){ echo site was made by me
;}print_header();for($i = 0 ; $i $v){ $arr[$c] = trim($v);}
but it can more cleaner with array_map :
$arr = array_map('trim' , $arr);
this will apply trim on all elements of the array $arr. another similar function is array_walk. check out the
documentation on these to know more.
21. validate data with php filters have you been using to regex to validate values like email , ip address etc. yes everybody had been doing that. now lets
try something different, called filters.
the php filter extension provides simple way to validate or check values as being a valid 'something'.
22. force type checking $amount = intval( $_get['amount'] );$rate = (int) $_get['rate'];
its a good habit.
23. write php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. a good idea would be write some important errors in a file for logging purpose
24. handle large arrays carefully large arrays or strings , if a variable is holding something very large in size then handle with care. common mistake is to create a copy and then run out of memory and get a fatal error of memory size exceeded :
$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 ?
the above thing is common when importing a csv file or exporting table to a csv file
doing things like above can crashs scripts quite often due to memory limits. for small sized variables its not a problem , but must be avoided when handling large arrays.
consider passing them by reference , or storing them in a class variable :
$a = get_large_array();pass_to_function(&$a);
by doing this the same variable (and not its copy) will be available to the function. check documentation
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 is freed and rest of the script can relax.
here is a simple demonstration of how assign by reference can save memory in some cases
query(delete from cart .....);}
having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory.
use the singleton pattern for special cases like database connection.
26. avoid direct sql query , abstract it $query = insert into users(name , email , address , phone) values('$name' , '$email' , '$address' , '$phone');$db->query($query); //call to mysqli_query()
the above is the simplest way way of writing sql queries and interacting with databases for operations like insert, update, delete etc. but it has few drawbacks like:
all values have to be escaped everytime manually manually verify the sql syntax everytime. wrong queries may go undetected for a long time (unless if else checking done everytime) difficult to maintain large queries like that solution: activerecord
it involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries.
a very simple example of an activerecord insert function can be like this :
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 to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the insert queryinsert_record('users' , $data);
the above example shows how to insert data in a database, without actually having to write insert statements. the function insert_record takes care of escaping data as well. a big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse).
this function can be part of a database class, and callable like this $db->insert_record(). similar functions can be written for update, select, delete as well. should be a good practise.
27. cache database generated content to static files pages that are generated by fetching content from the database like cms etc, can be cached. it means that once generated, a copy of it can be writted to file. next time the same page is requested, then fetch it from the cache directory, dont query the database again.
benefits :
save php processing to generate the page , hence faster execution lesser database queries means lesser load on mysql database 28. store sessions in database file based sessions have many limitation. applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. but database can be access from multiple servers hence the the problem is solved there. also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. this can be a security issue.
storing session in database makes many other things easier like:
restrict concurrent logins from same username. same username cannot log in from 2 different places at same time check online status of users more accurately 29. avoid using globals use defines/constants get value using a function use class and access via $this 30. use base url in head tag quick example :
the base tag is like a 'root' url for all relative urls in the html body. its useful when static content files are organised into directories and subdirectories.
lets take an example
www.domain.com/store/home.php
www.domain.com/store/products/ipad.php
in home.php the following can be written :
homeipad
but in ipad.php the links have to be like this :
homeipad
this is because of different directories. for this multiple versions of the navigation html code has to be maintained. so the quick solution is base tag.
homeipad
now this particular code will work the same way in the home directory as well as the product directory. the base href value is used to form the full url for home.php and products/ipad.php
31. manage error reporting error_reporting is the function to use to set the necessary level of error reporting required.
on a development machine notices and strict messages may be disabled by doing.
ini_set('display_errors', 1);error_reporting(~e_notice & ~e_strict);
on production , the display should be disabled.
ini_set('display_errors', 0);error_reporting(~e_warning & ~e_notice & ~e_strict);
it is important to note that error_reporting should never be set to 0 on production machines. atleast e_fatals have to be known. just switch off the display using the display_errors directive. if error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.
after the display is switched off, the errors should be logged to a file for later analysis. this can be done inside the script using init_set.
ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~e_warning & ~e_notice & ~e_strict);
note :
1. the path '/path/to/errors.txt' should be writable by the web server for errors to be logged there.
2. a separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors.
3. also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).
4. the path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched.
5. dont set error_reporting to 0. it will not log anything then.
alternatively set_error_handler should be used to set a custom user written function as the error handler. that particular function, for example can log all errors to a file.
set 'display_errors=on' in php.ini on development machine
on development machine its important to enable display_errors right in the php.ini (and not rely on ini_set)
this is because any compile time fatal errors will now allow ini_set to execute , hence no error display
and a blank white page.
similarly when they are on in php.ini , switching it off in a script that has fatal errors will not work.
set 'display_errors=off' in php.ini on production machine
do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.
32. be aware of platform architecture the length of integers is different on 32 and 64 bit architectures. so functions like strtotime give different results.
on a 64 bit machine you can see such output.
$ php -ainteractive shellphp > echo strtotime(0000-00-00 00:00:00);-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600
but on a 32 bit machine all of them would give bool(false). check here for more.
what would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.
33. dont rely on set_time_limit too much if you are limiting the maximum run-time of a script , by doing this :
set_time_limit(30);//rest of the code
it may not always work. any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit.
so if a database operation takes lot of time or hangs then the script will not stop. dont be surprised then. make better strategies to handle the run-time.
34. make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. each has a slightly different behaviour. but the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. most newbie programmers tend to first find out which function is enabled and then use it.
a better solution :
/** 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 execute the shell command using whichever function is available , keeping your code consistent.
35. localize your application localise your php application. format dates and numbers with commas and decimals. show the time according to timezone of the user.
36. use a profiler like xdebug if you need to profilers are used to generate reports that show the time is taken by different parts of the code to execute. when writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.
use profilers to check how your code is performing in terms of speed. check out xdebug and webgrind.
37. use plenty of external libraries an application often needs more than what can be coded with basic php. like generating pdf files, processing images, sending emails, generating graphs and documents etc. and there are lots of libraries out there for doing these things quickly and easily.
few popular libraries are :
mpdf - generate pdf documents, by converting html to pdf beautifully. phpexcel - read and write excel files phpmailer - send html emails with attachments easily pchart - generate graphs in php 38. have a look at phpbench for some micro-optimisation stats if you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.
39. use an mvc framework its time to start using an mvc (model view controller) framework like codeigniter. mvc does not make your code object oriented rightaway. the first thing they do is separate the php code from html code.
clean separation of php and html code. good for team work, when designers and coders are working together. functions and functionalities are organised in classes making maintenance easy. inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. is a must when writing big applications lots of tips, techniques, hacks are already implemented in the framework 40. read the comments on the php documentation website the php documentation website has entries for each function, class and their methods. all those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.
they contain user feedback, expert advice and useful code snippets. so check them out.
41. go to the irc channel to ask the irc channel #php is the best place online to ask about php related things. although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. then irc is the place to ask. and its totally free!!
42. read open source code reading other open source applications is always a good idea to improve own skills if you have not already. things to learn are techniques, coding style, comment style, organisation and naming of files etc.
the first open source thing that i read was the codeigniter framework. its easy to developers to use, as well as easy to look inside. here are a few more
1. codeigniter
2. wordpress
3. joomla cms
43. develop on linux if you are already developing on windows, then you might give linux a try. my favorite is ubuntu. although this is just an opinion but still i strongly feel that for development linux is a much better environment.
php applications are mostly deployed on linux (lamp) environments. therefore, developing in a similar environment helps to produce a robust application faster.
most of the development tools can be very easily installed from synaptic package manager in ubuntu. plus they need very little configuration to setup and run. and the best thing is, that they all are free.