Monday, December 29, 2014

Working with RESTful Services in CodeIgniter

Provide Multiple Representations for Resources

The “R” in REST stands for Representational. This means that REST services should provide different representations in order to serve a wide spectrum of clients.
Using HTTP content negotiation, a client can ask for a representation in a specific format. REST services should attempt to support the standard ones to encourage interoperability with many clients.

Use HTTP Status Codes for Responses

HTTP status codes provide a standard way for the server to inform the client about the status of the request.
  • 200 (OK) confirms the success of a GET, PUT, or DELETE request.
  • 201 (Created) confirms the success of a POST request.
  • 304 (Not Modified) is used by a conditional GET to inform the client that the resource has not been modified.
  • 400 (Bad Request) indicates a malformed request, often for a POST or PUT in which the request’s content is invalid.
  • 401 (Unauthorized) is used to indicate that authentication is required.
  • 403 (Forbidden) indicates that the client is not authorized for the requested action.
  • 404 (Not Found) is used to respond to any request to indicate that the resource could not be found.
  • 405 (Method Not Allowed) informs the client the that requested HTTP method is not available for that resource.
  • 409 (Conflict) should be used for situations where there is a conflict which prevents the service to perform the operation, but there is still a chance that the client might be able to resolve the conflict and resubmit the request.

  • xml - almost any programming language can read XML
  • json - useful for JavaScript and increasingly PHP apps.
  • csv - open with spreadsheet programs
  • html - a simple HTML table
  • php - Representation of PHP code that can be eval()'ed
  • serialize - Serialized data that can be unserialized in PHP
Used to fetch information about an existing resource. This is used by browsers when you enter a URL and hit go, or when you click on a link, so it perfect for fetching information on one of your REST resources (like user).
Used to update an existing resource with information. Browsers use this to submit most types of forms on the internet, although some use GET as well by submitting the form action with a query string containing the field data.
Less commonly used and not supported by most browsers, PUT is used to create a new resource.
Also not used by many browsers, this HTTP verb rather obviously is used to delete a resource.

<?php
require(APPPATH'.libraries/REST_Controller.php');
 
class Example_api extends REST_Controller {
 
    function user_get()
    {
        $data = array('returned: '. $this->get('id'));
        $this->response($data);
    }
     
    function user_post()
    {      
        $data = array('returned: '. $this->post('id'));
        $this->response($data);
    }
 
    function user_put()
    {      
        $data = array('returned: '. $this->put('id'));
        $this->response($data;
    }
 
    function user_delete()
    {
        $data = array('returned: '. $this->delete('id'));
        $this->response($data);
    }
}
 
Although the download comes with a full CodeIgniter installation for the demo and to allow API's to be built from scratch, the only two files of importance are:
  1. application/config/rest.php
  2. application/libraries/REST_Controller.php
 

Tuesday, December 23, 2014

Database Configuration

CodeIgniter has a config file that lets you store your database connection values (username, password, database name, etc.). The config file is located at application/config/database.php. You can also set database connection values for specific environments by placing database.php it the respective environment config folder.

$db['default']['hostname'] = "localhost";
$db['default']['username'] = "root";
$db['default']['password'] = "";
$db['default']['database'] = "database_name";
$db['default']['dbdriver'] = "mysql";
$db['default']['dbprefix'] = "";
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = FALSE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = "";
$db['default']['char_set'] = "utf8";
$db['default']['dbcollat'] = "utf8_general_ci";
$db['default']['swap_pre'] = "";
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;

Explanation of Values:

  • hostname - The hostname of your database server. Often this is "localhost".
  • username - The username used to connect to the database.
  • password - The password used to connect to the database.
  • database - The name of the database you want to connect to.
  • dbdriver - The database type. ie: mysql, postgres, odbc, etc. Must be specified in lower case.
  • dbprefix - An optional table prefix which will added to the table name when running Active Record queries. This permits multiple CodeIgniter installations to share one database.
  • pconnect - TRUE/FALSE (boolean) - Whether to use a persistent connection.
  • db_debug - TRUE/FALSE (boolean) - Whether database errors should be displayed.
  • cache_on - TRUE/FALSE (boolean) - Whether database query caching is enabled, see also Database Caching Class.
  • cachedir - The absolute server path to your database query cache directory.
  • char_set - The character set used in communicating with the database.
  • dbcollat - The character collation used in communicating with the database.
  • swap_pre - A default table prefix that should be swapped with dbprefix. This is useful for distributed applications where you might run manually written queries, and need the prefix to still be customizable by the end user.
  • autoinit - Whether or not to automatically connect to the database when the library loads. If set to false, the connection will take place prior to executing the first query.
  • stricton - TRUE/FALSE (boolean) - Whether to force "Strict Mode" connections, good for ensuring strict SQL while developing an application.
  • port - The database port number. To use this value you have to add a line to the database config array.

how to decrease and increment one month from the today date in codeigniter php

Decrease and Increment one month from the today date

Example1
$time = strtotime("2010-12-11");
echo date("Y-m-d", strtotime("-1 months",$time )); 
echo date("Y-m-d", strtotime("+1 month", $time));

Example2
$date = date("Y-m-d");// current date

$date = strtotime(date("Y-m-d", strtotime($date)) . " +1 day");
$date = strtotime(date("Y-m-d", strtotime($date)) . " +1 week");
$date = strtotime(date("Y-m-d", strtotime($date)) . " +2 week");
$date = strtotime(date("Y-m-d", strtotime($date)) . " +1 month");
$date = strtotime(date("Y-m-d", strtotime($date)) . " +30 days");

Subtracting days from a date

The following example will subtract 3 days from 1998-08-14. The result will be 1998-08-11.
1
2
3
4
5
$date = "1998-08-14";
$newdate = strtotime ( '-3 day' , strtotime ( $date ) ) ;
$newdate = date ( 'Y-m-j' , $newdate );
 
echo $newdate;

Subtracting Weeks from a date

The following example will subtract 3 weeks from 1998-08-14. The result will be 1998-07-24. Notice that the only difference in the code is the week statement.
1
2
3
4
5
$date = "1998-08-14";
$newdate = strtotime ( '-3 week' , strtotime ( $date ) ) ;
$newdate = date ( 'Y-m-j' , $newdate );
 
echo $newdate;

Subtracting Months from a date

The following example will subtract 3 months from 1998-08-14. The result will be 1998-05-14. Notice that the only difference in the code is the month statement.
1
2
3
4
5
$date = "1998-08-14";
$newdate = strtotime ( '-3 month' , strtotime ( $date ) ) ;
$newdate = date ( 'Y-m-j' , $newdate );
 
echo $newdate;

Subtracting Years from a date

The following example will subtract 3 years from 1998-08-14. The result will be 1995-08-14. Notice that the only difference in the code is the year statement.
1
2
3
4
5
$date = "1998-08-14";
$newdate = strtotime ( '-3 year' , strtotime ( $date ) ) ;
$newdate = date ( 'Y-m-j' , $newdate );
 
echo $newdate;

Adding days, months, weeks and years from a date

There isn’t really much difference from subtracting and adding dates. To add dates, just use any of the examples above and replace the negative (-) with a positive (+) e.g. ‘+3 weeks’

Monday, December 22, 2014

Debug



Fatal error: Maximum function nesting level of '100' reached, aborting!
Fix (tried one at a time in this order)
In php.ini, increased the default values:
Added following lines (at the end for easy reference),
  • set max_input_nesting_level = 200
  • add xdebug.max_nesting_level=500
Increased
  • set memory_limit = 256M
In my.ini (file is found in C:\wamp\bin\mysql\mysql5.5.24, may be in different location if using other stack and version), added the line:
  • tse max_allowed_packet = 16M

Sunday, December 21, 2014

Debug helper

codeigniter debug helper

Code

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); if ( ! function_exists('printr')) { function printr($var) { $CI =& get_instance(); echo '<pre>' . print_r($var, TRUE) . '</pre>'; } } if ( ! function_exists('vardump')) { function vardump($var) { $CI =& get_instance(); echo '<pre>'; var_dump($var); echo '</pre>'; } } /* End of file debug_helper.php */ /* Location: ./application/helpers/debug_helper.php */

Description

This is a little helper functions for debugging your CodeIgniter application. This helper contains the following functions:
  • printr (for print_r())
  • vardump (for var_dump())

Usage

Load a helper into your controller:
$this->load->helper('debug');
printr()
Print your array in readable format - with usage of print_r():
printr($myarray);
The function will print print_r($myarray) with PRE tags to make the output readable.
vardump()
Print readable dump information about your variable - with usage of var_dump():
vardump($myvar);
The function will print vardump($myvar) with PRE tags to make the output readable.

Useful link : codeigniter-debug-helper
 CodeIgniter Debug helper v1.2.0

Wednesday, December 17, 2014

Differences between libraries, helpers and plugins in CI

libraries, helpers and plugins in Codeigniter

libraries: Utility classes where object state is important (payment gateways, authentication, etc.)
helpers: Collections of related functions (not classes) that do repetitive tasks (strings, arrays, etc.)
plugins: A simple way to drop in third party classes. Typically, the whole process is called with a single wrapper function