CRUD за CodeIgniter

Автор: tu6o
С този урок ще покажа един лесен и удобен модел на работа с популярния framework CI(CodeIgniter) 2.1.0.
Препоръчвам преди това да прочете основните теми в документацията на CI.
В директорията models/ ще създам нов скрипт на име crudder.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
//
// crudder_model is written by Tihomir Yanev
// http://www.ti6o-bg.com/
// last update: 5th june 2012
//
// ------------------------- BEGIN ------------------------------------- //
class Crudder extends CI_Model
{
//
// the constructor
//
// check whether database driver is loaded
//
public function __construct()
{
parent::__construct();
if (!class_exists('CI_DB'))
{
die("Unable to connect to Database!");
}
}
//
// checkTable method
// params:
//
// string $table (required) --> name of the table
//
// return boolean $validTable
//
private function checkTable(& $table)
{
$table = htmlspecialchars($table);
if (empty($table) or !$this->db->table_exists($table))
{
$this->showErrors("Could not find this table");
}
}
//
// createData method
// params:
//
// string $table (required) --> name of the table
// array $fields (required) --> fields to fill in
//
// return bool --> whether it was successful
//
public function createData($table, $fields)
{
$this->checkTable($table);
if (!is_array($fields))
{
$this->showErrors("Empty fields!");
}
return $this->db->insert($table, $fields);
}
//
// deleteData method
// params:
//
// string $table (required) --> name of the table
// array $where (required) --> where to delete
//
// return int $affectedRows --> number of deleted rows
//
public function deleteData($table, $where)
{
$this->checkTable($table);
if (empty($where))
{
$this->showErrors("Empty criteria!");
}
if (!is_array($where))
{
$this->showErrors("Second parameter must be an array!");
}
$query = $this->db->delete($table, $where);
$affectedRows = $this->db->affected_rows();
$this->db->query("OPTIMIZE table `" . $table . "` ");
return $affectedRows;
}
//
// readData method
// params:
//
// string $table (required) --> name of the table
// array $options (optional) --> our options
//
// return array/NULL $data
//
public function readData($table, $options = array())
{
$this->checkTable($table);
// selecting fields from table
if (isset($options['select']))
{
// allowed types: string
$this->db->select($options['select']);
}
// produces: FROM $table
$this->db->from($table);
// adding join clause
// array('table' => 'comments', 'on' => 'comments.id = blogs.id', 'type' => 'left');
if (isset($options['join']) and is_array($options['join']))
{
// allowed types: array
$this->db->join($options['join']['table'], $options['join']['on'], $options['join']['type']);
}
// adding where clauses
// example: array('name !=' => $name, 'id <' => $id, 'date >' => $date);
if (isset($options['where']))
{
// allowed types: array
$where = (array) $options['where'];
$this->db->where($where);
}
// adding like clause
// example: $array = array('title' => $match, 'page1' => $match, 'page2' => $match);
if (isset($options['like']))
{
// allowed types: array
$this->db->like((array)$options['like']);
}
// adding group by clause
// example: $this->db->group_by("title, date");
if (isset($options['groupBy']))
{
// allowed types: string, array
$this->db->group_by($options['groupBy']);
}
// adding order by clause
// example: $this->db->order_by('title desc, name asc');
if (isset($options['orderBy']))
{
// allowed types: array
$this->db->order_by($options['orderBy']);
}
// adding limit option
// example: $this->db->limit(10);
if (isset($options['limit']))
{
if (isset($options['offset']))
{
$this->db->limit($options['limit'], $options['offset']);
}
else
{
$this->db->limit($options['limit']);
}
}
// perform the query
$query = $this->db->get();
if ($query->num_rows())
{
return $query->result_array();
}
return NULL;
}
//
// readDataSql method
// params:
// string $sql
//
// return array/NULL data
//
public function readDataSql($sql = NULL)
{
if (empty($sql))
{
$this->showErrors("Empty query!");
}
$query = $this->db->query($sql);
if ($query->num_rows())
{
return $query->result_array();
}
return NULL;
}
//
// setErrorFlag method
// params:
// bool $flag
//
// return
//
public function setErrorFlag($flag = FALSE)
{
$this->showErrorsFlag = $flag;
}
//
// showErrors method
// params:
//
// string $message (optional) --> message to output
//
// return exit() with/without message
//
private function showErrors($message)
{
if ($this->showErrorsFlag)
{
die($message);
}
exit();
}
//
// updateData method
// params:
//
// string $table (required) --> name of the table
// array $fields (required) --> fields to update
// array $where (required) --> criteria(s)
//
// return int --> number of affected rows
//
public function updateData($table, $fields, $where)
{
$this->checkTable($table);
if (!is_array($fields))
{
$this->showErrors("Empty fields!");
}
$this->db->where((array)$where);
$this->db->update($table, $fields);
return $this->db->affected_rows();
}
private $showErrorsFlag;
}
// ------------------------- END --------------------------------------- //Нищо особено дотук, сега ще покажа как примерна употреба. За целта ще създадем един контролер:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Test extends CI_Controller
{
private $admin_controller = "administrator";
public function __construct()
{
parent::__construct();
$this->load->model('crudder'); // зареждам модела
$this->crudder->setErrorFlag(true); // нека извеждаме грешките на екрана
}
public function index()
{
$someData = $this->crudder->readData('accounts', array
(
'select' => 'userName, id',
'where' => array
(
'status' => 0,
'id >' => 3
),
'limit' => 12
));
// тази заявка избира 12 записа от таблица 'accounts', където status = 0 и id > 3
if(!count($someData)) // реално count($someData) е еквивалент на mysql_num_rows()
return;
foreach($someData as $item) : ?>
<p>Id: <?=$item['id'];?>; UserName: <?=$item['userName'];?></p>
<?php endforeach;
}
}Предимствата на модела са използването на Active Record Class, който се грижи за филтрирането на вашите входни данни. Разбира се, за писане на по-сложни SQL заявки, използващи вложени SELECT-и или UNION, създадох метода readDataSql($sql), където $sql е низът, съдържащ валидна SQL заявка.


