Icon

Irimis'S Blog

NOT just another blog.

Codeigniter: Keep constants in database

Have you ever asked yourself how to achieve something like that before? How to keep your constants in a MySQL Database? This is very simple :).

First thing first .. We have to create a database table. Let’s name it app_constants

CREATE TABLE IF NOT EXISTS `app_constants` (
  `name` varchar(50) NOT NULL,
  `value` text NOT NULL,
  PRIMARY KEY (`name`),
  UNIQUE KEY `UNIQUE` (`name`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

This is self explanatory. name row will keep our constant name and the value row will keep the constant value. Let’s move ahead and create the functions which will get the constants from Database and initialize them.

		/**
		 * Initialize DB Constants
		 */
		function initConstant() {

			foreach ($this->_getConstant() as $data) {

				$data = get_object_vars($data);
				define($data['name'], $data['value']);
			}

			/**
			 * This is a good place for your IS_AJAX constant (if used)
			 */
			define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
		}

		/**
		 * Get constants from DB
		 */
		function _getConstant() {
			return $this->db->select()->from('app_constants')->get()->result();
		}

That’s it. Keep in mind that this have to be executed earlier using hooks or in your MY_Controller (One controller to rule them all)

CSV parser library for CodeIgniter

I spent last hour working on a CodeIgniter CSV (Comma Separated Values) parser library for a project I’m working on. It use PHP built in function fgetcsv(). The result is a multi-dimensional array.

	class Csv {

		private $file_name = '';
		private $parse_header = FALSE;
		private $delimiter = ',';
		private $length = 0;

		private $header;
		private $file_pointer;

		function __construct($config = array()) {

			if(count($config > 0)) {
				$this->initialize($config);
			}

			log_message('debug', "CSV Class Initialized");
		}

		function initialize($config = array()) {

			foreach($config as $key => $val) {

				if(isset($this->$key)) {
					$this->$key = $val;
				}

			}

			if(is_file($this->file_name))
				$this->file_pointer = fopen($this->file_name, 'r');

			if($this->parse_header) {
				$this->header = fgetcsv($this->file_pointer, $this->length, $this->delimiter);
			}
		}

		function parse() {

			$data = array();

			while(($row = fgetcsv($this->file_pointer, $this->length, $this->delimiter)) !== FALSE) {
				if($this->parse_header) {

					foreach ($this->header as $i => $heading_i)
						$row_new[$heading_i] = $row[$i];

					$data[] = $row_new;
				} else
					$data[] = $row;
			}

			return $data;
		}

		function __destruct() {

			if($this->file_pointer) {
				fclose($this->file_pointer);
			}
		}
	}

For usage, save this library in system/libraries/ or system/application/libraries/ and load it into your controller.

$this->load->library('csv', $params);

Usage example:

Let’s suppose we have a CSV file contains data like this.

Id,Name,Category,Price
1,iPhone,Mobile,300
2,iMac,Desktop,529
3,MacBook,Mobile,2000
4,iTouch,Gadgets,157
5,Wii,Gaming,1250

Load the library

	$params = array(
		'file_name' => '/path/to/csv/file.csv',
		'delimiter' => ',',
		'parse_header' => false,
	);

	$this->load->library('csv', $params);

	var_dump($this->csv->parse());

This is the result with parse_header FALSE

    array
      0 =>
        array
          0 => string 'Id' (length=2)
          1 => string 'Name' (length=4)
          2 => string 'Category' (length=8)
          3 => string 'Price' (length=5)
      1 =>
        array
          0 => string '1' (length=1)
          1 => string 'iPhone' (length=6)
          2 => string 'Mobile' (length=6)
          3 => string '300' (length=3)
      2 =>
        array
          0 => string '2' (length=1)
          1 => string 'iMac' (length=4)
          2 => string 'Desktop' (length=7)
          3 => string '529' (length=3)
      3 =>
        array
          0 => string '3' (length=1)
          1 => string 'MacBook' (length=7)
          2 => string 'Mobile' (length=6)
          3 => string '2000' (length=4)
      4 =>
        array
          0 => string '4' (length=1)
          1 => string 'iTouch' (length=6)
          2 => string 'Gadgets' (length=7)
          3 => string '157' (length=3)
      5 =>
        array
          0 => string '5' (length=1)
          1 => string 'Wii' (length=3)
          2 => string 'Gaming' (length=6)
          3 => string '1250' (length=4)

and the result with parse_header TRUE

    array
      0 =>
        array
          'Id' => string '1' (length=1)
          'Name' => string 'iPhone' (length=6)
          'Category' => string 'Mobile' (length=6)
          'Price' => string '300' (length=3)
      1 =>
        array
          'Id' => string '2' (length=1)
          'Name' => string 'iMac' (length=4)
          'Category' => string 'Desktop' (length=7)
          'Price' => string '529' (length=3)
      2 =>
        array
          'Id' => string '3' (length=1)
          'Name' => string 'MacBook' (length=7)
          'Category' => string 'Mobile' (length=6)
          'Price' => string '2000' (length=4)
      3 =>
        array
          'Id' => string '4' (length=1)
          'Name' => string 'iTouch' (length=6)
          'Category' => string 'Gadgets' (length=7)
          'Price' => string '157' (length=3)
      4 =>
        array
          'Id' => string '5' (length=1)
          'Name' => string 'Wii' (length=3)
          'Category' => string 'Gaming' (length=6)
          'Price' => string '1250' (length=4)

Download CodeIgniter CSV file parser Library (165).

Joomla! and SID in URI

On last project I’ve worked, I needed to pass the SID trough URI on entire website. The website was builded on Joomla! platform.

Joomla! is not offering natively anything for such thing and i had to find quickly a solution to fix this.

First solution, was to add these lines

$session =& JFactory::getSession();

$uri->setVar($session->getName(), $session->getId());

in includes/router.php, function build, before

return $uri;

Second solution, was fixing this with a plugin

	// no direct access
	defined( '_JEXEC' ) or die( 'Restricted access' );

	jimport( 'joomla.plugin.plugin' );

	class plgSystemSid extends JPlugin {

		function onAfterInitialise() {

			// Get application
			$application =& JFactory::getApplication();

			// Get router
			$router =& $application->getRouter();

			// Add the SID rule
			$router->attachBuildRule(array(&$this, 'addSidToUri'));
		}

		function addSidToUri(&$router, &$uri) {

			// Add SID to query
			$session =& JFactory::getSession();
			$uri->setVar($session->getName(), $session->getId());
		}

	}

Download Joomla! SID to URI (121) plugin.

Hello world!

Welcome to my blog.