Monday, 23 December 2013

RESTful Web Service in Cake php Framework


Representational State Transfer (REST)




Many newer application programmers are realizing the need to open their core functionality to a greater audience. Providing easy, unfettered access to your core API can help get your platform accepted, and allows for mashups and easy integration with other systems.

While other solutions exist, REST is a great way to provide easy access to the logic you’ve created in your application. It’s simple, usually XML-based (we’re talking simple XML, nothing like a SOAP envelope), and depends on HTTP headers for direction. Exposing an API via REST in CakePHP is simple.
The Simple Setup
The fastest way to get up and running with REST is to add a few lines to your routes.php file, found in app/Config. The Router object features a method called mapResources(), that is used to set up a number of default routes for REST access to your controllers. Make sure mapResources() comes before require CAKE . 'Config' . DS . 'routes.php'; and other routes which would override the routes. If we wanted to allow REST access to a recipe database, we’d do something like this:


//In app/Config/routes.php...
Router::mapResources('recipes');
Router::parseExtensions();
The first line sets up a number of default routes for easy REST access where method specifies the desired result format (e.g. xml, json, rss). These routes are HTTP Request Method sensitive. 
HTTP format URL.format Controller action invoked
GET /recipes.format RecipesController::index()
GET /recipes/123.format RecipesController::view(123)
POST /recipes.format RecipesController::add()
PUT /recipes/123.format RecipesController::edit(123)
DELETE /recipes/123.format RecipesController::delete(123)
POST /recipes/123.format RecipesController::edit(123)
CakePHP’s Router class uses a number of different indicators to detect the HTTP method being used. Here they are in order of preference: 1. The _method POST variable 2. The X_HTTP_METHOD_OVERRIDE 3. The REQUEST_METHOD header The _method POST variable is helpful in using a browser as a REST client (or anything else that can do POST easily). Just set the value of _method to the name of the HTTP request method you wish to emulate. Once the router has been set up to map REST requests to certain controller actions, we can move on to creating the logic in our controller actions. A basic controller might look something like this:
// Controller/RecipesController.php
class RecipesController extends AppController {
 
    public $components = array('RequestHandler');
 
    public function index() {
        $recipes = $this->Recipe->find('all');
        $this->set(array(
            'recipes' => $recipes,
            '_serialize' => array('recipes')
        ));
    }
 
    public function view($id) {
        $recipe = $this->Recipe->findById($id);
        $this->set(array(
            'recipe' => $recipe,
            '_serialize' => array('recipe')
        ));
    }
 
    public function edit($id) {
        $this->Recipe->id = $id;
        if ($this->Recipe->save($this->request->data)) {
            $message = 'Saved';
        } else {
            $message = 'Error';
        }
        $this->set(array(
            'message' => $message,
            '_serialize' => array('message')
        ));
    }
 
    public function delete($id) {
        if ($this->Recipe->delete($id)) {
            $message = 'Deleted';
        } else {
            $message = 'Error';
        }
        $this->set(array(
            'message' => $message,
            '_serialize' => array('message')
        ));
    }
}

Since we’ve added a call to Router::parseExtensions(), the CakePHP router is already primed to serve up different views based on different kinds of requests. Since we’re dealing with REST requests, we’ll be making XML views. You can also easily make JSON views using CakePHP’s built in JSON and XML views. By using the built in XmlView we can define a _serialize view variable. This special view variable is used to define which view variables XmlView should serialize into XML.
If we wanted to modify the data before it is converted into XML we should not define the _serialize view variable, and instead use view files. We place the REST views for our RecipesController inside app/View/recipes/xml. We can also use the Xml for quick-and-easy XML output in those views. Here’s what our index view mightlook like:
// app/View/Recipes/xml/index.ctp
// Do some formatting and manipulation on
// the $recipes array.
$xml = Xml::fromArray(array('response' => $recipes));
echo $xml->asXML();

When serving up a specific content type using parseExtensions(), CakePHP automatically looks for a view helper that matches the type. Since we’re using XML as the content type, there is no built-in helper, however if you were to create one it would automatically be loaded for our use in those views. The rendered XML will end up looking something like this:

    
        
        
    
    
        
        
    


Creating the logic for the edit action is a bit trickier, but not by much. Since you’re providing an API that outputs XML, it’s a natural choice to receive XML as input. Not to worry, the RequestHandler and Router classes make things much easier. If a POST or PUT request has an XML content-type, then the input is run through Cake’s Xml class, and the array representation of the data is assigned to $this->request->data. Because of this feature, handling XML and POST data in parallel is seamless: no changes are required to the controller or model code. Everything you need should end up in $this->request->data.
Accepting input in other formats
Typically REST applications not only output content in alternate data formats they also accept data in different formats. In CakePHP, the RequestHandlerComponent helps facilitate this. By default it will decode any incoming JSON/XML input data for POST/PUT requests and supply the array version of that data in $this->request->data. You can also wire in additional deserializers for alternate formats if you need them, using RequestHandler::addInputType()
Modifying the default REST routes
If the default REST routes don’t work for your application, you can modify them using Router::resourceMap(). This method allows you to set the default routes that get set with Router::mapResources(). When using this method you need to set all the defaults you want to use:
Router::resourceMap(array(
    array('action' => 'index', 'method' => 'GET', 'id' => false),
    array('action' => 'view', 'method' => 'GET', 'id' => true),
    array('action' => 'add', 'method' => 'POST', 'id' => false),
    array('action' => 'edit', 'method' => 'PUT', 'id' => true),
    array('action' => 'delete', 'method' => 'DELETE', 'id' => true),
    array('action' => 'update', 'method' => 'POST', 'id' => true)
));

By overwriting the default resource map, future calls to mapResources() will use the new values. 


Custom REST Routing
If the default routes created by Router::mapResources() don’t work for you, use the Router::connect() method to define a custom set of REST routes. The connect() method allows you to define a number of different options for a given URL. See the section on Using additional conditions when matching routes for more information.

Saturday, 26 October 2013

Scalability - In Programming Paradigm

What is Scalability?

There are a number of different aspects of scalability. It always starts with performance, which is what we will cover in this article. But it also covers issues such as code maintainability, fault tolerance, and the availability of programming staff.

These are all reasonable issues, and should be covered whenever you are choosing the development platform for any large project. But in order to convey a convincing argument in this small space, I need to reduce the term scalability to its core concern: performance.

Language and Database Performance

Both Java and PHP run in virtual machines, which means that neither perform as well as compiled C or C++. In the great language shootout, Java beat PHP on most of the performance benchmarks, even substantially on some. However, overall the two languages were not an order of magnitude different. In addition, an older version of PHP was used in the test, and substantial performance improvements have been made since and are continuing to be made.

Another area of performance concern is in the connection to the database. This is a misnomer, however, as the majority of the time spent in a database query is on the database server end, processing the query, and the transmit time to marshal the data between the server and the client. PHP's connectivity to the database consists of either a thin layer on top of the C data access functions, or a database abstraction layer called PEAR::DB. There is nothing to suggest that there is any PHP-specific database access performance penalty.

Yet another area of efficiency concern is in the connection between the language and the web server. In the CGI model, the program or interpreter is booted on each request. In the in-process model, the interpreter stays around after each request. One of the original Java-versus-scripting-languages (e.g. PHP) benchmarks pit in-process Java against CGI invocation on the server. In the CGI model, each page incurred the overhead of the startup and shutdown of the interpreter. Even at the time, the comparison was unfair, as production machines used server-scripting extensions (such as PHP), which run in-process and stay loaded between each page fetch. There is no performance penalty for loading the interpreter and compiled pages remain in memory.

With these basic efficiency questions out of the way, it's time to look at the overall architecture of the web application.


Comparing Architectures


There are three basic web architectures in common use today: two-tier, logical three-tier, and physical three-tier. Engineers give them different names and slightly different mechanics, so to be clear about what I mean, I will illustrate the three architectures.

Two-Tier Architecture


A two-tier application web application has one tier for the display and application logic, connected to a second tier, which is the database server. Two-tier web applications perform best because they require the least processing for a single request.


Three-Tier Architecture





