Friday, 3 July 2015

Why to use Framework in PHP

Introduction

The word FRAMEWORK is the combination of two words, i.e., FRAME and WORK. It means, one FRAME has already been designed and developer has to WORK on that FRAME to meet his/her project requirements. It’s just a tool, which helps a developer to code better and faster.
In computer language, a Framework is a universal, reusable software platform to develop software applications, products and solutions. In other words, we can say it is some kind of library, a piece of software, which provides web developers with code base and consistent standardized ways of creating web applications.
Back when PHP and other technology started, developers were writing their own custom code for each functionality. Later, some people realized that, writing the same code every time, in every page, not reusing it extensively, plain PHP is not so effective.
Afterwards, as the PHP object model developed (especially with the launch of PHP 5), framework development really came into action and became so popular.
So, let's not stretch this topic as chewing gum Big Grin | :-D and let’s check what are the key benefits of using a Framework, especially in PHP.

Organizing Code and File

When you setup a PHP Framework, it already has a certain folder structure. Most of the Framework uses MVC (Model-View-Controller) guideline or structure for managing the code. MVC pattern allows to separate business logics and presentation layer of your website, making its structure consistent and maintainable. It is expected from you to follow the same standards and keep everything organized in a certain way. Once you get used to this model, you will never want to go back.

The MVC Pattern

The Popular PHP frameworks like CakePHP, CodeIgniter, Zend Framework, Symfony follow Model View Controller(MVC) design pattern which separates business logic from user interface making the code cleaner and extensible. The way the MVC Pattern applies to PHP applications is as follows:
  • Models represent your data structures, usually by interfacing with the database.
  • Views contain page templates and output.
  • Controllers handle page requests and bind everything together.

Enforcing of Good Coding Standards

Another effect of using Framework is maintaining coding standard in an efficient manner. Coding conventions are a set of guidelines for a specific programming language that recommend programming style, practices and methods for each aspect of a piece program written in this language. Using Framework makes it so much easier to code as you should.

Utilities and Libraries

PHP is a great language for web development and provides countless number of tools and libraries. As everybody can guess, these frameworks contains a lot of libraries to make your job easier. All top PHP frameworks come with certain Libraries and Helpers, that help you with:
  • Form Validation
  • SOAP/REST API
  • Caching Mechanism
  • Input/Output Filtering
  • Data Handle With JSON
  • Database Abstraction
  • Session and Cookie Handling
  • Email, Calendar, Pagination, etc…

Less Code & Faster Development

These MVC frameworks will really help you to develop the project rapidly, if you know one framework well then you’ll never worry about the project deadline. You will write less code, which means less time spent typing. You will not have to chase down 3rd party libraries all the time for every new project because most of them will come with the default framework installed. While working on a large project in a team, these MVC PHP frameworks will be a great tool for development as you can assign a developer to develop the MVC part of a module for a developer and integration will be quite easy for these developed modules at final level. Also, since you are being more organized, it will be much faster to chase down bugs, maintain code, and make changes to the existing code.

Community Support

All popular PHP Frameworks have great active communities behind them. There is no lack of support from the community, the documentation, and the developers. If you have any questions or need any clarifications, a quick search with the right keywords should almost always give you relevant results. If not, there’s still the message boards, mailing lists, the official and unofficial forums or the unofficial IRC channel.

Security

With a framework, most of the work for code security can be done for you automatically. For example:
  • Central Authentication
  • Any value passed to database object gets filtered against SQL injection attacks
  • Central input validation and filtering
  • All HTML generating functions, such as form helpers and URL helpers filter the output automatically
  • Cross Site Request Forgery (CSRF) Protection
  • Session Management Security
  • Cross Site Scripting (XSS) Protection
  • Encrypting cookies automatically is only a matter of changing a config option and lot more…

Performance Tools

Framework tools are utility module for maintaining modular applications. You can actually gain per Code generation makes developers life easier by creating files and default content automatically so you don’t have to do the same thing again. Framework comes with tools that help you to do caching, benchmarks, profiling, etc… Modern frameworks are also great with dynamic loading, as they load code only as needed. Lazy loading concept is also there, to make the web page ready, till the time content is ready. Different page requests can load different amounts of library code based on what needs to be used.

Simplified and Pretty URLs

Most Frameworks use a bit of mod_rewrite magic to ensure your URLs are always clean and accessible. Apache handles requests to a particular URL, and (hidden to the client) returns this URL to /index.php as a GET string. The index page instantiates your main framework object. Accessible URLS also help with SEO. URLs are great for the below reasons:
  • They look prettier
  • They are easier to remember
  • They help you save filespace on pages which have many links
  • They are easier to link to, both for you and for other webbies
  • They help cut down on typos because there is less confusion about what exactly to write and type

Efficiently Access Database

Framework provides the way to access database in an object-oriented way. Instead of directly interacting with the database using SQL queries, you can use any Object-Relational Mapping (ORM) model to manage the structure and relationships between your data. With ORM model, you can map your database table to a PHP class and a row from that table is mapped to an instance of that class.

Conclusion

You might not opt for using PHP Framework or using a Framework may or may not be the best choice for you. But, if we believe the words “Performance Really Matters”, then we can try for any popular PHP Framework, and that will be an even easier and robust way to develop applications. Frameworks are cool and easy, and we can’t tell what tomorrow is going to bring. I hope this blog will help you to understand what are the advantages of using a Framework and will value developers.
After reading the above post, are we still thinking, whether to use Framework or not !!! \:-| Eek! | :eek: :(
But, if we got the points and benefits of Framework, then Cool | :cool: Wink | ;-) , we are way to go Smile | :) . Hope you will like this post and will use Framework, if not till now :mrgreen:.

PS: codeproject.com

Thursday, 2 July 2015

What are persistent cookies used for?


Persistent cookies help websites remember your information and settings when you visit them in the future. This result in faster and more convenient access since, for example, you don't have to login again.
Besides authentication, other website features made possible by persistent cookies include: language selection, theme selection, menu preferences, internal site bookmarks or favorites, among many others. On your first visit, the website is presented in default mode. During your visit, you select your preferences and these preferences are remembered, through the use of the persistent cookie, the next time you visit the site.


For example, a website may offer its contents in different languages. On your first visit, you may choose to have the content delivered in French and the site may record that preference in a persistent cookie set on your browser. When you revisit that site it will use the cookie to ensure that the content is delivered in French.


A persistent cookie enables a website to remember you on subsequent visits, speeding up or enhancing your experience of services or functions offered.
For example, a website may offer its contents in different languages. On your first visit, you may choose to have the content delivered in French and the site may record that preference in a persistent cookie set on your browser. When you revisit that site it will use the cookie to ensure that the content is delivered in French.
For a demonstration of how a persistent cookie might be used. You can decide whether to allow your browser to accept these types of cookies by changing the settings. For more information, please go to the manage cookies section.

Friday, 26 June 2015

Parallel Multiple API call Using PHP


Here I will explain how to call multiple apis in parallel process. So I am going to use PHP CURL function to achieve it   

#Default GET method

 $nodes =array(array('url'=>"http://rest.example1.com"),
                                   array('url'=>"http://rest.example2.com?id=2&param1=yourvalue"),
                                   array('url'=>"http://rest.example3.com?id=2&param1=yourvalue")
                                    );
   $results = multiThreading($nodes);

#POST Method And PUT Method

 $user_data  will be array of your post data
 like  $user_data['name']= 'dev'; 
        $user_data['email']= 'xyz@test.com';

        $nodes[0]['url'] ="http://rest.";
        $nodes[0]['post'] = $user_data;
        $results = multiThreading($nodes);

#POST Method And PUT Method  - XML Input

$user_data  will be array of your post data
like  $user_data['name']= 'dev'; 
        $user_data['email']= 'xyz@test.com';

        $nodes[0]['url'] ="http://rest.";
        $nodes[0]['post'] = $user_data;
        $results = multiThreading($nodes,array('Content-Type: application/xml'));


Output - var_dump( $results);


