Wednesday 27 June 2012

php code optimization tips

Wrap your string in single quotes (’) instead of double quotes (”) is faster because PHP searches for variables inside “…” and not in ‘…’, use this when you’re not using variables you need evaluating in your string.

If method is static, declare that method for once and reuse that method and achieve improvement in speed.


Echo is faster than print
echo and print are virtually (not technically) the same thing. The (pretty much only) difference between the two is that print will return the integer 1, whereas echo returns nothing. Keep in mind that neither is actually a function, but rather language constructs. echo allows you to pass multiple strings when using it as if it were a function (e.g., echo($var1, $var2, $var3)) 
echo can also be shorthanded by using the syntax <?= $var1; ?> (in place of <?php echo $var1; ?>).
Use loop limit calculation outside and same extra calculation
for($i=0; $i<$cnt*10; $++) replace with$count1 = $cnt*10;for($i=0; $i<$count1; $i++)
Unset the value of variable and get more freed space for faster performance
Use the unset($var); to unset the variable.
Avoid expensive require_once() and include_once() to for faster execution
_once() method do require to store log and has to check log every time for file requie/include.
Use fullpath because it takes less time in path resolving.

Possibly avoid regex by the use of strncasecmp, strpbrk or stripos.

str_replace is faster than preg_replace, but strtr is faster than str_replace by a factor of 4

If the function, such as string replacement function, accepts both arrays and single characters as arguments, and if your argument list is not too long, consider writing a few redundant replacement statements, passing one character at a time, instead of one line of code that accepts arrays as search and replace arguments.

It is better to use select statements than multi if, else if, statements.
if...else statement - use this statement if you want to execute a set of code when a condition is true and another if the condition is not true
elseif statement - is used with the if...else statement to execute a set of code if one of several condition are true
switch statement - is used if you want to select one of many blocks of code to be executed, use the Switch statement. The switch statement is used to avoid long blocks of if..elseif..else code.
Error suppression with @ is very slow.
@ is called error suppression symbol in php and used to tell php that it shouldn’t generate a warning (or a notice) as u know It’s perfectly correct to ignore that warning message. And overuse of that @ symbol can decrease your speed performance 

Turn on apache's mod_deflate
It is good to compress files on apache to reduce bandwidth usage and speed. This can be done by mod_deflate in apache 
In order to compress files using mod_deflate on Apache 2.x you first need to load the module, so you'll need to edit the Apache configuration. The exact location of the configuration file varies between each Linux/BSD distro, but it's often found at /etc/httpd/httpd.conf or /etc/apache2/httpd.conf, or /etc/httpd/conf/httpd.conf or /etc/apache2/conf/httpd.conf. If you are unsure of its location locate httpd.conf will usually send you in the right direction. 
So now that you've found the Apache config file, open it up in your favourite text editor as root or using sudo, and add this line: 
LoadModule deflate_module modules/mod_deflate.so this section:
<Location />          AddOutputFilterByType DEFLATE text/html text/plain text/xml text/x-js text/css</Location> 
Always remember to close database connection after the use of that connection

If you are using prepared statement then remember to close stmt objects, and in select statement when you 
use store_result use free_result to free the memory
Use $stmt->free_result(); and 
$stmt->close()
$row['id'] is 7 times faster than $row[id], because if you don’t supply quotes it has to guess which index you meant, assuming you didn’t mean a constant.

Error messages are expensive try to reduce error message and warning messages

Do not use functions inside of for loop, such as for ($x=0; $x < count($array); $x++) The count() function gets called each time.
$cnt = count($array);
For($x=0; $x < $cnt; $x++)
{
      ………..
}
Incrementing a local variable in a method is the fastest. Nearly the same as calling a local variable in function.

Incrementing a global variable is 2 times slow than a local var.

Try to exchange calculation with cheaper instruction. Ex. Replace multiplication by cheaper instruction addition.
$z = $x*2;
$z = $x+$x;
Incrementing an object property (eg. $this->prop++) is 3 times slower than a local variable

Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one.

Try to use local variable rather than global variable. 
Little time is waste behind checking the global variable
Surrounding your string by ' instead of “ will make things interpret a little faster since php looks for variables inside ”..." but not inside '...' . Of course you can only do this when you don't need to have variables in the string.

A PHP script will be served at least 2-10 times slower than a static HTML page by Apache. Try to use more static HTML pages and fewer scripts.
Means use html tags outside the php script code by breaking php scriptAvoid <?php echo “<br />” ?> and use simply <br />
Your PHP scripts are recompiled every time unless the scripts are cached. Install a PHP caching product to typically increase performance by 25-100% by removing compile times.

Cache as much as possible. Use memcached - memcached is a high-performance memory object caching system intended to speed up dynamic web applications by alleviating database load. OP code caches are useful so that your script does not have to be compiled on every request

When working with strings and you need to check that the string is either of a certain length you'd understandably would want to use the strlen() function. This function is pretty quick since it's operation does not perform any calculation but merely return the already known length of a string available in the zval structure (internal C struct used to store variables in PHP). However because strlen() is a function it is still somewhat slow because the function call requires several operations such as lowercase & hashtable lookup followed by the execution of said function. In some instance you can improve the speed of your code by using an isset() trick.
Example:
if (strlen($foo) < 5) { echo "Foo is too short";}
vs.
if (!isset($foo{5})) { echo "Foo is too short"; }
Calling isset() happens to be faster then strlen() because unlike strlen(), isset() is a language construct and not a function meaning that it's execution does not require function lookups and lowercase. This means you have virtually no overhead on top of the actual code that determines the string's length.

When incrementing or decrementing the value of the variable $i++ happens to be a tad slower then ++$i. This is something PHP specific and does not apply to other languages, so don't go modifying your C or Java code thinking it'll suddenly become faster, it won't. ++$i happens to be faster in PHP because instead of 4 opcodes used for $i++ you only need 3. Post incrementation actually causes in the creation of a temporary var that is then incremented. While pre-incrementation increases the original value directly. This is one of the optimization that opcode optimized like Zend's PHP optimizer. It is a still a good idea to keep in mind since not all opcode optimizers perform this optimization and there are plenty of ISPs and servers running without an opcode optimizer.

Not everything has to be OOP, often it is too much overhead, each method and object call consumes a lot of memory.

Do not implement every data structure as a class, arrays are useful, too

Don't split methods too much, think, which code you will really re-use

You can always split the code of a method later, when needed

Make use of the countless predefined functions

If you have very time consuming functions in your code, consider writing them as C extensions

Profile your code. A profiler shows you, which parts of your code consumes how many time. The Xdebug debugger already contains a profiler. Profiling shows you the bottlenecks in overview

mod_gzip which is available as an Apache module compresses your data on the fly and can reduce the data to transfer up to 80%

Sunday 17 June 2012

Introduction to Wordpress Plugin Development

—A WordPress Plugin is a program, or a set of one or more functions, written in the PHP scripting language, that adds a specific set of features or services to the WordPress weblog

—Now a days many plugins are available and for requirement first need to search for available functions if it is already available you can use them directly else need to develop.

—In development of plugin first part of the page required to be comment describing about the plugin, author, license, etc.

—It all should be written within the php comment.

<?php

/*

Plugin Name: Name Of The Plugin
Plugin URI: http://URI_Of_Page_Describing_Plugin_and_Updates Description: description of the Plugin.
Version: The Plugin's Version Number, e.g.: 1.0
Author: Name Of The Plugin Author
Author URI: http://URI_Of_The_Plugin_Author
License: A "Slug" license name e.g. GPL2

*/

?>

WordPress Plugin Hooks


Many WordPress Plugins accomplish their goals by connecting to one or more WordPress Plugin "hooks". 


The way Plugin hooks work is that at various times while WordPress is running, WordPress checks to see if any Plugins have registered functions to run at that time, and if so, the functions are run. These functions modify the default behavior of WordPress.

For instance, before WordPress adds the title of a post to browser output, it first checks to see if any Plugin has registered a function for the "filter" hook called "the_title". If so, the title text is passed in turn through each registered function, and the final result is what is printed. So, if your Plugin needs to add some information to the printed title, it can register a "the_title" filter function.

Template Tags

Another way for a WordPress Plugin to add functionality to WordPress is by creating custom Template Tags. Someone who wants to use your Plugin can add these "tags" to their theme, in the sidebar, post content section, or wherever it is appropriate.
In a theme file functions are written with the help of php code <?php ?>

Saving Plugin Data to the Database

Plugins will need to get some input from the site owner or blog users and save it between sessions, for use in its filter functions, action functions, and template functions. This information has to be saved in the WordPress database, in order to be persistent between sessions.


There are three methods for saving Plugin data in the database:

÷   Use the WordPress "option" mechanism (described below). This method is appropriate for storing         relatively small amounts of relatively static, named pieces of data -- the type of data you'd expect the site owner to enter when first setting up the Plugin, and rarely change thereafter.

÷ Post Meta : Appropriate for data associated with individual posts, pages, or attachments ex. add_post_meta(), update_post_meta()

÷ Create a new, custom database table : This method is appropriate for data not associated with individual posts, pages, attachments, or comments -- the type of data that will grow as time goes on, and that doesn't have individual names.
There are two kind of Hooks available in wordpress.


Hooks


÷   Actions: Actions are the hooks that the WordPress core launches at specific points during execution, or when specific events occur. Your plugin can specify that one or more of its PHP functions are executed at these points, using the Action API.

÷   Filters: Filters are the hooks that WordPress launches to modify text of various types before adding it to the database or sending it to the browser screen. Your plugin can specify that one or more of its PHP functions is executed to modify specific types of text at these times, using the Filter API.

Actions

—Actions are triggered by specific events that take place in WordPress, such as publishing a post, changing themes, or displaying a page of the admin panel. Your plugin can respond to the event by executing a PHP function, which might do one or more of the following:

÷   Modify database data
÷   Send an email message
÷   Modify what is displayed in the browser screen (admin or end-user)

Ex.

class emailer {
function send($post_ID) {
$friends = 'bob@example.org,susie@example.org';
mail($friends,"sally's blog updated",'I just put something on my blog: ');
return $post_ID;
}
}

add_action('publish_post', array('emailer', 'send'));


Actions Functions
÷   has_action()
÷    add_action()
÷    do_action()
÷    do_action_ref_array()
÷    did_action()
÷    remove_action()
÷    remove_all_actions()

After your function is defined, the next step is to "hook" or register it with WordPress. To do this, call add_action() in the global execution space of your plugin file:

add_action ( 'hook_name', 'your_function_name', [priority], [accepted_args] );

÷    hook_name - name of an action hook provided by WordPress, that tells what event your function should be associated with.
÷ your_function_name  - The name of the function that you want to be executed following the event specified by hook_name. This can be a standard php function, a function present in the WordPress core, or a function defined by you in the plugin file (such as 'email_friends'defined above).
÷ priority - An optional integer argument that can be used to specify the order in which the functions associated with a particular action are executed (default: 10). Lower numbers correspond with earlier execution, and functions with the same priority are executed in the order in which they were added to the action.
÷ accepted_args An optional integer argument defining how many arguments your function can accept (default 1), useful because some hooks can pass more than one argument to your function.

Ex. add_action ( 'publish_post', 'email_friends' );

  ÷ hook_name
                      init - Typically used by plugins to initialize
                      register_sidebar – for each sidebar
                      wp_footer – for footer
                      Shutdown – php execution about to end / end of action
                      loop_start – loop start
                      Loop_end – loop end (ex. In comment)
                      plugins_loaded – After active plugins and pluggable functions are loaded
                      wp_loaded – when full wordpress is loaded

                 Visit for more hook_name http://codex.wordpress.org/Plugin_API/Action_Reference

has_action() 
Desc : Check if any action has been registered for a hook. 
<?php has_action( $tag, $function_to_check ) ?> 
÷  $tag(string) (required) The name of the action hook.
         Default: None
÷  $function_to_check(callback) (optional) If specified, return the priority of that function on this hook or false if not attached.Default: fals 

do_action()
       Desc : Executes a hook created by add_action. Placing argument for add_action.
<?php do_action( $tag, $arg ); ?> 
÷  $tag(string) (required) The name of the hook you wish to execute.
Default: None 
÷   $arg(mixed) (optional) The list of arguments to send to this hook. 
Default: ''

do_action_ref_array()
Desc : Execute functions hooked on a specific action hook, specifying arguments in an array. 
This function is identical to do_action, but the arguments passed to the functions hooked to $tag are supplied using an array. 
<?php do_action_ref_array( $tag, $arg ); ?>  
÷  $tag(string) (required) The name of the action to be executed.
         Default: None 
÷  $args(array) (required) The arguments supplied to the functions hooked to $tag
Default: None
did_action()
Desc : Retrieve the number of times an action is fired.
—<?php did_action( $tag ); ?> 
remove_action()
Desc : This function removes a function attached to a specified action hook. This method can be used to remove default functions attached to a specific action hook and possibly replace them with a substitute. 
<?php remove_action( $tag, $function_to_remove, $priority, $accepted_args ); ?>
remove_all_actions()
Desc : Remove all of the hooks from an action. 
<?php remove_all_actions( $tag, $priority ) ?> 

Filters

 Filters are functions that WordPress passes data through, at certain points in execution, just before taking some action with the data.

Filters sit between the database and the browser - when WordPress is generating pages.
and between the browser and the database - when WordPress is adding new posts and comments to the database

The basic steps to adding your own filters to WordPress (described in more detail below) are:

÷  Create the PHP function that filters the data.
÷  Hook to the filter in WordPress, by calling add_filter()
÷  Put your PHP function in a plugin file, and activate it.

