Icon

Irimis'S Blog

NOT just another blog.

Codeigniter: MY_Controller (One controller to rule them all)

Download MY_Controller (215)

February 28, 2010

  1. Debugging with FirePHP (url)

February 05, 2010

  1. Constants in MySQL Database (url)

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)