In my recent project i tried to integrate codeigniter with twig template engine with php-activerecord and so thought to share with everyone.

First you need to have codeigniter downloaded and extracted then download php-activerecord. Now lets integrate both:

1- Extract active record and put it inside /libraries folder so the directory structure becomes /application/libraries/php-activerecord.
2- Create a class Activerecord.php inside libraries folder itself with the following contents

$db_values) {
                // Convert to dsn format
                $dsn[$name] = $db[$name]['dbdriver'] .
                    '://'   . $db[$name]['username'] .
                    ':'     . $db[$name]['password'] .
                    '@'     . $db[$name]['hostname'] .
                    '/'     . $db[$name]['database'];
        // Initialize ActiveRecord
        ActiveRecord\Config::initialize(function($cfg) use ($dsn, $active_group){
/* End of file Activerecord.php */
/* Location: ./application/libraries/Activerecord.php */

3- Configure your config/database.php file to match with your database settings.

And that’s it!! You are done… And can use this easily in your application. All you now need to do is , load the library whenever you want to use it. And to get rid of this you can simple put a line in your config/autoload.php

$autoload['libraries'] = array('activerecord');

Now lets configure codeigniter with twig engine.

For this first get Twig. After extracting you can place this too in your application/libraries folder so that your directory structure becomes


Afterward, you need to create a file named Twig.php in libraries directory and place following code into that

CI =& get_instance();         $this->CI->config->load('twig');           ini_set('include_path',         ini_get('include_path') . PATH_SEPARATOR . APPPATH . 'libraries/Twig');         require_once (string) "Autoloader" . EXT;           log_message('debug', "Twig Autoloader Loaded");           Twig_Autoloader::register();           $this->_template_dir = $this->CI->config->item('template_dir');         $this->_cache_dir = $this->CI->config->item('cache_dir');           $loader = new Twig_Loader_Filesystem($this->_template_dir);           $this->_twig = new Twig_Environment($loader, array(                 'cache' => $this->_cache_dir,                 'debug' => $debug,         ));                 $this->_config['title_separator'] = ' | ';             foreach(get_defined_functions() as $functions) {                     foreach($functions as $function) {                         $this->_twig->addFunction($function, new Twig_Function_Function($function));                     }             }     }       public function add_function($name)      {         $this->_twig->addFunction($name, new Twig_Function_Function($name));     }                  public function add_functions($names)      {             foreach ($names as $name)                 $this->_twig->addFunction($name, new Twig_Function_Function($name));     }       public function render($template, $data = array())      {         $template = $this->_twig->loadTemplate($template);         return $template->render($data);     }       public function display($template, $data = array())      {         $template = $this->_twig->loadTemplate($template.'.html.twig');         /* elapsed_time and memory_usage */         $data['elapsed_time'] = $this->CI->benchmark->elapsed_time('total_execution_time_start', 'total_execution_time_end');         $memory = (!function_exists('memory_get_usage')) ? '0' : round(memory_get_usage()/1024/1024, 2) . 'MB';         $data['memory_usage'] = $memory;         $template->display($data);     }         public function title()     {         if(func_num_args() > 0)         {             $args = func_get_args();               // If at least one parameter is passed in to this method,              // call append() to either set the title or append additional             // string data to it.             call_user_func_array(array($this, 'append'), $args);         }           return $this;     }         public function append()     {         $args = func_get_args();         $title = implode($this->_config['title_separator'], $args);           if(empty($this->_globals['title']))         {             $this->set('title', $title, TRUE);         }         else         {             $this->set('title', $this->_globals['title'] . $this->_config['title_separator'] . $title, TRUE);         }           return $this;     }         public function set($key, $value, $global = FALSE)     {         if(is_array($key))         {             foreach($key as $k => $v) $this->set($k, $v, $global);         }         else         {             if($global)             {                 $this->_twig->addGlobal($key, $value);                 $this->_globals[$key] = $value;             }             else             {                 $this->_data[$key] = $value;             }            }           return $this;     } }

I would like to take you through the functions defined in this file first. Well, first two functions are to add function to twig which will help you call php/codeigniter functions in your template files.

Function title is to add title to the page and function append is to append title to the title you have defined earlier. For example we can create a base title of the website something like “Google” and then append strings to it to appear something like “Google | About” and in these cases append function is very useful.

Set function is used to set a variable which can be accessed in template files and if you set “global=TRUE”, you can access it in your all template files. These all functions may look trivial but actually these are very useful to separate your logic(Controllers) from view completely as view files are only responsible to display data and it’s controller who should handle all the logic behind those data.

Now finally you need to create a file twig.php in your config directory with following contents:

<?php  if (!defined('BASEPATH')) exit('No direct script access allowed'); // Below line is to define the location of all your view files. // For me i wanted to put them in views directory. $config['template_dir'] = APPPATH.'views'; // This is important to locate your cache folder. Although it's not that much important but as a good practice you should create application/cache/twig directory. $config['cache_dir'] = APPPATH.'cache/twig';

And that’s it 🙂 You are done with it.

Now you have to create some view files. You can do it at your own also but in my case i created a folder called _layouts inside views(directory you had configured earlier to handle template files) directory and another directory to place my pages. So my directory structure becomes


So first i created a file application.html.twig in my _layouts/ folder like this.


<!--[if lt IE 9]>-->
        <title>{% block title %}{% endblock %}</title>
        {% block content %}
        {% endblock %}

You see these {% block %} thing? The first one is used to display the title you had set in your controller using that “title” and “append” function we discussed earlier. And the second one to display the page content which will come later.

Now create another file index.html.twig in pages directory with the following contents:

{% extends "_layouts/application.html.twig" %}
{% block title %}{{title}}{% endblock %}
{% block content %}
    Default template data.
{% endblock %}

Now one last line needs to be added in your autoload.php and that is:

$autoload['libraries'] = array('activerecord','twig');

And that’s it.. I hope you enjoyed this. Also if you are looking for Codeigniter Web Development services connect with us at Dignitech Media Works

Please feel free to comment or ask me any query.

Content Source:

We are posting very interesting thing which we believe could be a great help for people who wanna develop scalable applications with lots of images.

We have often seen that when people upload images on websites, they tend to create thumbnails as to make those images appear better on websites. Even we used to do this but recently we analyzed that this method obviously solves our in-hand problem but let say if we want to change the design of our website in future and want different sized image. One way to solve this problem is to keep your original image and run scripts to resize all your images to desired size but we thought to solve this problem with a different approach which is to not resize the images at all and keep it as is.

Now the question is, how do we fit our images in my website?

To solve this problem we created a Codeigniter Class(However it can be used for other frameworks as well with some changes) which would resize our images on the fly. Lets see how:–

 * This is a custom image manupulation library developed by raakesh.
 * @license GNU GPL
 * @author raakesh
 * Released under public license hence author takes no warranty of this code out of this project scope. However, modification of this code is allowed under GNU GPL license.
class Image {
    // Declare all public variables
    var $image;
    var $image_type;
    var $image_name;
    // Function to render final image to the browser
    public function display() {        
        $this->image_name = $_GET['image'];
        if($this->image_type == IMAGETYPE_JPEG)
            $this->check_orientation ($_GET['image']);
        if(isset($_GET['w']) and !isset($_GET['h']))
            $this->resizeToWidth ($_GET['w']);
        if(!isset($_GET['w']) and isset($_GET['h']))
            $this->resizeToHeight ($_GET['h']);
        if(isset($_GET['w']) and isset($_GET['h']))
            $this->crop($_GET['w'], $_GET['h']);            
    function load($filename) {
        $image_info = getimagesize($filename);
        $this->image_type = $image_info[2];
        if ($this->image_type == IMAGETYPE_JPEG) {
            $this->image = imagecreatefromjpeg($filename);
        } elseif ($this->image_type == IMAGETYPE_GIF) {
            $this->image = imagecreatefromgif($filename);
        } elseif ($this->image_type == IMAGETYPE_PNG) {
            $this->image = imagecreatefrompng($filename);
    function output($image_type = IMAGETYPE_JPEG) {
        header('Cache-Control: max-age=86400, public');
        if ($image_type == IMAGETYPE_JPEG) {
            header('Content-Type: image/jpeg');
            imagejpeg($this->image, NULL, 60);
        } elseif ($image_type == IMAGETYPE_GIF) {
            header('Content-Type: image/gif');
        } elseif ($image_type == IMAGETYPE_PNG) {
            header('Content-Type: image/png');
            imagepng($this->image, NULL, 6);
    function getWidth() {
        return imagesx($this->image);
    function getHeight() {
        return imagesy($this->image);
    function resizeToHeight($height) {
        $ratio = $height / $this->getHeight();
        $width = $this->getWidth() * $ratio;
        $this->resize($width, $height);
    function resizeToWidth($width) {
        $ratio = $width / $this->getWidth();
        $height = $this->getheight() * $ratio;
        $this->resize($width, $height);
    function resize($width, $height) {
        $new_image = imagecreatetruecolor($width, $height);
        imagealphablending($new_image, false);
        imagesavealpha($new_image, true);
        $transparent = imagecolorallocatealpha($new_image, 255, 255, 255, 127);
        imagefilledrectangle($new_image, 0, 0, $width, $height, $transparent);
        imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
        $this->image = $new_image;
    function crop($thumb_width, $thumb_height) {
        $width = $this->getWidth();
        $height = $this->getHeight();
        $original_aspect = $width / $height;
        $thumb_aspect = $thumb_width / $thumb_height;
        if ($original_aspect >= $thumb_aspect) {
            // If image is wider than thumbnail (in aspect ratio sense)
            $new_height = $thumb_height;
            $new_width = $width / ($height / $thumb_height);
        } else {
            // If the thumbnail is wider than the image
            $new_width = $thumb_width;
            $new_height = $height / ($width / $thumb_width);
        $new_image = imagecreatetruecolor($thumb_width, $thumb_height);
        imagealphablending($new_image, false);
        imagesavealpha($new_image, true);
        $transparent = imagecolorallocatealpha($new_image, 255, 255, 255, 127);
        imagefilledrectangle($new_image, 0, 0, $thumb_width, $thumb_height, $transparent);
// Resize and crop
        imagecopyresampled($new_image, $this->image, 0 - ($new_width - $thumb_width) / 2, // Center the image horizontally
                0 - ($new_height - $thumb_height) / 2, // Center the image vertically
                0, 0, $new_width, $new_height, $width, $height);
        $this->image = $new_image;
    function check_orientation($source) {
        $exif = exif_read_data($source);        
        $ort = isset($exif['Orientation']) ? $exif['Orientation'] : '';
        switch ($ort) {
            case 2: // horizontal flip
            case 3: // 180 rotate left
                $this->image = imagerotate($this->image, 180, -1);
            case 4: // vertical flip
            case 5: // vertical flip + 90 rotate right
                $this->image = imagerotate($this->image, -90, -1);
            case 6: // 90 rotate right
                $this->image = imagerotate($this->image, -90, -1);
            case 7: // horizontal flip + 90 rotate right
                $this->image = imagerotate($this->image, -90, -1);
            case 8: // 90 rotate left
                $this->image = imagerotate($this->image, 90, -1);
            default :
                $this->image = $this->image;
    public function ImageFlip($x = 0, $y = 0, $width = null, $height = null) {
        if ($width < 1)
            $width = $this->getWidth();
        if ($height < 1)
            $height = $this->getHeight();
        // Truecolor provides better results, if possible.
        if (function_exists('imageistruecolor') && imageistruecolor($this->image)) {
            $tmp = imagecreatetruecolor(1, $height);
        } else {
            $tmp = imagecreate(1, $height);
        $x2 = $x + $width - 1;
        for ($i = (int) floor(($width - 1) / 2); $i >= 0; $i--) {
            // Backup right stripe.
            imagecopy($tmp, $this->image, 0, 0, $x2 - $i, $y, 1, $height);
            // Copy left stripe to the right.
            imagecopy($this->image, $this->image, $x2 - $i, $y, $x + $i, $y, 1, $height);
            // Copy backuped right stripe to the left.
            imagecopy($this->image, $tmp, $x + $i, $y, 0, 0, 1, $height);
        return true;

When i have to use this class, i can simply call it using

 <?= base_url() ?>image/display?image=url-of-your-image&w=width&h=height

With this solution you don’t have to worry about creating different thumbnails for images as well as future design changes. Also read about Secure Image Uploading im PHP.

We hope this will solve your problems. Comments & suggestions are invited.

Content Source: