Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

Friday, July 29, 2011

Using Drupal menu system callback mapping to retrieve JSON or XML data

In my previous post I talked about Drupal menu system callback mapping. Today I'm going to show you how Drupal menu system callback mapping can be used to retrive JSON or XML data.

The way to accomplish the task is to register a path for a menu item with an optional argument. If you pass that optional argument along with the request URL callback function will return JSON data else it will return XML data. In that way callback function will serve both data formats.

Following is a coding example of above mentioned scenario.

<?php
//hook_perm implementation
function example_perm() {
    return array(
        'access city'
    );
}

//hook_menu implementation
function example_menu() {
    $items = array();
 
    //menu item 
    $items['full_city_list'] = array(
        'title' => t('City List JSON'
        ), 'page callback' => 'full_city_list', 'page arguments' => array(
            1
        ), 'access arguments' => array(
            'access city'
        ), 'type' => MENU_CALLBACK);   

    return $items;
}

function full_city_list() {
 $jsonParam=arg(1);//optional argument
 $result = db_query("SELECT  tid,name FROM term_data  WHERE  vid=2 order by name ASC");
 
 if(strcmp($jsonParam, "json") == 0){
    $response = array();
    
    while ($city_data = db_fetch_object($result)) {
        $response[$city_data->name]['city_name'] = $city_data->name;
        $response[$city_data->name]['tid'] = $city_data->tid;
    }

    if (!empty($response)) {
        //encodes city data as json  
        $jsonstrCityList = json_encode($response);
        echo $jsonstrCityList;
    } else {
        return false;
    }
 }elseif(strcmp($jsonParam, "") == 0){
 //sending city data as xml
 $dom = new DOMDocument("1.0");
    $root_elm = $dom->createElement("markers");
    $root = $dom->appendChild($root_elm);    

    while ($city_data = db_fetch_object($result)) {

        $marker_elm = $dom->createElement("marker");
        $marker_node = $root->appendChild($marker_elm);

        $marker_node->setAttribute("name", $city_data->name);
        $marker_node->setAttribute("tid", $city_data->tid);
    }
    header("Content-type: text/xml");
    echo $dom->saveXML();
 }
}
?>



output for http://example.com/full_city_list/json
{"Agalawatta":{"city_name":"Agalawatta","tid":"156"},"Ahungalla":{"city_name":"Ahungalla","tid":"214"},"Akurana":{"city_name":"Akurana","tid":"164"},"Akuressa":{"city_name":"Akuressa","tid":"162"},"Aluthgama":{"city_name":"Aluthgama","tid":"120"},"Ambalangoda":{"city_name":"Ambalangoda","tid":"125"},"Ampara":{"city_name":"Ampara","tid":"211"},"Anuradhapura":{"city_name":"Anuradhapura","tid":"46"},"Arugambay":{"city_name":"Arugambay","tid":"114"},"Avissawella":{"city_name":"Avissawella","tid":"212"},"Badulla":{"city_name":"Badulla","tid":"108"},"Balangoda":{"city_name":"Balangoda","tid":"149"},"Balapitiya":{"city_name":"Balapitiya","tid":"486"},"Bandarawela":{"city_name":"Bandarawela","tid":"197"}}


output for http://example.com/full_city_list
<markers>
<marker name="Agalawatta" tid="156"/>
<marker name="Ahungalla" tid="214"/>
<marker name="Akurana" tid="164"/>
<marker name="Akuressa" tid="162"/>
<marker name="Aluthgama" tid="120"/>
<marker name="Ambalangoda" tid="125"/>
<marker name="Ampara" tid="211"/>
<marker name="Anuradhapura" tid="46"/>
<marker name="Arugambay" tid="114"/>
<marker name="Avissawella" tid="212"/>
<marker name="Badulla" tid="108"/>
<marker name="Balangoda" tid="149"/>
<marker name="Balapitiya" tid="486"/>
<marker name="Bandarawela" tid="197"/>
</markers>

Wednesday, July 20, 2011

Drupal menu system callback mapping

How does drupal menu system callback mapping happen?

When a user makes a request to drupal through a browser, using the request URL drupal menu system decides which callback function to invoke.

what is a callback function?

Callback function in this case is a php function which gets called when a user trying to access a path that has already been registered in a menu item.

In the given example-1 if a browser makes a request using the URL "http://example.com/hello", menu system will look for a menu item which contains that path and invokes the relevant callback function in this case, "hello()".

example-1

<?php

//hook_perm implementation  
function example_perm() {
    return array(
        'access hello'
    );
}

//hook_menu implementation  
function example_menu() {
    $items = array();
    //menu item   
    $items['hello'] = array(
    'title' =--> t('hello'
    ), 'page callback' => 'hello', 'page arguments' => array(
    0
    ), 'access arguments' => array(
    'access hello'
    ), 'type' => MENU_CALLBACK);

    return $items;
}

//callback function  
function hello() {
    echo "hello!";
}
?>  

Output for example-1
hello!

example-2

This example shows how to get city data in json or xml using a request URL.

<?php

//hook_perm implementation
function example_perm() {
    return array(
        'access hello'
    );
}

//hook_menu implementation
function example_menu() {
    $items = array();
    //menu item 
    $items['hello'] = array(
        'title' => t('hello'
        ), 'page callback' => 'hello', 'page arguments' => array(
            0
        ), 'access arguments' => array(
            'access hello'
        ), 'type' => MENU_CALLBACK);

    $items['full_city_list_json'] = array(
        'title' => t('City List JSON'
        ), 'page callback' => 'full_city_list_json', 'page arguments' => array(
            0
        ), 'access arguments' => array(
            'access hello'
        ), 'type' => MENU_CALLBACK);

    $items['full_city_list_xml'] = array(
        'title' => t('City List XML'
        ), 'page callback' => 'full_city_list_xml', 'page arguments' => array(
            0
        ), 'access arguments' => array(
            'access hello'
        ), 'type' => MENU_CALLBACK);

    return $items;
}

function hello() {
    echo "hello!";
}

function full_city_list_json() {
    $response = array();
    $result = db_query("SELECT  tid,name FROM term_data  WHERE  vid=2 order by name ASC");
    while ($city_data = db_fetch_object($result)) {
        $response[$city_data->name]['city_name'] = $city_data->name;
        $response[$city_data->name]['tid'] = $city_data->tid;
    }

    if (!empty($response)) {
        //encodes city data as json  
        $jsonstrCityList = json_encode($response);
        echo $jsonstrCityList;
    } else {
        return false;
    }
}

function full_city_list_xml() {
//sending city data as xml
    $dom = new DOMDocument("1.0");
    $root_elm = $dom->createElement("markers");
    $root = $dom->appendChild($root_elm);

    $result = db_query("SELECT  tid,name FROM term_data  WHERE  vid=2 order by name ASC");

    while ($city_data = db_fetch_object($result)) {

        $marker_elm = $dom->createElement("marker");
        $marker_node = $root->appendChild($marker_elm);

        $marker_node->setAttribute("name", $city_data->name);
        $marker_node->setAttribute("tid", $city_data->tid);
    }
    header("Content-type: text/xml");
    echo $dom->saveXML();
}

?>

Outputs for example-2

for http://example.com/full_city_list_json

{"Agalawatta":{"city_name":"Agalawatta","tid":"156"},"Ahungalla":{"city_name":"Ahungalla","tid":"214"},"Akurana":{"city_name":"Akurana","tid":"164"},"Akuressa":{"city_name":"Akuressa","tid":"162"},"Aluthgama":{"city_name":"Aluthgama","tid":"120"},"Ambalangoda":{"city_name":"Ambalangoda","tid":"125"},"Ampara":{"city_name":"Ampara","tid":"211"},"Anuradhapura":{"city_name":"Anuradhapura","tid":"46"},"Arugambay":{"city_name":"Arugambay","tid":"114"},"Avissawella":{"city_name":"Avissawella","tid":"212"},"Badulla":{"city_name":"Badulla","tid":"108"},"Balangoda":{"city_name":"Balangoda","tid":"149"},"Balapitiya":{"city_name":"Balapitiya","tid":"486"},"Bandarawela":{"city_name":"Bandarawela","tid":"197"}}

for http://example.com/full_city_list_xml

<markers>
<marker name="Agalawatta" tid="156"/>
<marker name="Ahungalla" tid="214"/>
<marker name="Akurana" tid="164"/>
<marker name="Akuressa" tid="162"/>
<marker name="Aluthgama" tid="120"/>
<marker name="Ambalangoda" tid="125"/>
<marker name="Ampara" tid="211"/>
<marker name="Anuradhapura" tid="46"/>
<marker name="Arugambay" tid="114"/>
<marker name="Avissawella" tid="212"/>
<marker name="Badulla" tid="108"/>
<marker name="Balangoda" tid="149"/>
<marker name="Balapitiya" tid="486"/>
<marker name="Bandarawela" tid="197"/>
</markers>


As in example-2 after you grabbed the city data in json or in xml you can parse them and use in any of your applications.

Monday, June 20, 2011

Working with drupal API

It's been a while since I started working with drupal, without a doubt the best CMS ever. I find working with drupal extremely interesting with all those API functions in hand.

Drupal has convenient ways to handle database work for us, therefore it is advisable to use drupal API as much as possible to get the work done. Moreover updating to a new drupal version from an older version is quite less conflicting if we have followed the drupal API.

