Wednesday, October 23, 2013

codeigniter web cache example, custom data cache with file adapter, db cache is automatic

//for db cache
$db['default']['cache_on'] = TRUE;//FALSE;
$db['default']['cachedir'] = APPPATH.'cache/db';//''
//for web cache
$config['cache_path'] = FCPATH.'cache/';

<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class items extends HO_Site {

    function __construct() {
        parent::__construct();
       
        //for web cache
        $this->output->cache(intval(config_item('web_cache_minute')));
        $this->output->enable_profiler(ENVIRONMENT == 'development');
       
        //for custom cache
        $this->load->driver('cache', array('adapter' => 'file'));
    }
   
    //web output cache
    function show($id) {  
        $items = array();
        array_push($items, $id . ".boroo");
        array_push($items, $id . ".boldbaatar");

        // Load the subview
        $this->view($items);
    }
   
    //custom data cache
    function ss() {
        $this->load->model('category_model');
        $data = array();
        if (!$data['category'] = $this->cache->get('id')){
            $data['category'] = $this->category_model->get_list();
            $this->cache->save('id', $data['category'], 300);
        } else {
            echo 'sql queries cached...';
        }
        $this->view($data);
    }

}

?>

Monday, October 21, 2013

php super xml writer from array objects with attr, cdata

<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * b.boldbaatar
 *
 * xml tool for array to xml
 * @author        HiimelOyun Dev Team
 * @link        boroo_c@yahoo.com
 */
// ------------------------------------------------------------------------

class HO_XmlTool {

    protected static $FOLDER = 'xml/';

    public function __construct() {
      
    }

    // read
    // -----------------------------------------------------------------------
    public function read_file($file_name) {
        $file_path = FILESPATH . self::$FOLDER . trim($file_name, '/');
        $reader = new XMLReader();

        if (!$reader->open(site_url($file_path))) {
            die("Failed to open 'data.xml'");
        }
        $output = '';
        if ($reader->read()) {
            $output = $reader->readOuterXml();
        }
        $reader->close();
        return $output;
    }

    public function load_file($file_name) {
        $file_path = FILESPATH . self::$FOLDER . trim($file_name, '/');
        $reader = new XMLReader();

        if (!$reader->open(site_url($file_path))) {
            die("Failed to open 'data.xml'");
        }
        $node = NULL;
        while ($reader->read()) {
            $node = $reader->expand();
            if ($node->nodeType == XMLReader::ELEMENT) {
                break;
            }
        }
        $reader->close();
        return $node;
    }

    public function load_xml($xml) {
        $reader = new XMLReader();

        if (!$reader->xml($xml)) {
            die("Failed to open 'data.xml'");
        }
        $node = NULL;
        while ($reader->read()) {
            $node = $reader->expand();
            if ($node->nodeType == XMLReader::ELEMENT) {
                break;
            }
        }
        $reader->close();
        return $node;
    }

    // write
    // -----------------------------------------------------------------------

    public function &start($prm_xsltFilePath = '') {
        $xml_writer = new XMLWriter();
        $xml_writer->openMemory();
        $xml_writer->setIndent(true);
        $xml_writer->setIndentString(' ');
        $xml_writer->startDocument('1.0', 'UTF-8');
        if ($prm_xsltFilePath) {
            $this->writePi('xml-stylesheet', 'type="text/xsl" href="' . $prm_xsltFilePath . '"');
        }
        return $xml_writer;
    }

    public function end(&$xml_writer) {
        $xml_writer->endDocument();
        return $xml_writer->outputMemory();
    }

    public function fromArray($prm_array, &$xml_writer) {
        foreach ($prm_array as $index => $element) {
            if (is_array($element)) {
                if (!is_int($index)) {
                    $this->_startElement($xml_writer, $index, $element);
                    $this->_endElement($xml_writer);
                } else {
                    $this->fromArray($element, $xml_writer);
                }
            } else {
                $this->_startElement($xml_writer, $index, $element);
                $this->_endElement($xml_writer);
            }
        }
    }

    private function _startElement(&$xml_writer, $name, $value) {
        $cdata = false;
        $attrs = array();
        $index = json_decode($name);

        if (is_array($index) && !empty($index)) {
            $list = (array) $index;

            foreach ($list as $item) {
                if (is_bool($item)) {
                    $cdata = $item;
                } elseif (is_object($item)) {
                    $attrs = (array) $item;
                } else {
                    $name = $item;
                }
            }
        }
      
        $xml_writer->startElement($name);
        if (count($attrs) > 0) {
            foreach ($attrs as $attr_name => $attr_value) {
                $xml_writer->writeAttribute($attr_name, $attr_value);
            }
        }
        if (!is_array($value)) {
            if ($cdata) {
                $xml_writer->writeCData($value);
            } else {
                if (!is_null($value)) {
                    $xml_writer->text($value);
                }
            }
        } else {
            $this->fromArray($value, $xml_writer);
        }
    }

    private function _endElement(&$xml_writer) {
        $xml_writer->endElement();
    }

}

?>

usage

<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class some extends HO_Site {

    public function index() {
        $this->load->library('XmlTool');
        $val = json_encode(array('name', array('role' => 'admin'), TRUE));
        $prm_array = array(
            'class' => array(
                //'["name",{"role":"admin"},true]'
                $val => 'computer software',
                'employees' => array(
                    array(
                        'employee' => array(
                            'name' => 'boroo',
                            'tasks' => array(
                                array(
                                    'task' => array(
                                        'name' => 'com1'
                                    )
                                ),
                                array(
                                    'task' => array(
                                        'name' => 'com2',
                                        'time' => '3'
                                    )
                                ),
                            )
                        )
                    ),
                    array(
                        'employee' => array(
                            'name' => 'odgii',
                        )
                    )
                )
            )
        );

        $xml = new HO_XmlTool();
        $xml_writer = $xml->start();
        $xml->fromArray($prm_array, $xml_writer);
        header('Content-type: text/xml');
        echo $xml->end($xml_writer);
    }

}

?>

Monday, October 7, 2013

codeigniter shopping cart items example

<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Home extends HO_Controller {

    public function index() {
        $this->load->library('cart');
        $items = $this->cart->contents();
        if (!isset($items) || empty($items)) {

            $data = array(
                'id' => 2546,
                'qty' => 1,
                'price' => 39.95,
                'name' => 'T-Shirt',
                'options' => array('Size' => 'L', 'Color' => 'Red')
            );
            $this->cart->insert($data);
        } else {
            foreach ($items as $data) {
                echo $data['name'].'->'.$data['price'];
            }
        }
    }

}

?>

Friday, September 27, 2013

codeigniter url rewrite index.php redirect to base url

.htaccess

RewriteEngine On

# Keep these lines even in maintenance mode, to have an access to the website
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond $1 !^(index\.php|robots\.txt)
RewriteRule ^(.*)$ index.php/$1

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(application|modules|plugins|system|themes) index.php/$1 [L]

call this php in codeigniter.php

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class HO_INC {

function __construct()
{
$this->config =& load_class('Config', 'core');
log_message('debug', "CORE Class Initialized");
}

public function index_php_to_base_url($method = 'refresh')
{
if ( ! isset($_SERVER['REQUEST_URI']) OR ! isset($_SERVER['SCRIPT_NAME']))
{
return;
}

$uri = $_SERVER['REQUEST_URI'];
if (strpos($uri, $_SERVER['SCRIPT_NAME']) === 0)
{
$uri = substr($uri, strlen($_SERVER['SCRIPT_NAME']));

            if ( ! preg_match('#^https?://#i', $uri))
            {
                $uri = $this->config->site_url($uri);
            }

            switch($method)
            {
                case 'refresh' : header("Refresh:0;url=".$uri);
                    break;
                default : header("Location: ".$uri, TRUE, 200);
                    break;
            }
            exit;
        }
    }
}