A three-tier architecture separates the display and application logic into two separate tiers. To the left, a physical three-tier architecture puts the three tiers onto three separate machines or processes. To the right, a logical three-tier architecture has the application and business logic layer together in one process, but still divided by an API layer.
Three-tier web applications trade some performance hit for better code factoring. With the business logic separated from the user interface, it is possible to access the application logic from multiple directions. For example, we could expose the layer through web services.

J2EE Web Server Architecture


Perhaps the second most contentious part of this article is my definition of a J2EE web server application architecture. Externally to the Java community, the application structure looks clear: JSPs talk to EJBs, which talk to the database. Within the Java community, thestandard J2EE topology is anything but clear. A comparison is only valid between two things, so to decide whether "Java scales and PHP doesn't," I need to be clear about what a Java web application server is.
I'll take the two most common interpretations of J2EE architecture. The first is Sun's EJB 1.0 architecture, and the second is the EJB 2.0 architecture. Shown below is Sun's EJB 1.0 architecture for web application servers:




This is classic physical three-tier architecture, and it pays the performance price. I've highlighted the portions of the architecture that involve network traffic, either via database connection, an overhead shared by PHP, or by Remote Method Invocation (RMI), an overhead not shared by PHP.
To be fair, the connection between the web server and the servlet engine can be avoided with modern application servers and web servers, such as Tomcat and Apache 2.0. At the time when the first versions of the JSP and EJB standards were released, the prevalent web server was (and still is) Apache 1.x, which had a process model that was not compatible with Java's threading model. This meant that a small stub was required on the web server side to communicate with the servlet engine. The remains a non-trivial performance overhead for those that decide to pay it, and was a significant performance overhead when the first scalability comparisons were made.
A much more significant source of overhead was in the RMI connection between the servlet engine and the EJB layer. A page showing ten fields from twenty objects would make two hundred RMI calls before it was completed. This overhead was removed with the EJB 2.0 standard, which introduced local interfaces. This topology is shown below:





This is logical three-tier architecture. The web server box has been removed because more recent web servers are not separated from the servlet code (e.g. Tomcat, Apache 2.0, etc.). As you will see when we compare this model to the PHP model, EJB 2.0 moved Java web application server development closer to the successful, and scalable, PHP model.

PHP Web Server Architecture


PHP has always been capable of running the gamut between a two-tier architecture and a logical three-tier architecture. Early versions of PHP could abstract the business and database access logic into a functional second tier. More recent versions can abstract the business logic with objects, and with PHP 5, these objects can use public, protected, and private access control.
A modern PHP architecture, strikingly similar to the EJB 2.0 model, is shown below:





This is logical three-tier architecture, and this is how modern PHP applications are written. As with Java web servers, the PHP code is in-process with the web server, so there is no overhead in the server talking to the PHP code.
The PHP page acts as a broker between second-tier business objects and Smarty templates, which format the page for presentation. As with the JSP "best practice," the Smarty templates are only capable of displaying the data presented, with rudimentary looping and conditional control structures.
But this is all about the design of the server. What about the architecture of the application itself?

Stateful and Stateless Architecture


The lack of an external, stateful object store, where the application can hold session state, is often voiced as a scalability concern. PHP can use the database as the back-end session store. There is little performance difference, because a network access is required in both cases. An argument can be made that the external object store allows for any arbitrary data to be stored conveniently; however, this is easily offset by the fact that the object store itself is a single point of failure. If the object store is replicated across multiple web servers, that becomes an issue of data replication and cache coherency, which is a very complex problem.
Another familiar Java pattern is the use of a local persistent object store on each web server. The user is limited to a single server by use of sticky sessions on the router. The same could be done in PHP: a local, persistent data store. But this is an anti-pattern anyway, because a sticky session-based server pool is prone to overloading of a single web server. Or should the server go down, the result is the denial of service to a group of customers.
The ideal multi-server model is a pod architecture, where the router round-robins each of the machines and there is only a minimal session store in the database. Transient user interface information is stored in hidden variables on the web page. This allows for the user to run multiple web sessions against the server simultaneously, and alleviates the "back button issue" in web user interfaces.
This section has covered some very complex issues in web application server design. Scalability is mainly about the architecture of the application layer, and there is no one true panacea architecture that will work for all application architectures. The key to success is not in any particular technology, but in simplifying your server model and understanding all of the components of the application layer, from the HTML and HTTP on the front end to the SQL in the back end. Both PHP and Java are flexible enough to create scalable applications for those who spend the time to optimize their application architecture.