function multiThreading($nodes){
$node_count = count($nodes);
$RESP_TIMEOUT = 30;
$curl_arr = array();
$tmp_str_cookies = "";
/* pass your Headers */
$tmp_arr_httpheader = array("Connection: Close");

$master = curl_multi_init();

$options = array(
        CURLOPT_RETURNTRANSFER => true,         // return web page
        CURLOPT_HEADER         => false,        // don't return headers
        CURLOPT_FOLLOWLOCATION => true,         // follow redirects
        CURLOPT_AUTOREFERER    => true,         // set referer on redirect
        CURLOPT_CONNECTTIMEOUT => 10,          // timeout on connect
       // CURLOPT_TIMEOUT        => $RESP_TIMEOUT,          // timeout on response
        CURLOPT_MAXREDIRS      => 10,           // stop after 10 redirects
        CURLOPT_SSL_VERIFYHOST => 0,            // don't verify ssl
        CURLOPT_SSL_VERIFYPEER => false,        //
        CURL_HTTP_VERSION_1_1  => 1,
CURLOPT_NOSIGNAL => true,
CURLOPT_HTTPHEADER =>$tmp_arr_httpheader,
CURLOPT_REFERER => 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']
    );



for($i = 0; $i < $node_count; $i++)
{
$url = (is_array($nodes[$i]) && !empty($nodes[$i]['url'])) ? $nodes[$i]['url'] : $nodes[$i];
$resp_timeout =  (is_array($nodes) && array_key_exists('resp_timeout',$nodes[$i])) ? $nodes[$i]['resp_timeout'] : $RESP_TIMEOUT;
// default 5 secs timeout
$curl_arr[$i] = curl_init();
curl_setopt($curl_arr[$i], CURLOPT_URL, $url);
if (is_array($nodes[$i])) {
if (!empty($nodes[$i]['post'])) {
if (is_array($nodes[$i]['post']))
{
$o="";
foreach ($nodes[$i]['post'] as $k=>$v)
{
$o.= "$k=".$v."&";
}
$post_data=substr($o,0,-1);
}
else
{
$post_data = $nodes[$i]['post'];

}
curl_setopt($curl_arr[$i], CURLOPT_POST,1);
curl_setopt($curl_arr[$i], CURLOPT_POSTFIELDS,$post_data);
}
elseif (!empty($nodes[$i]['put'])) 
{
if (is_array($nodes[$i]['put']))
{
$o="";
foreach ($nodes[$i]['put'] as $k=>$v)
{
$o.= "$k=".$v."&";
}
$post_data=substr($o,0,-1);
}
else
{
$post_data = $nodes[$i]['put'];

}
curl_setopt($curl_arr[$i], CURLOPT_CUSTOMREQUEST,'PUT');
curl_setopt($curl_arr[$i], CURLOPT_POSTFIELDS,$post_data);
}
elseif (!empty($nodes[$i]['delete'])) 
{
curl_setopt($curl_arr[$i], CURLOPT_CUSTOMREQUEST,'DELETE');
}

}
curl_setopt($curl_arr[$i], CURLOPT_TIMEOUT, $resp_timeout);
curl_setopt_array($curl_arr[$i],$options);
curl_multi_add_handle($master, $curl_arr[$i]);

}
do {
curl_multi_exec($master,$running);
usleep(10000);
} while($running > 0);
for($i = 0; $i < $node_count; $i++)
{
$results[$i] = curl_multi_getcontent  ( $curl_arr[$i]  );
$tmp_arr = (curl_getinfo($curl_arr[$i]));
curl_multi_remove_handle($master, $curl_arr[$i]);
curl_close($curl_arr[$i]);

        

}
$rest_latency = $res_latency_array;

curl_multi_close($master);

return $results;
}

Thursday, 25 June 2015

What is Sticky Session?



When your website is served by only 1 web server, for each pair, a session object is created and remains in the memory of the web server. All the requests from the client go to this web server and update this session object. If some data needs to be stored in the session object over the period of interaction, it is stored in this session object and stays there as long as the session exists.
However, if your website is served by multiple web servers which sit behind a load balancer, the load balancer decides which actual (physical) web-server should each request go to. For example, if there are 3 webservers A, B and C behind the load balancer, it is possible that www.mywebsite.com/index.jsp is served from server A, www.mywebsite.com/login.jsp is served from server B and www.mywebsite.com/accoutdetails.php are served from server C.
Now, if the requests are being served from (physically) 3 different servers, each server has created a session object for you and because these session objects sit on 3 independent boxes, there's no direct way of one knowing what is there in the session object of the other. In order to synchronize between these server sessions, you may have to write/read the session data into a layer which is common to all - like a DB. Now writing and reading data to/from a db for this use-case may not be a good idea. Now, here comes the role of sticky-session. If the load balancer is instructed to use sticky sessions, all of your interactions will happen with the same physical server, even though other servers are present. Thus, your session object will be the same throughout your entire interaction with this website.
To summarize, In case of Sticky Sessions, all your requests will be directed to the same physical web server while in case of a non-sticky loadbalancer may choose any webserver to serve your requests.
As an example, you may read about Amazon's Elastic Load Balancer and sticky sessions here :http://aws.typepad.com/aws/2010/04/new-elastic-load-balancing-feature-sticky-sessions.html