recently I got the chance to work with some interesting drupal API functions and thought they might be useful for you as well at some point.

  1. node_load()
  2. Given nid(node id) as the parameter this function loads that node from drupal database. I'm not exaggerating if I say this functions helps us to get full control over any node.dreamy isn't it?

    Example usage 1
    <?php 
    $node=node_load(820);//loads the node with the nid equals to 820 and store it in $node variable
    print_r($node);//prints all the information associated with the node, yikes it's lengthy :P 
    ?>
    
    After loading a particular node it is possible to get almost every information related to it.

    Example usage 2
    <?php 
    echo $node->body;//prints the content of the node
    echo $node->title;//prints the title of the node
    ?>
    
  3. truncate_utf8()
  4. truncate_utf8() function truncates a string to a specified number of characters.

    Example usage
    <?php 
    $node=node_load(820);
    $content=truncate_utf8(strip_tags($node->body),400,true,true);//limits the body content of a node to 400 characters
    ?>
    
  5. l()
  6. Creating a link using html is super easy even for a web development newbie, it is possible to use the same method in drupal development, but if you follow drupal API that's not the best way to create a link. l() function comes to the stage at this moment as the drupal's way to create links.

    Example usage
    <?php 
    print l("click here","node/820");
    ?>
    
    above is exactly identical to following
    <a href="node/820">click here</a>
    
  7. url()
  8. url() generates and internal(eg: node/1) or external url.

    Example usage
    <?php 
    $path="node/820";
    $link=url($path,array('absolute'=>TRUE));
    ?>
    
  9. drupal_get_path_alias()
  10. Given an internal drupal path this function returns the alias set by admin.

    Example usage
    <?php 
    $path="node/820";
    $alias=drupal_get_path_alias($path);
    ?>
    

Tuesday, May 24, 2011

Getting started with drupal module development

Drupal is a very handy CMS, there are tons of modules written to extend the functionalities of drupal. This post will guide you to write a simple drupal module.

There must be at least two files to create a drupal module,

  • module_name.info
  • module_name.module

In this example I will use module_name as "cities". Then my two files would be cities.info and cities.module

Create a folder inside sites/all/modules which has the same name as your module, in this case it's "cities". Inside cities create two files cities.info and cities.module

It is possible to save your module in module folder but it is not recommended as that folder is kinda reserved for drupal core module. Instead of messing with core guys it is advisable to maintain a separate place for custom modules.

cities.info

cities.info file contains all the necessary information for drupal to know about your module. name, description, core are the musts in this file. There are also set of optional info which you can include but here in this example I only use required information only.

; $Id$
name = cities
description = This is a module that display list of cities 
core = 6.x


cities.module

what exactly is a hook?

Here is a good question if you are a newbie to drupal module development. Concept of hook is very important when it comes to drupal module development. Module system in drupal is based on hook, simply it's a php fuction which defines set of parameters and a result type. Hooks allow modules to interact with the drupal core.

In this example module I've used three hooks, hook_help, hook_perm and hook_block.

hook_help : provides help and additional information.
hook_perm : defines permissions for the module.
hook_block: creates a block or set of blocks.

We have to replace hook with our module name when using them.

This example block module cities will display a list of cities pulled out of a database.

<?php
// $Id: cities.module$

/**
 * @file
 * This is a module that display list of cities
 */

/**
 * Implementation of hook_help().
 */
function cities_help($path, $arg) {
  switch ($path) {
    case 'cities':
      return '<p>'. t('<b>help hook. This is a module that display list of cities.</b>') .'</p>';
  }
}

/**
 * Implementation of hook_perm().
 */
function cities_perm() {
  return array('access cites');
}

/**
 * grabbing data from the database
 */

global $arr; 
$arr=array();
global $datas;
$datas="";

$link = mysql_connect ('localhost', 'root', '');
$db = mysql_select_db ('cities', $link);

$sql = "SELECT name FROM city";
$sel = mysql_query($sql);
   
   if (mysql_num_rows($sel) > 0) { 
    $i=0;
    while($row = mysql_fetch_array($sel)) {
          
     $arr[$i]=$row['name'];
     $i=$i+1;
    }
    }
    
 foreach( $arr as $key => $value){
   $datas=$datas." ".$value."<br/>";
  }
  mysql_close();

/**
 * Implementation of hook_block().
 */
function cities_block($op = 'list', $delta = 0, $edit = array()) {
global $datas;
  if ($op == "list") {
    $block = array();
    $block[0]["info"] = t('cities');
    return $block;
  }
  elseif ($op == 'view') {
    $block_content = '<p>This is a block that display list of cities.</p>';
    $block['subject'] = 'City List';
    $block['content'] = $datas;
    return $block;
  }
}


Omitting the closing php tag is a drupal coding standard which prevents runtime issues.


Don't forget to enable your module (administrator-->modules) and pick a suitable place (administrator-->block) for it. Available permissions for this module can be viewed and customized from administrator-->permissions

That's it, now with this basic knowledge in hand it's not far away when you write more complex modules.