The Convergence of Web Application Architecture


This article started by asserting that PHP scales. When the tag-line "Java scales and scripting languages don't" was born, it was based on EJB 1.0, an architecture that most Java architects would consider absurd, based on its high overhead. Based on EJB 1.0, Java's performance was much worse than that of scripting languages. It is only the addition of local interfaces in EJB 2.0 that makes the J2EE architecture perform well.
The argument for PHP scalability is further simplified, however, by the fact that both PHP and J2EE architecture (as well as others) are converging on the same design. And if "J2EE scales" given this simpler, logical three-tier architecture, then it follows that PHP does as well.
The performance principle for scalability is simple: if you want to scale, then you have to serve web pages quickly. To serve web pages quickly, you either have to do less, or do what you do faster. Faster is a non-starter, because Java is not so much faster than PHP that it makes much of a difference. Doing less is the key. By using a logical three-tier architecture and by reducing the number of queries and commands sent to the database, we can get web applications that scale, both in Java and in PHP.
For the open-minded developer, there is a world of applications that can be built quickly, cheaply, robustly, and scalably with PHP. Services such as Amazon, Yahoo, Google, and Slashdot have known about scripting languages for years and used them effectively in production. Yahoo even adopted PHP as its language of choice for development. Don't believe the hype in the white papers that says that PHP isn't for real applications or doesn't scale.
I'm sure that what I have said in this article will be picked to death and ridiculed by some. I stand by what I have said. The idea that PHP does not scale is clearly false at the performance level. In fact, we should have never even gotten to the point where this article was necessary, because as engineers, we should recognize that the argument that one language clearly "scales better" than another is, on its face, ridiculous. As engineers and architects, we need to look objectively at technologies and use a factual and rational basis to make technology decisions.

Tuesday, 22 October 2013

Web Portals - Structure and Architecture : Part-4


Collaboration Platform

Portals also allow the development of collaborative websites for teams and an entire enterprise.

Team Collaboration

The portal ability to allow individuals to create their own communities empowers teams to create a web area and assign a set of collaborative tools (blog, wiki, calendar, tasks, alerts, doc sharing, etc.) to the group. An individual can create or join one or more communities and organize all collaboration within that community.


Organizational Collaboration

Portals are also capable of supporting an entire enterprise for collaboration. As various collaboration tools are implemented, they can be made available to teams through the portal's modular design capability (i.e., add an additional portlet to the system and make available to community owners). As teams collaborate, they input a wide range of resources that can be leveraged by other teams throughout the enterprise.



Social Collaboration

Although teams can be formed by formal organizational roles, they can also be formed by informal roles. Portals enable these teams to join together. For example, a team of experts in various areas of a company can "friend" each other and track various projects they are working on individually. Furthermore, they can come together and form their own ad hoc community for a specific project. Social features such as social equity, rating, friending, presence, internal messaging, and friend activity walls allow these informal teams to easily collaborate.

Social Applications Platform






Web Portals - Structure and Architecture : Part-3


Integration Platform

One of the earliest portal uses was to integrate various existing applications into a single unified user experience. Portals enabled enterprises to pull together information and applications into one website where users based on role would have quick access to all content specific to their role.

UI Integration Platform

Enterprises often have a very large number of websites and web applications that individual users regularly access. One method to improve the user experience and improve overall user productivity is to aggregate these various existing websites and applications into a single portal.

Enterprise Integration Platform

Integrations may also include external systems. ERP systems are often integrated into a portal dashboard, showing status and alerts. Rather than link to each system, a portal would include one or more portlets showing data from the back-end system.

Site Integration Platform

Additionally, portals can integrate various websites into a single unified website. For example, an enterprise may have an anonymous website, customer website, partner website, and an employee website.