Pros & Cons of Sticky Session :

Pros:
  • it's easy-- no app changes required.
  • better utilizes local RAM caches (e.g. look up user profile once, cache it, and can re-use it on subsequent visits from same user)
Cons:
  • if the server goes down, session is lost. (note that this is a con of storing session info locally on the web server-- not of sticky sessions per se). if what's in the session is really important to the user (e.g. a draft email) or to the site (e.g. a shopping cart) then losing one of your servers can be very painful.
  • depending on "sticky" implementation in your load balancer, may direct unequal load to some servers vs. others
  • bringing a new server online doesn't immediately give the new server lots of load-- if you have a dynamic load-balancing system to deal with spikes, stickiness may slow your ability to respond quickly to a spike. That said, this is somewhat of a corner case and really only applies to very large and sophisticated sites.
  • if you have relatively few users but a single user's traffic can swamp one server (e.g. complex pages with SSL, AJAX, dynamically-generated images, dynamic compression, etc.), then stickines may hurt end-user response time since you're not spreading a single user's load evenly across servers. If you have a lot of concurrent users, this is a non-issue since all your servers will be swamped!
    
Sticky Session Configuration :
   

Load balancer stickyness

The balancer supports stickyness. When a request is proxied to some back-end, then all following requests from the same user should be proxied to the same back-end. Many load balancers implement this feature via a table that maps client IP addresses to back-ends. This approach is transparent to clients and back-ends, but suffers from some problems: unequal load distribution if clients are themselves hidden behind proxies, stickyness errors when a client uses a dynamic IP address that changes during a session and loss of stickyness, if the mapping table overflows.
The module mod_proxy_balancer implements stickyness on top of two alternative means: cookies and URL encoding. Providing the cookie can be either done by the back-end or by the Apache web server itself. The URL encoding is usually done on the back-end.
top

Examples of a balancer configuration

Before we dive into the technical details, here's an example of how you might use mod_proxy_balancer to provide load balancing between two back-end servers:
<Proxy "balancer://mycluster">
    BalancerMember "http://192.168.1.50:80"
    BalancerMember "http://192.168.1.51:80"
</Proxy>
ProxyPass "/test" "balancer://mycluster"
ProxyPassReverse "/test" "balancer://mycluster"
Another example of how to provide load balancing with stickyness using mod_headers, even if the back-end server does not set a suitable session cookie:
Header add Set-Cookie "ROUTEID=.%{BALANCER_WORKER_ROUTE}e; path=/" env=BALANCER_ROUTE_CHANGED
<Proxy "balancer://mycluster">
    BalancerMember "http://192.168.1.50:80" route=1
    BalancerMember "http://192.168.1.51:80" route=2
    ProxySet stickysession=ROUTEID
</Proxy>
ProxyPass "/test" "balancer://mycluster"
ProxyPassReverse "/test" "balancer://mycluster"
Please check http://httpd.apache.org/docs/2.4/mod/mod_proxy_balancer.html for more details about configuration

Wednesday, 24 June 2015

Installing PhoneGap/Cordova and Android Studio on Windows

Hello,

I  wanted to develop Hybrid Android App ( Using Javascript  and HTML ) by using phonegap/cordova. I have spent lot of time for installation as there is not complete information about phonegap installation procedure , after searching I came across this article and wanted to published here ,so it will help others.

Install Procedure

ORDER MATTERS

