Thursday, January 31, 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.

Tuesday, March 20, 2012

Web Service Using PHP & NuSOAP

’As application developers, the ability to develop software and services for a wide range of platforms is a necessary skill, but not everyone uses the same language or platform and writing code to support them all is not feasible. If only there was a standard that allowed us to write code once and allow others to interact with it from their own software with ease. Well luckily there is… and it’s name is SOAP. (SOAP used to be an acronym which stood for Simple Object Access Protocol, but as of version 1.2 the protocol goes simply by the name SOAP.) SOAP allows you to build interoperable software and allows others to take advantage of your software over a network. It defines rules for sending and receiving Remote Procedure Calls (RPC) such as the structure of the request and responses. Therefore, SOAP is not tied to any specific operating system or programming language. As that matters is someone can formulate and parse a SOAP message in their chosen language In this first of a two part series on web services I’ll talk about the SOAP specification and what is involved in creating SOAP messages. I’ll also demonstrate how to create a SOAP server and client using the excellent NuSOAP library to illustrate the flow of SOAP. In the second part I’ll talk about the importance of WSDL files, how you can easily generate them with NuSOAP as well, and how a client may use a WSDL file to better understand your web service.

The Structure of a SOAP Message
SOAP is based on XML so it is considered human read, but there is a specific schema that must be adhered to. Let’s first break down a SOAP message, stripping out all of its data, and just look at the specific elements that make up a SOAP message.


 
  ...
 
 
  ...
  
   ...
  
 


This might look like just an ordinary XML file, but what makes it a SOAP message is the root element Envelope with the namespace soap as http://www.w3.org/2001/12/soap-envelope. The soap:encodingStyle attribute determines the data types used in the file, but SOAP itself does not have a default encoding. soap:Envelope is mandatory, but the next element, soap:Header, is optional and usually contains information relevant to authentication and session handling. The SOAP protocol doesn’t offer any built-in authentication, but allows developers to include it in this header tag. Next there’s the required soap:Body element which contains the actual RPC message, including method names and, in the case of a response, the return values of the method. The soap:Fault element is optional; if present, it holds any error messages or status information for the SOAP message and must be a child element of soap:Body. Now that you understand the basics of what makes up a SOAP message, let’s look at what SOAP request and response messages might look like. Let’s start with a request.


 
  
   IBM
  
 


Above is an example SOAP request message to obtain the stock price of a particular company. Inside soap:Body you’ll notice the GetStockPrice element which is specific to the application. It’s not a SOAP element, and it takes its name from the function on the server that will be called for this request. StockName is also specific to the application and is an argument for the function. The response message is similar to the request:

 
  
   183.08
  
 


Inside the soap:Body element there is a GetStockPriceResponse element with a Price child that contains the return data. As you would guess, both GetStockPriceResponse and Price are specific to this application. Now that you’ve seen an example request and response and understand the structure of a SOAP message, let’s install NuSOAP and build a SOAP client and server to demonstrate generating such messages.

Building a SOAP Server
It couldn’t be easier to get NuSOAP up and running on your server; just visit sourceforge.net/projects/nusoap, download and unzip the package in your web root direoctry, and you’re done. To use the library just include the nusoap.php file in your code. For the server, let’s say we’ve been given the task of building a service to provide a listing of products given a product category. The server should read in the category from a request, look up any products that match the category, and return the list to the user in a CSV format. Create a file in your web root named productlist.php with the following code:

register("getProd");
$server->service($HTTP_RAW_POST_DATA);


First, the nusoap.php file is included to take advantage of the NuSOAP library. Then, the getProd() function is defined. Afterward, a new instance of the soap_server class is instantiated, the getProd() function is registered with its register() method. This is really all that’s needed to create your own SOAP server – simple, isn’t it? In a real-world scenario you would probably look up the list of books from a database, but since I want to focus on SOAP, I’ve mocked getProd() to return a hard-coded list of titles. If you want to include more functionality in the sever you only need to define the additional functions (or even methods in classes) and register each one as you did above. Now that we have a working server, let’s build a client to take advantage of it.

Building a SOAP Client
Create a file named productlistclient.php and use the code below:

getError();
if ($error) {
    echo "

Constructor error

" . $error . "
"; } $result = $client->call("getProd", array("category" => "books")); if ($client->fault) { echo "

Fault

";
    print_r($result);
    echo "
"; } else { $error = $client->getError(); if ($error) { echo "

Error

" . $error . "
"; } else { echo "

Books

";
        echo $result;
        echo "
"; } }

Once again we include nusoap.php with require_once and then create a new instance of nusoap_client. The constructor takes the location of the newly created SOAP server to connect to. The getError() method checks to see if the client was created correctly and the code displays an error message if it wasn’t. The call() method generates and sends the SOAP request to call the method or function defined by the first argument. The second argument to call() is an associate array of arguments for the RPC. The fault property and getError() method are used to check for and display any errors. If no there are no errors, then the result of the function is outputted. Now with both files in your web root directory, launch the client script (in my case http://localhost/nusoap/productlistclient.php) in your browser. You should see the following:

If you want to inspect the SOAP request and response messages for debug purposes, or if you just to pick them apart for fun, add these lines to the bottom of productlistclient.php:

echo "

Request

"; echo "
" . htmlspecialchars($client->request, ENT_QUOTES) . "
"; echo "

Response

"; echo "
" . htmlspecialchars($client->response, ENT_QUOTES) . "
";

The HTTP headers and XML content will now be appended to the output.

Source: http://phpmaster.com/web-services-with-php-and-soap-1/


Sunday, November 20, 2011

Nivo Silder - jQuery Plugin Usage

To use the Nivo Slider you have to include the following in your page:

jQuery
Nivo Slider script
Nivo Slider CSS
You also need to add some body HTML. This is ususally just a
with images. Note that only images or images wrapped in links are allowed in the slider div. Any other HTML will break the slider.

Download a Free Version From Here : Download Nivo Silder 
To add a caption to an image you simply need to add a title attribute to the image. To add an HTML Caption simply set the title attribute to the ID of a element that contains your caption (prefixed with a hash). Note that the HTML element that contains your caption must have the CSS class nivo-html-caption applied and must be outside of the slider div.
Then it helps to add some CSS to make the slider look good while it’s loading:
.nivoSlider {
    position:relative;
    width:618px; /* Change this to your images width */
    height:246px; /* Change this to your images height */
    background:url(images/loading.gif) no-repeat 50% 50%;
}
.nivoSlider img {
    position:absolute;
    top:0px;
    left:0px;
    display:none;
}
.nivoSlider a {
    border:0;
    display:block;
}
.nivoSlider {
    position:relative;
    width:618px; /* Change this to your images width */
    height:246px; /* Change this to your images height */
    background:url(images/loading.gif) no-repeat 50% 50%;
}
.nivoSlider img {
    position:absolute;
    top:0px;
    left:0px;
    display:none;
}
.nivoSlider a {
    border:0;
    display:block;
} 


Finally you need to hook up your script using the $(window).load() function:

The Nivo Slider has plenty of options to fiddle with. Below is an example of the code with all available options and their defaults: 
The effect parameter can be any of the following:

sliceDown
sliceDownLeft
sliceUp
sliceUpLeft
sliceUpDown
sliceUpDownLeft

etc...

Note: For Fix in IE & Opera Browsers (To Display Image) Use the Following Code in Style sheet.
#slider a{
    display:block;
}

Thursday, November 3, 2011

Pagination Conditions in Cakephp

Here the pagination conditions will be described for Cakephp v.1.2

function index() {
        $conditions = array($product['Product']['status']=>0);  // Give the  Pagination Condition.
        $paginationParameters = array();
        $paginationParameters['controller'] = 'products';
        $paginationParameters['action'] = $this->action;
        $this->paginate['Product'] = array(
        'limit' => 1,
        'order' => array ('Product.id' => 'asc'),
        'url' => array ('url' => $paginationParameters)
        );
        $products = $this->paginate($conditions);
        $this->Product->recursive = 0;
        $this->set('products',  $products);
    }
It Will Display the Products according to the Product Status in View page (like app/views/products/index.ctp)

Wednesday, October 26, 2011

Simple Pagination In Cakephp

Achieving Pagination in Cakephp is Slight simple. We use the initial method for applying the pagination.Here i use the Helper to load a paginate class and its instantiate part by using $paginate variable in Controller.
For this first up all, we define the Helper variable like, 



var $name='news';//init for news.
var $helpers=array('Html','Session'); // Load the Helpers to an array.
var $paginate=array('limit' =>5, 'order'=> array('News.id'=>'asc')); //init for Paginate and its options.

// Then we make the Controller - newsController - Code

function index(){
$data=$this->$paginate('News'); 
//Apart from find(); function we use the paginate();
$this->set('news',$data);
} 

In View Page (views/news/index.ctp page), we add the following code for display the data with Pagination. 

echo $html->css('default'); //  if need to load Style sheet.
 
echo $html->link(
    'Add New News',
    array(
      'controller' => 'News',
      'action'     => 'add',
    ),
    array(
     
    ),
    null
);
 

echo $html->tableHeaders(
    array(
      'ID',
      'Title',
      'News',
      'Comments'
    )
  );

foreach($news as $news)
{
  echo $html->tableCells(
      array(
        array(
          $news['News']['id'],
          $news['News']['n_title'],
          $news['News']['n_news'],
          $news['News']['n_comments']
        )
      )
    );
}
 
 

echo $html->div(
  null,
  $paginator->prev(
    '<< Previous',
    array(
      'class' => 'PrevPg'
    ),
    null,
    array(
      'class' => 'PrevPg DisabledPgLk'
    )
  ).
  $paginator->numbers().
  $paginator->next(
    'Next >>',
    array(
      'class' => 'NextPg'
    ),
    null,
    array(
      'class' => 'NextPg DisabledPgLk'
    )
  ),
  array(
    'style' => 'width: 100%;'
  )
);  
It displays the data with Pagination. Displays first 5 rows as per set the limit by 5.

Tuesday, October 25, 2011

Cakephp Basic Steps : Need To Understand By Beginers.

Understanding CakePhp Structure

Cakephp using basic MVC Architecture and it resolves the structural forms (eg. Form Handling) in new Version 1.3.



Models :-
Models represent data and are used in CakePHP applications for data access. Used for Communicating View and Controller. (Ex. Database Connection,Table,Query Dealings).

Controller :-
A controller is used to manage the logic for a part of your application. Most commonly, controllers are used to manage the logic for a single model.It represents the Core Part of the MVC.

Views :- Views are responsible for generating the specific output required for the request. Often this is in the form of HTML, XML, or JSON, but streaming files and creating PDF's that users can download are also responsibilities of the View Layer.

Apart from this basic Architecture, we need more tools to create a MVC World, like

Components :-Components are packages of logic that are shared between controllers. If you find yourself wanting to copy and paste things between controllers, you might consider wrapping some functionality in a component.
CakePHP also comes with a fantastic set of core components you can use to aid in:
  • Security
  • Sessions
  • Access control lists
  • Emails
  • Cookies
  • Authentication
  • Request handling
This represents the Controller Extensions.
A Component is a class that aids in controller logic.
If you have some logic you want to share between controllers (or applications), a component is usually a good fit.

Controllers are also fitted with callbacks. These callbacks are available for your use, just in case you need to insert some logic between CakePHP’s core operations. Callbacks available include:

  • beforeFilter(), executed before any controller action logic
  • beforeRender(), executed after controller logic, but before the view is rendered
  • afterFilter(), executed after all controller logic, including the view render. There may be no difference between afterRender() and afterFilter() unless you’ve manually made a call to render() in your controller action and have included some logic after that call.
View Extensions ("Helpers")

A Helper is a class that aids in view logic. Much like a component used among controllers, helpers allow presentational logic to be accessed and shared between views. One of the core helpers, AjaxHelper, makes Ajax requests within views much easier.

Model Extensions ("Behaviors")

Similar to Components and Helpers, "Behaviors" work as ways to add common functionality between models. For example, if you store user data in a tree structure, you can specify your "User" model as behaving like a tree, and gain free functionality for removing, adding, and shifting nodes in your underlying tree structure.

Just like controllers, models are featured with callbacks as well:

  • beforeFind()
  • afterFind()
  • beforeValidate()
  • beforeSave()
  • afterSave()
  • beforeDelete()
  • afterDelete()
A Typical CakePHP Request




File and Classname Conventions

In general, filenames are underscored while classnames are CamelCased. So if you have a class MyNiftyClass, then in Cake, the file should be named my_nifty_class.php. Below are examples of how to name the file for each of the different types of classes you would typically use in a CakePHP application:
  • The Controller class KissesAndHugsController would be found in a file named kisses_and_hugs_controller.php (notice _controller in the filename)
  • The Component class MyHandyComponent would be found in a file named my_handy.php
  • The Model class OptionValue would be found in a file named option_value.php
  • The Behavior class EspeciallyFunkableBehavior would be found in a file named especially_funkable.php
  • The View class SuperSimpleView would be found in a file named super_simple.php
  • The Helper class BestEverHelper would be found in a file named best_ever.php