Web Portals - Structure and Architecture : Part-2


Web Content Management System

Modern portals include a full workflow enabled web content management system. Many portal websites include a great deal of content that requires regular updates. These updates are often accomplished by non-technical content contributors and need to be approved by content approvers in a workflow approval process.

Easy Updates with Role-Based Approvals

Portals with web content management can additionally have a workflow approval process to allow some people to edit content, which must be approved by others before being published. For example, a website requiring an advertisement on the side of the page could add content via a UI editor. If changes to the advertisement are required, a portal content contributor can log in, make the edit, and save the changes. If the individual is not approved to publish content changes without review, the system will route the update to a content approver.

Document Repository

Portals can also serve as a repository for documents. Similar to content, documents can be added to the repository and made available through the web interface or website. For example, individuals can publish documents into a central repository and have them be made available to portal users in a central library upon their login.

Web Portals - Structure and Architecture : Part-1

Portals can serve an enterprise in a variety of ways. Read about key use cases and then learn more about Liferay Portal's robust portal, content, and collaboration features.


Web Platform

A portal is generally defined as a software platform for building websites and web applications. Modern portals have added multiple features that make them the best choice for a wide array of web applications. Some common uses for a portal include:






Build Gadgets, Portlets, Pages, Themes, Navigation and Websites

Portal platforms make it easy for users to build web pages and websites by assembling portlets or gadgets onto a portal page. Portal websites combine a theme (header/footer and common look and feel), a set of pages, navigation (menu bar, etc.), and a set of portlets and gadgets. Administrators can build pages without coding by reusing existing portlets and gadgets.

Role-Based Content Delivery

Portals additionally simplify the development of websites that display different data depending on a user's role. For instance, a bank website may feature anonymous and authenticated (logged-in) pages but can additionally have different pages available for various customer types. A standard account can have basic services and pages, while business customers can have additional pages defined.



Anonymous Pages and Authenticated Pages

Portals make it easy to build websites that show different content depending on whether or not the person is logged in.
For example, a bank website may feature a set of pages describing its services, special offers, and contact information that are accessible to all; however, after a customer login, additional content may be available such as account information, bill payment, loans, etc.







Community Pages

In addition, portals allow end-users to define pages, and add content to their pages using predefined portlets or gadgets. They can also define who can access their pages. Team members can then collaborate together within their community site.

Multiple Languages, Multiple Platforms

Once it is developed, a website may need to be made available in multiple languages and from multiple platforms (e.g., smart phones, tablets). The portal provides a method to simplify the development and management of pages for each type of end-user.






Tuesday, 27 August 2013

Match Media Usage - In Cross Browser and IPhone

Firefox 6 was released recently with support for a few nifty new things including window.matchMedia() - a feature that gives developers the JavaScript equivalent of CSS media queries. This welcome addition has been in the FF nightly channel builds for Aurora since April and has been supported by Google Chrome since m10.

There are a number of ways in which window.matchMedia() can be used right out of the box:

window.matchMedia() itself accepts a media-query string as input and returns back a MediaQueryList interface (http://dev.w3.org/csswg/cssom-view/#the-mediaquerylist-interface).

Some basic usage:

//screen width is 800px or wider

if(window.matchMedia("(min-width: 800px)").matches){}



//orientation of the screen is landscape

if(window.matchMedia("(orientation: landscape)").matches)){}



and with event listeners:

var matched = window.matchMedia("(min-width: 800px)");

function matchHandler(mql) {

if ( mql.matches ) {

// width is 800px or wider

} else {

// width is less than 800px

}

}

matched.addListener(matchHandler);

matchHandler(matched);



matchMedia.js works quite similarly, allowing you to perform basic testing as follows:



if ( matchMedia('only screen and (max-width: 480px)').matches ) {

//possibly an iPhone/Smartphone device.

}



For more information on window.matchMedia() see:
The specs: http://dev.w3.org/csswg/cssom-view/#dom-window-matchmedia

MDN page on matchMedia(): https://developer.mozilla.org/en/CSS/Using_media_queries_from_code

and remember to check out the matchMedia.js repo here: https://github.com/paulirish/matchMedia.js