Thursday 15 March 2012

What is REST

REST is a term coined by Roy Fielding in his Ph.D. to describe an architecture style of networked systems. REST is an acronym standing for Representational State Transfer.


Why is it called Representational State Transfer?

The Web is comprised of resources. A resource is any item of interest. For example, the Boeing Aircraft Corp may define a 747 resource. Clients may access that resource with this URL:
http://www.boeing.com/aircraft/747
A representation of the resource is returned (e.g., Boeing747.html). The representation places the client application in a state. The result of the client traversing a hyperlink in Boeing747.html is another resource is accessed. The new representation places the client application into yet another state. Thus, the client application changes (transfers) state with each resource representation --> Representational State Transfer!
Here is Roy Fielding's explanation of the meaning of Representational State Transfer:
"Representational State Transfer is intended to evoke an image of how a well-designed Web application behaves: a network of web pages (a virtual state-machine), where the user progresses through an application by selecting links (state transitions), resulting in the next page (representing the next state of the application) being transferred to the user and rendered for their use."

REST is not a standard. You will not see the W3C putting out a REST specification. You will not see IBM or Microsoft or Sun selling a REST developer's toolkit. Why? Because REST is just an architectural style. You can't bottle up that style. You can only understand it, and design your Web services in that style. (Analogous to the client-server architectural style. There is no client-server standard.)
Here are the characteristics of REST
  • Client-Server: a pull-based interaction style: consuming components pull representations.
  • Stateless: each request from client to server must contain all the information necessary to understand the request, and cannot take advantage of any stored context on the server.
  • Cache: to improve network efficiency responses must be capable of being labeled as cacheable or non-cacheable.
  • Uniform interface: all resources are accessed with a generic interface (e.g., HTTP GET, POST, PUT, DELETE).
  • Named resources - the system is comprised of resources which are named using a URL.
  • Interconnected resource representations - the representations of the resources are interconnected using URLs, thereby enabling a client to progress from one state to another.
  • Layered components - intermediaries, such as proxy servers, cache servers, gateways, etc, can be inserted between clients and resources to support performance, security, etc.

Principles of REST Web Service Design

1. The key to creating Web Services in a REST network (i.e., the Web) is to identify all of the conceptual entities that you wish to expose as services. Above we saw some examples of resources: parts list, detailed part data, purchase order.
2. Create a URL to each resource. The resources should be nouns, not verbs. For example, do not use this:
http://www.parts-depot.com/parts/getPart?id=00345
Note the verb, getPart. Instead, use a noun:
http://www.parts-depot.com/parts/00345
3. Categorize your resources according to whether clients can just receive a representation of the resource, or whether clients can modify (add to) the resource. For the former, make those resources accessible using an HTTP GET. For the later, make those resources accessible using HTTP POST, PUT, and/or DELETE.
4. All resources accessible via HTTP GET should be side-effect free. That is, the resource should just return a representation of the resource. Invoking the resource should not result in modifying the resource.
5. No man/woman is an island. Likewise, no representation should be an island. In other words, put hyperlinks within resource representations to enable clients to drill down for more information, and/or to obtain related information.
6. Design to reveal data gradually. Don't reveal everything in a single response document. Provide hyperlinks to obtain more details.
7. Specify the format of response data using a schema (DTD, W3C Schema, RelaxNG, or Schematron). For those services that require a POST or PUT to it, also provide a schema to specify the format of the response.
8. Describe how your services are to be invoked using either a WSDL document, or simply an HTML document.

Monday 12 March 2012

Creating Widgets for WordPress 2.8 and above


In this example we are going to create a widget called "Sample_Widget" and tell PHP that it is going to extend (inherit from) the WP_Widget class. It is the WP_Widget class which makes your widget function, have settings and allow multiple instances so you don't have to.
You will need to rename every occurrence of "Sample_Widget" with the name of your widget.
The first method, Sample_Widget() in the example, is the class constructor which contains the code that is run every time the widget is loaded – either when activated, used on a page, updated and so on.
The second method, form(), contains the settings page on the WordPress widgets administration screen (Appearance -> Widgets). This method is always called form and never changes. Within this function you add all the controls that will appear when the widget options are expanded. See below for an example.
The third method, update(), is called when the user click on "save" from the settings page on the widgets administration screen. This automatically handles saving to the database of options. You can use this function to validate information prior to being saved. See the example below for basic operation.
Finally the widget() function contains the code that will be rendered to the sidebar when the widget is added. This is what your visitors will see when viewing your page.


Let's have a look at a very simple example "Hello World" widget.

Create SampleWidget.php inside /Wp_content/Plugins  folder


<?php
/*
Plugin Name: Sample WordPress Widget
Plugin URI: http://azuliadesings.com/
Version: 1.0
Description: How to create a WordPress Widget
Author: Tim Trott
Author URI: http://azuliadesings.com/
*/

class Sample_Widget extends WP_Widget
{
  function Sample_Widget()
  {
    /* * The first method, Sample_Widget() in the example, is the class constructor which contains the code that is run every time the widget is loaded – either when activated, used on a page, updated and so on.*/
    $widget_ops = array('classname' => 'Sample_Widget', 'description' => 'My Sample Widget Description');
    $this->WP_Widget('Sample_Widget', 'My Sample Widget', $widget_ops);
  }

  function form($instance)
  {
/* *The second method, form(), contains the settings page on the WordPress widgets administration screen (Appearance -> Widgets). This method is always called form and never changes. Within this function you add all the controls that will appear when the widget options are expanded. */
    $instance = wp_parse_args((array) $instance, array( 'title' => '' ));
    $title = $instance['title'];
?>
  <p><label for="<?php echo $this->get_field_id('title'); ?>">Title: <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo attribute_escape($title); ?>" /></label></p>
<?php
  } 
  function update($new_instance, $old_instance)
  {
/* The third method, update(), is called when the user click on "save" from the settings page on the widgets administration screen. This automatically handles saving to the database of options. You can use this function to validate information prior to being saved. See the example below for basic operation.
*/
    $instance = $old_instance;
    $instance['title'] = $new_instance['title'];
    return $instance;
  } 
  function widget($args, $instance)
  {
/*the widget() function contains the code that will be rendered to the sidebar when the widget is added. This is what your visitors will see when viewing your page.
*/
    extract($args, EXTR_SKIP); 
    echo $before_widget;
    $title = empty($instance['title']) ? '' : apply_filters('widget_title', $instance['title']); 
    if (!empty($title))
      echo $before_title . $title . $after_title;; 
    // ** Do Your Widgety Stuff Here...
    echo "<h1>Hello World</h1>"; 
    echo $after_widget;
  }
}
add_action( 'widgets_init', create_function('', 'return register_widget("Sample_Widget");') ); 
?>


How To Create WordPress Widgets

Wordpress plugins are pieces of addon code that extend the functionality of Wordpress, either behind-the-scenes or extra visual code. Widgets allow these code segments to be quickly and easily added to predefined sidebars on most themes. Before WordPress version 2.0, these extra visual plugins had to be hand coded into the theme template, so knowledge of PHP was required. In version 2.0 they introduced "Widgets" which wrap around a plugin and allow a non code editing method for incorporating into a theme using sidebars and a drag and drop interface. This tutorial covers creating a Widget, creating a plugin widget, adding sidebars to a theme, and upgrading a non-widget plugin.

Creating a Simple WordPress Plugin

<?php

/*

Plugin Name: Hello World

Plugin URI: http://example.com/

Description: Sample Hello World Plugin

Author: Deep

Version: 1

Author URI: http://example.com/

*/


function sampleHelloWorld() {

  echo "<h2>Hello World</h2>";

}

?>


The lines inside /* and */ are used by WordPress to find out about the plugin. We have one function called sampleHelloWorld which does exactly that.

Now, traditionally we would have had to open up the sidebar of the theme you are using, find the location of where you want the Hello World displayed, and hard code the function in. Upload to the server and test. If for some reason there is a problem with your plugin (or a third party plugin) then your site would almost certainly stop working. Changing the location from the left to the right sidebar means editing both files accordingly. This isn't very good.

Widgets

Widgets take away the need for editing the sidebar files of a theme and allow for a drag and drop interface in the admin panel. Let's have a look at how we can widget enable our plugin.

Open up the Hello World plugin file again and add these lines.

<?php

function widget_myHelloWorld() {

?>

  <h2 class="widgettitle">My Widget Title</h2>

  <?php sampleHelloWorld(); ?>

<?php

}

function myHelloWorld_init(){

  register_sidebar_widget(__('Hello World'), 'widget_myHelloWorld');

}

add_action("plugins_loaded", "myHelloWorld_init");

//**Add action just tells WordPress to call myHelloWorld_init when the plugin is loaded.

?>

To make Widget Theme compatible

While this widget will function fine, we can make some improvements to enable greater theme compatibility – not everyone uses the same themes as you test on.WordPress will pass parameters to your widget, which contain information about the sidebar and the CSS classes. We should process these parameters and output the correct tags, or you risk breaking some themes.The first thing we need to do is change our sampleHelloWorld function so that it will accept parameters, then to process these parameters into variables. This is done using the extract function.

function widget_myHelloWorld($args) {

     //** $args had been added as parameter

  extract($args);

?>

  <h2 class="widgettitle">My Widget Title</h2>

  <?php sampleHelloWorld(); ?>

<?php

}


again we change hello world function.

These two lines will allow us to reference some variables and output correct html structure for the theme being used. The most important variables are before_widget, after_widget, before_title and after_title. Previously we have surrounded the widget title with a hard coded H2 tag with a css class widgettitle, but many themes do not support these tags. They may use a div, or a h1 or a span, so we need our widget to be flexible.

function widget_myHelloWorld($args) {

  extract($args);

  echo $before_widget;

  echo $before_title;?>My Widget Title<?php echo $after_title;

  sampleHelloWorld();

  echo $after_widget;

}


//** These changes will allow our plugin to use the same tags as the theme author informs us we need to use, and will allow your widget to look the same as the other widgets in the sidebar.

Complete Plugin:

<?php

/*

Plugin Name: Hello World

Plugin URI: http://azuliadesigns.com/

Description: Sample Hello World Plugin

Author: Tim Trott

Version: 1

Author URI: http://azuliadesigns.com/

*/


function sampleHelloWorld()

{

  echo "<h2>Hello World</h2>";

}

function widget_myHelloWorld($args) {

  extract($args);

  echo $before_widget;

  echo $before_title;?>My Widget Title<?php echo $after_title;

  sampleHelloWorld();

  echo $after_widget;

}

function myHelloWorld_init() {

  register_sidebar_widget(__('Hello World'), 'widget_myHelloWorld');

}

add_action("plugins_loaded", "myHelloWorld_init");

?>

If Theme Does Not Have Widget Enable SideBars. If your theme does not have widget enabled sidebars, this will help make it widget enabled. I am using a very basic sidebar theme, most sidebars are a little more complex than this.

<div id="sidebar">

<ul>

<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar() ) : ?>

<?php wp_list_pages('title_li=<h2>Pages</h2>' ); ?><br/>

        <li><h2>Archives</h2>

        <ul>

        <?php wp_get_archives('type=monthly'); ?>

        </ul>

       </li>

<?php wp_list_categories('show_count=1&amp;title_li=<h2>Categories</h2>'); ?>

<?php endif; ?>

</ul>

</div>


The first of these lines does an if else statement, if we have a sidebar function call it otherwise we do the existing hard coded sidebar.The second line (endif) tells the if statement where the hard coded sidebar ends. Anything between the first and second lines will be shown if widgets are disabled or no widgets are assigned to the sidebar.Before you can add a widget to this sidebar, we need to make WordPress aware of it by registering it.Open, or create, functions.php in your theme folder, and find (or add) a line like this.

<?php

if ( function_exists('register_sidebars') )

    register_sidebars(1);

?>


Where the parameter to register_sidebars is the number of sidebars defined in your theme. You can have any number of sidebars. Now you will be able to add widgets to your sidebar.

Should you wish to configure the elements that will appear before and after a widget, or the tags that a widget title will appear in, you can setup the options array and pass it to the register_sidebar function.

register_sidebar(array(

'before_widget' => '<li>',

'after_widget' => '</li>',

'before_title' => '<div class="sidebar_title">',

'after_title' => '</div>',

));


//** This will cause the widget to be contained within <li></li> tags and the widget title will be in a div with the css class sidebar_title.

materials supplied by

By  http://azuliadesigns.com/create-wordpress-widgets/