Create a Filter Function
A filter function takes as input the unmodified data, and returns modified data (or in some cases, a null value to indicate the data should be deleted or disregarded). If the data is not modified by your filter, then the original data must be returned so that subsequent plugins can continue to modify the value if necessary. 
function filter_profanity($content) {
    $profanities = array('badword','alsobad','...');
    $content=str_ireplace($profanities,'{censored}',$content);
    return $content;
add_filter('comment_text','filter_profanity');
add_filter()
Desc : Hooks a function to a specific filter action. 
<?php add_filter( $tag, $function_to_add, $priority, $accepted_args ); ?> 
has_filter()
Desc : Check if any filter has been registered for a hook. 
<?php has_filter( $tag, $function_to_check ); ?>
apply_filter()
Desc : Call the functions added to a filter hook. 
<?php apply_filters( $tag, $value, $var ... ); ?> 
current_filter()
Desc : Retrieve the name of the current filter or action. 
<?php current_filter(); ?>

Introduction to Wordpress

Word presss was released in 

Founder of wordpress is Matt Mullenweg

WordPress is one such advanced blogging tool and it provides a rich set of features. Through its Administration Panels, you can set options for the behavior and presentation of your weblog. Via these Administration Panels, you can easily compose a blog post, push a button, and be published on the internet, instantly! WordPress goes to great pains to see that your blog posts look good, the text looks beautiful, and the html code it generates conforms to web standards. 


WordPress.com lets you easily create your own blog and write about the things that interest you. It is a blogging community managed by makers of the open source WordPress software. WordPress.com blogs are free with the option of adding upgrades such as personalized domain names, custom CSS, video storage, and more. In comparison, a self-hosted WordPress.org blog does not have upgrades and must be installed on a web hosting account separately. See WordPress.com vs. WordPress.org to learn more about the differences.

Features

Themes

WordPress users may install and switch between \theme. Themes allow users to change the look and functionality of a WordPress website or installation without altering the informational content. Themes may be installed by using the Wordpress "Dashboard" administration tool, or by uploading theme folders via FTP. The PHP and HTML code in themes can also be edited for more advanced customizations.

Plugins

One very popular feature of WordPress is its rich plugin architecture which allows users and developers to extend its abilities beyond the features that are part of the base install; WordPress has a database of over 18,000 plugins with purposes ranging from SEO to adding widget.


Widgets

Widgets are small modules that offer users drag-and-drop sidebar content placement and implementation of many plugins' extended abilities. Widgets allow WordPress developers to add functionality to their sites. These small widgets can be used to add functionality such as a slideshow, Facebook-like box, small news slider, and more.


Multi-user and multi-blogging

Prior to WordPress 3.0, WordPress supported one blog per installation, although multiple concurrent copies may be run from different directories if configured to use separate database tables. WordPress Multi-User (WordPress MU, or just WPMU) was a fork of WordPress created to allow multiple blogs to exist within one installation that is able to be administered by a centralized maintainer. WordPress MU makes it possible for those with a website to host their own blogging community, as well as control and moderate all the blogs from a single dashboard. WordPress MU adds eight new data tables for each blog.

Mobiles

Native applications exist for WebOS, Android, iOS (iPhone, iPod Touch, iPad) Windows Phone 7, and Blackberry which provide access to some of the features in the WordPress Admin panel and work with WordPress.com and many WordPress.org blogs.

What is Blog

"Blog" is an abbreviated version of "weblog," which is a term used to describe web sites that maintain an ongoing chronicle of information. A blog features diary-type commentary and links to articles on other Web sites, usually presented as a list of entries in reverse chronological order. Blogs range from the personal to the political, and can focus on one narrow subject or a whole range of subjects.

Many blogs focus on a particular topic, such as web design, home staging, sports, or mobile technology. Some are more eclectic, presenting links to all types of other sites. And others are more like personal journals, presenting the author's daily life and thoughts.

Generally speaking (although there are exceptions), blogs tend to have a few things in common:
 




A main content area with articles listed chronologically, newest on top. Often, the articles are organized into categories.
An archive of older articles.
A way for people to leave comments about the articles.
A list of links to other related sites, sometimes called a "blogroll".
One or more "feeds" like RSS, Atom or RDF files.


Useful features of Blog


Archives  


                   It commonly seen at the front page of a blog. A few recent entries, some links to other sites and not much else. However its worth knowing that there is a lot more going on under the surface that might initially meet the eye. For example in addition to the main page of this blog – at the time of writing this post there are over 520 other pages or posts below the surface that I’ve written over the past few months.

   Comments
                     Not all blogs use comments – but most do. This blog is not a monologue but a conversation. You can give me feedback on almost everything I write simply by clicking the ‘comments’ link at the bottom of each one of my posts. This will take you to a little form where you leave your name, email and a link to your own blog if you have one as well as your feedback, comment, critique, question, essay on why you love my blog, promise of money…. etc). Try it now. Scroll to the bottom of this page, click ‘comments’ and fill in the blanks with a little introduction to yourself.