Showing posts with label CodeIgnitor. Show all posts
Showing posts with label CodeIgnitor. Show all posts

Monday, October 21, 2013

Display form validation error count in codeigniter V2

The following are the steps for showing the form validation error counts in codeigniter.
Step 1: Create a new file named MY_Form_validation.php under /application/libraries/. Remmeber to Ensure the following line is present in config.php
$config['subclass_prefix'] = 'MY_';

Step 2: Place the following code in the newly created MY_Form_validation.php:

class MY_Form_validation extends CI_Form_validation {

    public function __construct( $rules=array() )
    {
        parent::__construct($rules);
    }

    /*   This function will return the error count    */    
    function get_error_count()
    {
       return count($this->_error_array); 
    }
}

You can find more details about the core form validation class from here
Now you will be able to get the validation error count via the following code: 
$this->load->library('form_validation');
$this->form_validation->get_error_count(); 

Custom 404 page in codeigniter

By default CodeIgniter handles broken links(404), but when it comes to look and feel the default design becomes unpleasant.   In CodeIgniter we can override the default 404 functionality and implement our own custom 404 page very easily. The steps are described below:


Step 1: First create a new controller to handle the 404 page requests. For that just create a new controller under your controllers directory. For example, Say 'custom404Page'.
The controller would look like this 

class 
custom404Page extends CI_Controller {
 public function __construct(){
           parent::__construct();        
  }   
 public function index(){
  $this->output->set_status_header('404');
  $data['errorMessage'] = ' Ooops! Page not found'; 
  $this->load->view('custom404View',$data);//loading view
 }
}

Step 2: Open routes.php  under /application/config/ directory.
Step 2: Find the line which looks like $route['404_override'] = ''. If you cannot find such a line don't worry just add the above code in that file and point your controller file. For example in our case the code will be as below:

 $route['404_override'] = 'custom404Page'


Step4: Now create the view with your design and its all set and ready to roll. 

Another way for handling broken links is to override the Exception core class in CodeIgniter. There is a function called show_404() in CodeIgniter. You can either follow the method described in the above link or follow the following method.  

Step 1: Open config.php  under /application/config/ directory.
Step 2: Ensure the following line is present in config.php
$config['subclass_prefix'] = 'MY_';
Step 3: Now create a new file under /application/libraries/. Say MY_Exception and put the following code in it:

class MY_Exceptions extends CI_Exceptions{

    function MY_Exceptions(){

        parent::CI_Exceptions();
    }

    function show_404($page=''){    

        $this->config =& get_config();
        $baseUrl = $this->config['base_url'];
        header("location: ".$baseUrl.'error.html');//view file location
        /* Use this section if your view file is under views directory
          $CI = &get_instance();
$CI->load->view('custom404View', $data);
       */
        exit;
    }

}


Step 4: Now you can use show_404 function in any of your controllers. for example 

class test extends CI_Controller{
   public function index(){
         if(some condition){
            //do something
         }else{
             show_404();
        }
   }
}

Thursday, October 10, 2013

Integrate and use zend framework 2 with codeigniter

Zend framework 2(ZF2) is an open source framework using PHP 5.3+ with more than 15 million downloads. It should be kept in mind that ZF2 is not backward compatible with ZF1. ZF2 has an unique component structure and each component only have few dependencies on other components. Simply Zend call this architecture as "use-at-will" design.


If you want to integrate Codeigniter and ZF2 then that's a good idea. I assume that you have downloaded both codeigniter and ZF2. Help on installing Zend Framework 2 in ubuntu can be found here.

Now as the two frameworks are downloaded, copy the Zend folder(under library) from Zend download to application/libraries in Codeigniter. The idea here is to use the Zend components as a library in Codeigniter. Lets see an example of using Zend Captcha in Codeigniter.

First we need to create a new file under application/libraries, lets call it "Zend". After creating this file and open it in a text editor and copy paste the following code:

Zend.php

require_once 'autoload.php';
class Zend{

public $obj;
public $objId;

public function __construct(){

}


public function createImageCaptcha($params=array()){
$this->obj = new Zend\Captcha\Image( array(
  'imgDir'=>'public/',
  'font' => 'font/opensans-regular-webfont.ttf',
  'width' => 250,
  'height' => 100,
  'dotNoiseLevel' => 40,
  'lineNoiseLevel' => 3)
);
$this->obj->generate();
return $this->obj;
}

}


In the constructor i am just including the corresponding class file from Zend. The function createImageCaptcha() actually creates an image of type png inside the path you specify, imgDir variable sets the file path and font variable sets the font path. Remember that the paths are relative your root folder. Here what i am trying to do is to create my own wrapper to the Zend components instead of calling them directly in controller. In my controller i would access my Zend Captcha as follows:

$this->load->library('zend');
$captcha = $this->zend->createImageCaptcha();


Here $captcha is an object and will hold all the information regarding the Captcha.  $captcha->getimgDir()  would give you the image directory, $captcha->getId() would give you the filename, $captcha->getsuffix() would give you the file extension and so on. All the properties can be accessed by just appending "get" to them. 

At last but not least we need to know about the file named "autoload.php" which is included in the top. The purpose of this file is to autoload all the dependency files in Zend while instantiating an object. If this file is not present then an error like the following may appear "Fatal error: Class 'Zend\Captcha\AbstractWord' not found", in case of Captcha component. Same  will be the case with all components in Zend. So instead of updating every file with include directive we autoload all the dependent files. 

autoload.php

namespace Zend;
spl_autoload_register(function ($class) {
    if (substr($class, 0, strlen(__NAMESPACE__)) != __NAMESPACE__) {
        //Only autoload libraries from this package
        return;
    }
    $path = substr(str_replace('\\', '/', $class), 0);
    $path = __DIR__ . "/".$path . '.php';
    if (file_exists($path)) {
        require $path;
    }

});

The main purpose of this article is to explain how to use ZF2 modules along with Codeigniter. Hope this article was helpfull. If you find this information incorrect please don't hesitate to comment. There is also an alternative by using the third_party option in Codeigniter. 


Wednesday, October 9, 2013

Twitter codeigniter-php library

I have created a Codeigniter library and a helper that would fetch the tweets from a twitter account and display it. You can find it here. The usage of this library is simple.
in your controller file just add the following to get the tweets.


   $params = array(
'userName'=>'your name',
'consumerKey'=>'your consumer key',
'consumerSecret'=>'your secret',
'accessToken'=>'your access token',
'accessTokenSecret'=>'your access token secret',
'tweetLimit'=>5,// the no of tweets to be displayed
);
$this->load->library('twitter',$params);
$tweets = $this->twitter->getHomeTimeLine();
$this->load->helper('tweet');
$mytweets = getTweetsHTML($tweets);
                echo $mytweets;