Please follow the installation order as it appears.
  • If you encounter issues when editing your path variables, please see this stack overflow post for some good advise as how to prevent this issue.
  1. Download JDK- Java SE Development Kit - Windows x64 - (latest edition) and Install using default options
    1. Add a system variable JAVA_HOME and point it to the directory containing the contents of the JDK (example C:\Program Files\Java\jdk1.7.0_51)
    2. Add ;%JAVA_HOME%\bin; to the Path system variable.
    3. If you have a Proxy Server, note proxy server settings and:
      1. Start --> Type Java Control Panel
      2. General Tab --> Click Network Settings...
      3. Choose the appropriate settings, "use browser settings" may work for you.
    4. Validate Java Install:
      1. From a command prompt enter the following
        java -version
      2. You should see something like :
        java version "1.7.0_51"
  2. Download Apache Ant and extract to a directory on your computer. (example C:\util\ant\)
    1. Add a system variable ANT_HOME and point it to the directory containing the contents of the ANT directory
    2. Add ;%ANT_HOME%\bin; to the Path system variable.
    3. Validate Ant Install:
      1. From a command prompt enter the following
        ant -version
      2. You should see something like :
        Apache Ant(TM) version 1.9.3 compiled on December 23 2013
      3. Troubleshooting: Unable to locate tools.jar (check to see if JAVA_HOME is set properly)
  3. Download Android Studio and Install using default settings.
    1. If you have a Proxy Server, note proxy server settings and open Android Studio:
      1. File --> Settings --> (IDE Settings Section) --> HTTP Proxy
      2. Make the appropriate selection for your environment.
    2. Add a system variable ANDROID_HOME and point it to the directory containing the android sdk that's installed with Android Studio (example: C:\Users\jdoe\AppData\Local\Android\android-studio\sdk)
    3. Add the following to your Path system variable:
      1. ;%ANDROID_HOME%\platform-tools;%ANDROID_HOME%\tools;
  4. Download Node and Install (if you already have it installed, download and install again to update it)
    1. Clear your NPM cache (this may save some headaches):
      npm cache clean
    2. If behind a firewall, configure node to speak to the firewall by issuing the following commands:
      npm config set proxy http://domain%5Cusername:password@ipaddress:port
      npm config set https-proxy http://domain%5Cusername:password@ipaddress:port
    3. Validate Node Install:
      1. From a command prompt enter the following
        node --version
      2. You should see something like :
        v0.10.26
    4. Update Node & Global Packages
      1. Update Node:
        npm update -g n
      2. Update Global Packages:
        npm update -g
  5. Install Cordova
    npm install -g cordova

Create a New Android Project

  1. In a command prompt, Navigate to a folder that will hold the project (example: C:\MobileApps)
  2. Create a new project:
    cordova create MyFirstMobileApp com.companyName.MyFirstMobileApp MyFirstMobileApp
  3. Navigate to the new project folder:
    cd MyFirstMobileApp
  4. Add the Android Platform:
    cordova platform add android

Setup Android Emulator

  1. Bring up android config:
    android
  2. In the packages tree, in the open Android x.x.x (APIxx) ...
    1. Select Intel x86 Atom System Image
  3. In the packages tree, in Extras..
    1. Select Intel x86 Emulator Accelerator (HAXM)
  4. Click the Install Packages button
  5. Agree to any dialogs that come up.
  6. While still in the android config, note the SDK Path, open windows explorer and navigate to that directory.
  7. Navigate to extras\intel\Hardware_Accelerated_Execution_Manager and run IntelHaxm.exe
  8. While still in the android config, choose tools->manage avds, switch to Device Definitions, select one, Click Create AVD, be sure to choose Intel Atom(x86) for CPU/ABI and in emulation options enable Use Host GPU, choose ok and close out..

Don't Open the project in Android Studio!

  1. When pulling from source control, make sure all files are not read only and run clean.bat in platforms\android\cordova and delete any local.properties files in any directories..this may help relieve headaches!!!

Debugging Android Apps

  1. Choose to debug using an emulator or on a device attached to the computer:
    1. Start and deploy to the android emulator:
      cordova emulate android
    2. Debug using attached android device:
      cordova run android
  2. See cordova android debug output:
    adb start server
    adb devices
    Note : To connect your device to your laptop use USB Cable and
  3.  Install http://adbdriver.com/AdbUsb driver .so it will detect your phone.
  4. You can use Google Chrome Development tools to remotely inspect and debug javascript running on the device (KitKat +) or in the emulator. This is just wonderful!
    1. Update the java code to enable remote debugging
    2. Start the ADB server:
      adb start-server
    3. Open a new chrome window, enter the following url into the addres bar:
      chrome://inspect#devices

Source : Github