Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- defined('BASEPATH') OR exit('No direct script access allowed');
- /**
- * MY_Model
- *
- * This base model attempts to use idiorm class instead of CodeIgniter
- * query builder.
- *
- * @see https://github.com/j4mie/idiorm (original)
- * @see https://github.com/bkader/idiorm (used for this)
- *
- * @package CodeIgniter
- * @category Core Extension
- * @author Kader Bouyakoub <bkader@mail.com>
- * @link https://github.com/bkader
- * @link https://twitter.com/KaderBouyakoub
- */
- class_exists('ORM', false) OR require APPPATH.'third_party/idiorm/idiorm.php';
- class MY_Model extends CI_Model
- {
- /**
- * holds the current model class name.
- * @var string
- */
- protected $_model = null;
- /**
- * holds the current table depending on the model class name.
- * @var string
- */
- protected $_table = null;
- /**
- * holds ORM class instance.
- * @var object
- */
- protected $_database = null;
- /**
- * table's primary key.
- * @var string
- */
- protected $_primary_key = 'id';
- /**
- * whether to turn ON soft deletes or not.
- * @var boolean
- */
- protected $_soft_delete = false;
- /**
- * data return type: array o object.
- * @var string
- */
- protected $_return_type = 'object';
- /**
- * if TRUE, use unix_timestamp.
- * @var boolean
- */
- protected $unix_timestamp = true;
- /**
- * MySQL datetime format.
- * @var string
- */
- protected $datetime_format = 'Y-m-d H:i:s';
- /**
- * column that holds date of creation.
- * @var string
- */
- protected $_created_at = 'created_at';
- /**
- * column that holds date of update.
- * @var string
- */
- protected $_updated_at = 'updated_at';
- /**
- * column that holds date of delete.
- * @var string
- */
- protected $_deleted_at = 'deleted_at';
- /**
- * if set to TRUE, data will not be passed to form validation.
- * @var boolean
- */
- protected $_skip_validation = false;
- /**
- * array of form validation rules.
- * @see https://codeigniter.com/user_guide/libraries/form_validation.html?highlight=form%20validation#setting-validation-rules
- * @var array
- */
- protected $_validation_rules = array();
- /**
- * Attributes that will be ignored and removed from insert or update.
- * @var array
- */
- protected $protected_attributes = array();
- /**
- * Observers.
- */
- protected $before_create = array();
- protected $after_create = array();
- protected $before_find = array();
- protected $after_find = array();
- protected $before_update = array();
- protected $after_update = array();
- protected $before_delete = array();
- protected $after_delete = array();
- public function __construct()
- {
- parent::__construct();
- $this->_set_model();
- $this->_set_table();
- $this->_set_database();
- array_unshift($this->before_create, 'protect_attributes', 'created_at');
- array_unshift($this->before_update, 'protect_attributes', 'updated_at');
- }
- // ------------------------------------------------------------------------
- public function __call($method, $params)
- {
- // No table set? Nothing to do.
- if (empty($this->_table))
- {
- show_error("Table name is not set for '{$this->_model}' class.");
- }
- // Add methods to observers.
- if (preg_match('/^before_([^)]+)$/', $method, $m))
- {
- if (isset($this->{$m[0]}) && is_array($this->{$m[0]}))
- {
- is_array($params[0]) && $params = $params[0];
- foreach ($params as $param)
- {
- array_push($this->{$m[0]}, $param);
- }
- }
- return $this;
- }
- // The method exists in this class? Call it.
- if (method_exists($this, $method))
- {
- return call_user_func_array(array($this, $method), $params);
- }
- // Retrieve by a given column name?
- if (preg_match('/^get_by_([^)]+)$/', $method, $m) && count($m) == 2)
- {
- $field = $m[1];
- $match = array_shift($params);
- if (strpos($field, '_or_'))
- {
- $field = explode('_or_', $field);
- }
- $result = false;
- if (is_array($field))
- {
- foreach ($field as $_field)
- {
- if ($found = $this->get_by($_field, $match, $params))
- {
- $result = $found;
- break;
- }
- }
- }
- else
- {
- $result = $this->get_by($field, $match, $params);
- }
- return $result;
- }
- // Update a row using update_by() method
- if (preg_match('/^update_by_([^)]+)$/', $method, $m) && count($m) == 2)
- {
- array_unshift($params, $m[1]);
- return call_user_func_array(array($this, 'update_by'), $params);
- }
- // Delete a row using delete_by() method
- if (preg_match('/^delete_by_([^)]+)$/', $method, $m) && count($m) == 2)
- {
- array_unshift($params, $m[1]);
- return call_user_func_array(array($this, 'delete_by'), $params);
- }
- // Remove records even if $soft_delete is set to true.
- if (strpos($method, 'remove') === 0)
- {
- $method = str_replace('remove', 'delete', $method);
- $this->_soft_delete = false;
- return call_user_func_array(array($this, $method), $params);
- }
- // The method exists in ORM object? Call it.
- if (method_exists(ORM::for_table($this->_table), $method))
- {
- return call_user_func_array(
- array(ORM::for_table($this->_table), $method),
- $params
- );
- }
- // No method found? Show error.
- show_error("Undefined method '{$this->_model}::{$method}()'.");
- }
- // ------------------------------------------------------------------------
- // FINDERS
- // ------------------------------------------------------------------------
- /**
- * Retrieves a single record by its primary value with optional select.
- */
- public function get()
- {
- $args = func_get_args();
- $primary_value = array_shift($args);
- if ( ! empty($args))
- {
- is_array($args[0]) && $args = $args[0];
- foreach ($args as $arg)
- {
- $query = $this->_database->select($arg);
- }
- }
- $result = $this->_database->find_one($primary_value);
- return $result ? $result->{'as_'.$this->_return_type}() : false;
- }
- /**
- * Retrieves a single record by $field=$match condition with option select.
- */
- public function get_by()
- {
- $args = func_get_args();
- if (empty($args))
- {
- return false;
- }
- $field = array_shift($args);
- $match = is_array($field) ? null : array_shift($args);
- // $query = ORM::for_table($this->_table);
- if ( ! empty($args))
- {
- is_array($args[0]) && $args = $args[0];
- foreach ($args as $arg)
- {
- $query = $this->_database->select($arg);
- }
- }
- $result = $this->_database->where($field, $match)->find_one();
- return $result ? $result->{'as_'.$this->_return_type}() : false;
- }
- /**
- * Retrieves multiple records by conditions with optional select.
- */
- public function get_many()
- {
- $args = func_get_args();
- if (empty($args))
- {
- return false;
- }
- $field = array_shift($args);
- $match = is_array($field) ? null : array_shift($args);
- $query = ORM::for_table($this->_table);
- if ( ! empty($args))
- {
- is_array($args[0]) && $args = $args[0];
- foreach ($args as $arg)
- {
- $query = $query->select($arg);
- }
- }
- if ($result = $query->find_many())
- {
- foreach ($result as &$row)
- {
- $row = $row->{'as_'.$this->_return_type}();
- }
- return $result;
- }
- return false;
- }
- // ------------------------------------------------------------------------
- // INSERT
- // ------------------------------------------------------------------------
- /**
- * Insert a new row into the table. $data should be an associative array
- * of data to be inserted. Returns newly created ID.
- */
- public function insert(array $data = array(), $validate = true)
- {
- if ($validate === true)
- {
- $data = $this->validate($data);
- }
- if ($data !== false)
- {
- $data = $this->trigger('before_create', $data);
- $row = $this->_database->create($data);
- if ($row->save())
- {
- $id = $row->id();
- $this->trigger('after_create', $id);
- return $id;
- }
- return false;
- }
- return false;
- }
- /**
- * Insert multiple rows into the table. Returns an array of multiple IDs.
- */
- public function insert_many(array $data = array(), $validate = true)
- {
- if (empty($data))
- {
- return false;
- }
- $ids = array();
- foreach ($data as $key => $row)
- {
- $ids[] = $this->insert($row, $validate, ($key = count($data) - 1));
- }
- return $ids;
- }
- // ------------------------------------------------------------------------
- // UPDATERS
- // ------------------------------------------------------------------------
- /**
- * Updated a single record based on the primary value.
- */
- public function update($primary_value, $data, $validate = true)
- {
- if ($validate === true)
- {
- $data = $this->validate($data);
- }
- if ($data !== false)
- {
- // We check the row exists before proceeding.
- $row = $this->_database->find_one($primary_value);
- if ($row)
- {
- $data = $this->trigger('before_update', $data);
- $row->set($data);
- $result = $row->save();
- $this->trigger('after_update', array($data, $result));
- return $result;
- }
- return false;
- }
- return false;
- }
- /**
- * Updated a single record based on WHERE conditions.
- */
- public function update_by()
- {
- $args = func_get_args();
- if (empty($args))
- {
- return false;
- }
- $data = array_pop($args);
- if ( ! is_array($data) OR empty($data) OR empty($args))
- {
- return false;
- }
- $data = $this->trigger('before_update', $data);
- if ($this->validate($data) !== false)
- {
- $field = array_shift($args);
- $match = is_array($field) ? null : array_shift($args);
- $update = ORM::for_table($this->_table)
- ->where($field, $match)
- ->find_one();
- if ( ! $update)
- {
- return false;
- }
- $update->set($data);
- $result = $update->save();
- $this->trigger('after_update', array($data, $result));
- return $result;
- }
- return false;
- }
- /**
- * Update many records, based on WHERE clause.
- */
- public function update_many()
- {
- $args = func_get_args();
- if (empty($args))
- {
- return false;
- }
- $data = array_pop($args);
- if ( ! is_array($data) OR empty($data) OR empty($args))
- {
- return false;
- }
- $data = $this->trigger('before_update', $data);
- if ($this->validate($data) !== false)
- {
- $field = array_shift($args);
- $match = is_array($field) ? null : array_shift($args);
- $update = ORM::for_table($this->_table)
- ->where($field, $match)
- ->find_many();
- if ( ! $update)
- {
- return false;
- }
- $result = true;
- foreach ($update as $row)
- {
- $row->set($data);
- $result = $row->save();
- }
- $this->trigger('after_update', array($data, $result));
- return $result;
- }
- return false;
- }
- // ------------------------------------------------------------------------
- // DELETERS
- // ------------------------------------------------------------------------
- /**
- * Delete a row from the table by the primary value
- */
- public function delete($primary_value)
- {
- $row = $this->_database->find_one($primary_value);
- if ( ! $row)
- {
- return false;
- }
- if ($this->_soft_delete === true)
- {
- // Update the row only if its not deleted.
- if ($row->{$this->_deleted_at} < 1)
- {
- $row->set($this->_deleted_at, $this->_get_timestamp());
- return $row->save();
- }
- return true;
- }
- return $row->delete();
- }
- /**
- * Delete a row from the database table by an arbitrary WHERE clause
- */
- public function delete_by()
- {
- $args = func_get_args();
- if (empty($args))
- {
- return false;
- }
- $field = array_shift($args);
- $match = is_array($field) ? null : array_shift($args);
- $row = $this->_database->where($field, $match)->find_one();
- if ( ! $row)
- {
- return false;
- }
- if ($this->_soft_delete === true)
- {
- // Update the row only if its not deleted.
- if ($row->{$this->_deleted_at} < 1)
- {
- $row->set($this->_deleted_at, $this->_get_timestamp());
- return $row->save();
- }
- return true;
- }
- return $row->delete();
- }
- /**
- * Delete many rows from the database table by multiple primary values
- */
- public function delete_many()
- {
- $args = func_get_args();
- if (empty($args))
- {
- return false;
- }
- $field = array_shift($args);
- $match = is_array($field) ? null : array_shift($args);
- $rows = $this->_database->where($field, $match)->find_many();
- if ( ! $rows)
- {
- return false;
- }
- if ($this->_soft_delete === true)
- {
- // To avoid time being updated, we store it.
- $deleted_at = $this->_get_timestamp();
- foreach ($rows as $row)
- {
- // Update the row only if it's not already deleted.
- if ($row->{$this->_deleted_at} < 1)
- {
- $row->set($this->_deleted_at, $deleted_at);
- $row->save();
- }
- }
- }
- else
- {
- foreach ($rows as $row)
- {
- $row->delete();
- }
- }
- return true;
- }
- // ------------------------------------------------------------------------
- // INTERNAL METHODS
- // ------------------------------------------------------------------------
- /**
- * Triggers and event and call its observer.
- */
- public function trigger($event, $data = array())
- {
- if (isset($this->{$event}) && is_array($this->{$event}))
- {
- foreach ($this->$event as $method)
- {
- $data = $this->{$method}($data);
- }
- }
- return $data;
- }
- /**
- * Run form validation on the passed data.
- *
- * @param array $data
- * @return mixed array after validation or false.
- */
- public function validate($data = array())
- {
- if ($this->_skip_validation)
- {
- return $data;
- }
- if ( ! empty($this->_validation_rules))
- {
- foreach ($data as $key => $val)
- {
- $_POST[$key] = $val;
- }
- if ( ! class_exists('CI_Form_validation', false))
- {
- $this->load->library('form_validation');
- }
- if (is_array($this->_validation_rules))
- {
- $this->form_validation->set_rules($this->_validation_rules);
- if ($this->form_validation->run() == true)
- {
- return $data;
- }
- else
- {
- return false;
- }
- }
- else
- {
- if ($this->form_validation->run($this->_validation_rules) == true)
- {
- return $data;
- }
- else
- {
- return false;
- }
- }
- }
- return $data;
- }
- /**
- * Fetches the current model class name.
- */
- private function _set_model()
- {
- if (empty($this->_model))
- {
- $this->_model = ucfirst(get_class($this));
- }
- }
- /**
- * Guesses the current table name from model class name.
- */
- private function _set_table()
- {
- if ($this->_table == null)
- {
- function_exists('plural') OR $this->load->helper('inflector');
- $this->_table = plural(preg_replace('/(_m|_model)?$/', '', strtolower($this->_model)));
- }
- }
- /**
- * Estalishes the connection to the database.
- */
- private function _set_database()
- {
- if (file_exists($db_config = APPPATH.'config/'.ENVIRONMENT.'/database.php'))
- {
- include($db_config);
- }
- elseif (file_exists($db_config = APPPATH.'config/database.php'))
- {
- include($db_config);
- }
- $db_group = isset($active_group) ? $active_group : 'default';
- $config = $db[$db_group];
- $params = array(
- 'dsn' => isset($config['dsn']) ? rawurldecode($config['dsn']) : '',
- 'host' => isset($config['hostname']) ? $config['hostname'] : 'localhost',
- 'port' => isset($config['port']) ? $config['port'] : '3306',
- 'user' => isset($config['username']) ? $config['username'] : '',
- 'pass' => isset($config['password']) ? $config['password'] : '',
- 'dbname' => isset($config['database']) ? $config['database'] : '',
- 'pref' => isset($config['dbprefix']) ? $config['dbprefix'] : '',
- 'driver' => isset($config['dbdriver']) ? $config['dbdriver'] : 'mysqli',
- );
- $params['driver'] = ($params['driver'] == 'sqltie') ? 'sqltie' : 'mysql';
- // echo '<pre>', print_r($params, true);
- // exit;
- if (empty($params['dsn']))
- {
- if (empty($params['host'])
- OR empty($params['user'])
- OR empty($params['dbname']))
- {
- show_error('No database connection settings were found in the database config file.');
- }
- else
- {
- if ($params['driver'] == 'mysql')
- {
- $params['dsn'] = "{$params['driver']}:host={$params['host']};";
- if ( ! empty($params['post']))
- {
- $params['dsn'] .= "port={$param['port']};";
- }
- $params['dsn'] .= "dbname={$params['dbname']};";
- }
- }
- }
- ORM::configure($params['dsn'], null, $db_group);
- ORM::configure('username', $params['user']);
- ORM::configure('password', $params['pass']);
- $this->_database = ORM::for_table($this->_table);
- }
- // ------------------------------------------------------------------------
- // OBSERVERS
- // ------------------------------------------------------------------------
- /**
- * Protects attributes by removing them from $data.
- */
- protected function protect_attributes($data)
- {
- foreach ($this->protected_attributes as $attr)
- {
- if (is_object($data))
- {
- unset($data->{$attr});
- }
- else
- {
- unset($data[$attr]);
- }
- }
- return $data;
- }
- /**
- * Add date of creation to $data before insert.
- */
- protected function created_at($data)
- {
- if (is_object($data) && empty($data->{$this->_created_at}))
- {
- $data->{$this->_created_at} = $this->_get_timestamp();
- }
- elseif (is_array($data) && empty($data[$this->_created_at]))
- {
- $data[$this->_created_at] = $this->_get_timestamp();
- }
- return $data;
- }
- /**
- * Add date of update to $data before update.
- */
- protected function updated_at($data)
- {
- if (is_object($data) && empty($data->{$this->_updated_at}))
- {
- $data->{$this->_updated_at} = $this->_get_timestamp();
- }
- elseif (is_array($data) && empty($data[$this->_updated_at]))
- {
- $data[$this->_updated_at] = $this->_get_timestamp();
- }
- return $data;
- }
- /**
- * Set time() depending on the property $this->unix_timestamp
- */
- public function _get_timestamp()
- {
- if ($this->unix_timestamp === true)
- {
- return time();
- }
- return date($this->datetime_format);
- }
- }
- /* End of file MY_Model.php */
- /* Location: ./application/core/MY_Model.php */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement