Add namespace.
This commit is contained in:
63
Model/Db.php
Normal file
63
Model/Db.php
Normal file
@ -0,0 +1,63 @@
|
||||
<?php namespace Majestic\Model;
|
||||
/**
|
||||
* @copyright NetMonsters <team@netmonsters.ru>
|
||||
* @link http://netmonsters.ru
|
||||
* @package Majestic
|
||||
* @subpackage db
|
||||
* @since 2010-02-16
|
||||
*/
|
||||
|
||||
class Db
|
||||
{
|
||||
|
||||
const FETCH_ASSOC = 2;
|
||||
const FETCH_NUM = 3;
|
||||
const FETCH_BOTH = 4;
|
||||
const FETCH_OBJ = 5;
|
||||
|
||||
/**
|
||||
* Databases connections
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
static protected $connections = array();
|
||||
|
||||
/**
|
||||
* Connect to database
|
||||
*
|
||||
* @param string $name Database name. If not set 'default' will be used.
|
||||
* @param array $config Configuration array.
|
||||
*
|
||||
* @return DbDriver
|
||||
* @throws \Majestic\Exception\InitializationException
|
||||
*/
|
||||
static public function connect($name = 'default', $config = null)
|
||||
{
|
||||
if (!isset(self::$connections[$name])) {
|
||||
if (!$config) {
|
||||
if (!is_object(\Majestic\Config::get(__CLASS__))) {
|
||||
throw new \Majestic\Exception\InitializationException('Trying to get property of non-object');
|
||||
}
|
||||
$config = \Majestic\Config::get(__CLASS__)->$name;
|
||||
}
|
||||
|
||||
if (!is_array($config)) {
|
||||
throw new \Majestic\Exception\InitializationException('Connection parameters must be an array');
|
||||
}
|
||||
|
||||
$driver = '\Majestic\Model\MySQLiDriver';
|
||||
if (isset($config['driver'])) {
|
||||
$driver = $config['driver'];
|
||||
unset($config['driver']);
|
||||
}
|
||||
|
||||
$connection = new $driver($config);
|
||||
|
||||
if (!$connection instanceof DbDriver) {
|
||||
throw new \Majestic\Exception\InitializationException('Database driver must extends DbDriver');
|
||||
}
|
||||
self::$connections[$name] = $connection;
|
||||
}
|
||||
return self::$connections[$name];
|
||||
}
|
||||
}
|
84
Model/DbDriver.php
Normal file
84
Model/DbDriver.php
Normal file
@ -0,0 +1,84 @@
|
||||
<?php namespace Majestic\Model;
|
||||
/**
|
||||
* @copyright NetMonsters <team@netmonsters.ru>
|
||||
* @link http://netmonsters.ru
|
||||
* @package Majestic
|
||||
* @subpackage db
|
||||
* @since 2010-02-16
|
||||
*/
|
||||
|
||||
abstract class DbDriver
|
||||
{
|
||||
|
||||
/**
|
||||
* Database connection
|
||||
*
|
||||
* @var object
|
||||
*/
|
||||
protected $connection = null;
|
||||
|
||||
/**
|
||||
* Configuration data
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $config = array();
|
||||
|
||||
|
||||
public function __construct($config)
|
||||
{
|
||||
$this->checkConfig($config);
|
||||
$this->config = $config;
|
||||
}
|
||||
|
||||
protected function checkConfig($config)
|
||||
{
|
||||
$required = array('database', 'username', 'password', 'hostname');
|
||||
foreach ($required as $option) {
|
||||
if (!isset($config[$option])) {
|
||||
throw new \GeneralException('Configuration must have a "' . $option . '".');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function getConnection()
|
||||
{
|
||||
$this->connect();
|
||||
return $this->connection;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $request
|
||||
* @param mixed $params
|
||||
* @return DbStatement
|
||||
*/
|
||||
public function query($request, $params = array())
|
||||
{
|
||||
$this->connect();
|
||||
if (!is_array($params)) {
|
||||
$params = array($params);
|
||||
}
|
||||
$stmt = $this->prepare($request);
|
||||
$stmt->execute($params);
|
||||
return $stmt;
|
||||
}
|
||||
|
||||
|
||||
/* Abstract methods */
|
||||
|
||||
abstract public function insert($table, $data);
|
||||
|
||||
abstract public function update($table, $data, $condition);
|
||||
|
||||
abstract public function delete($table, $condition);
|
||||
|
||||
abstract public function prepare($request);
|
||||
|
||||
abstract public function getInsertId($table = null, $key = null);
|
||||
|
||||
abstract public function isConnected();
|
||||
|
||||
abstract public function disconnect();
|
||||
|
||||
abstract protected function connect();
|
||||
}
|
28
Model/DbExpr.php
Normal file
28
Model/DbExpr.php
Normal file
@ -0,0 +1,28 @@
|
||||
<?php namespace Majestic\Model;
|
||||
/**
|
||||
* @copyright NetMonsters <team@netmonsters.ru>
|
||||
* @link http://netmonsters.ru
|
||||
* @package Majestic
|
||||
* @subpackage db
|
||||
* @since 2010-02-19
|
||||
*/
|
||||
|
||||
class DbExpr
|
||||
{
|
||||
|
||||
protected $expression;
|
||||
|
||||
/**
|
||||
* @param string $expression
|
||||
* @return DbExpr
|
||||
*/
|
||||
public function __construct($expression)
|
||||
{
|
||||
$this->expression = (string) $expression;
|
||||
}
|
||||
|
||||
public function __toString()
|
||||
{
|
||||
return $this->expression;
|
||||
}
|
||||
}
|
115
Model/DbStatement.php
Normal file
115
Model/DbStatement.php
Normal file
@ -0,0 +1,115 @@
|
||||
<?php namespace Majestic\Model;
|
||||
/**
|
||||
* @copyright NetMonsters <team@netmonsters.ru>
|
||||
* @link http://netmonsters.ru
|
||||
* @package Majestic
|
||||
* @subpackage db
|
||||
* @since 2010-02-19
|
||||
*/
|
||||
|
||||
abstract class DbStatement
|
||||
{
|
||||
|
||||
/**
|
||||
* @var DbDriver
|
||||
*/
|
||||
protected $driver;
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
protected $request;
|
||||
|
||||
protected $params = array();
|
||||
|
||||
protected $result;
|
||||
|
||||
public function __construct($driver, $request)
|
||||
{
|
||||
$this->driver = $driver;
|
||||
$this->request = $request;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $params
|
||||
* @return bool
|
||||
*/
|
||||
public function execute($params = null)
|
||||
{
|
||||
if (is_array($params)) {
|
||||
foreach ($params as $param => &$value) {
|
||||
$this->bindParam($param, $value);
|
||||
}
|
||||
}
|
||||
return $this->driverExecute($this->assemble());
|
||||
}
|
||||
|
||||
public function __destruct()
|
||||
{
|
||||
$this->close();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $style
|
||||
* @return array
|
||||
*/
|
||||
public function fetchAll($style = Db::FETCH_OBJ)
|
||||
{
|
||||
$data = array();
|
||||
while ($row = $this->fetch($style)) {
|
||||
$data[] = $row;
|
||||
}
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $field
|
||||
* @return array Value of queried field for all matching rows
|
||||
*/
|
||||
public function fetchColumn($field)
|
||||
{
|
||||
$data = array();
|
||||
while ($row = $this->fetch(Db::FETCH_ASSOC)) {
|
||||
$data[] = $row[$field];
|
||||
}
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $field
|
||||
* @return mixed Value of queried filed for first matching row
|
||||
*/
|
||||
public function fetchField($field)
|
||||
{
|
||||
$row = $this->fetch(Db::FETCH_ASSOC);
|
||||
if (isset($row[$field])) {
|
||||
return $row[$field];
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Abstract methods */
|
||||
|
||||
abstract public function bindParam($param, &$value);
|
||||
|
||||
abstract protected function assemble();
|
||||
|
||||
abstract public function fetch($style = Db::FETCH_OBJ);
|
||||
|
||||
abstract public function fetchObject($class = 'stdClass');
|
||||
|
||||
abstract public function close();
|
||||
|
||||
/**
|
||||
* @return int
|
||||
*/
|
||||
abstract public function affectedRows();
|
||||
|
||||
abstract public function numRows();
|
||||
|
||||
/**
|
||||
* @param mixed $request
|
||||
* @return bool
|
||||
*/
|
||||
abstract protected function driverExecute($request);
|
||||
}
|
172
Model/Model.php
Normal file
172
Model/Model.php
Normal file
@ -0,0 +1,172 @@
|
||||
<?php namespace Majestic\Model;
|
||||
|
||||
/**
|
||||
* Класс модели данных
|
||||
*
|
||||
* @copyright NetMonsters <team@netmonsters.ru>
|
||||
* @link http://netmonsters.ru
|
||||
* @package Majestic
|
||||
* @subpackage Model
|
||||
* @since 2010-02-16
|
||||
*/
|
||||
|
||||
abstract class Model
|
||||
{
|
||||
|
||||
/**
|
||||
* DbDriver instance
|
||||
*
|
||||
* @var DbDriver
|
||||
*/
|
||||
protected $db;
|
||||
|
||||
/**
|
||||
* Cache instance
|
||||
*
|
||||
* @var \Cache
|
||||
*/
|
||||
protected $cache;
|
||||
|
||||
/**
|
||||
* Custom expiration time for keys
|
||||
*
|
||||
* @var mixed
|
||||
*/
|
||||
protected $cache_keys = array();
|
||||
|
||||
/**
|
||||
* Caches to clean.
|
||||
*
|
||||
* @var mixed
|
||||
*/
|
||||
protected $caches_clean = array();
|
||||
|
||||
protected $table;
|
||||
|
||||
protected $key = 'id';
|
||||
|
||||
|
||||
public function __construct($connection = 'default')
|
||||
{
|
||||
$this->db = Db::connect($connection);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int
|
||||
*/
|
||||
public function getInsertId()
|
||||
{
|
||||
return $this->db->getInsertId($this->table(), $this->key);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $data
|
||||
* @return int Id of inserted row
|
||||
*/
|
||||
public function insert($data)
|
||||
{
|
||||
$affected = $this->db->insert($this->table(), $data);
|
||||
return ($this->getInsertId()) ? $this->getInsertId() : $affected;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $data
|
||||
* @param mixed $where
|
||||
* @return int Number of affected rows
|
||||
*/
|
||||
public function update($data, $where)
|
||||
{
|
||||
return $this->db->update($this->table(), $data, $where);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
protected function table()
|
||||
{
|
||||
if (!$this->table) {
|
||||
$this->table = substr(strtolower(get_class($this)), 0, -5/*strlen('Model')*/);
|
||||
}
|
||||
return $this->table;
|
||||
}
|
||||
|
||||
|
||||
/* Cache workaround */
|
||||
|
||||
/**
|
||||
* @return \Cache
|
||||
*/
|
||||
public function getCache()
|
||||
{
|
||||
if (!$this->cache) {
|
||||
$this->cache = \Cacher::get(\Majestic\Config::get(__CLASS__, 'MemcacheCache'));
|
||||
}
|
||||
return $this->cache;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $name
|
||||
* @param array $params
|
||||
* @return \CacheKey
|
||||
*/
|
||||
protected function cacheKey($name, $params = array())
|
||||
{
|
||||
$expire = (isset($this->cache_keys[$name])) ? ($this->cache_keys[$name] * 60) : 0;
|
||||
return new \CacheKey($this->getCache(), $name, $params, $expire);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \CacheKey $cache
|
||||
*/
|
||||
protected function addCleanCache($cache)
|
||||
{
|
||||
$this->caches_clean[] = $cache;
|
||||
}
|
||||
|
||||
protected function cleanCaches()
|
||||
{
|
||||
// cleaning caches
|
||||
foreach ($this->caches_clean as $cache) {
|
||||
$cache->del();
|
||||
}
|
||||
$this->caches_clean = array();
|
||||
}
|
||||
|
||||
/**
|
||||
* Abstract methods
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param int $id
|
||||
* @return object
|
||||
*/
|
||||
abstract public function get($id);
|
||||
|
||||
/**
|
||||
* @param int $id Int id
|
||||
* @return int Number of affected rows
|
||||
*/
|
||||
abstract public function delete($id);
|
||||
|
||||
/**
|
||||
* @param string $data Request
|
||||
* @param array $params Request parameters
|
||||
* @param string $field Requested field name
|
||||
* @param \CacheKey $cache_key Key for caching in
|
||||
*/
|
||||
abstract protected function fetchField($data, $params = array(), $field, $cache_key = null);
|
||||
|
||||
/**
|
||||
* @param string $data Request
|
||||
* @param array $params Request parameters
|
||||
* @param \CacheKey $cache_key Key for caching in
|
||||
*/
|
||||
abstract protected function fetch($data, $params = array(), $cache_key = null);
|
||||
|
||||
/**
|
||||
* @param string $data
|
||||
* @param array $params
|
||||
* @param \CacheKey $cache_key
|
||||
*/
|
||||
abstract protected function fetchAll($data, $params = array(), $cache_key = null);
|
||||
}
|
365
Model/MongoDbCommand.php
Normal file
365
Model/MongoDbCommand.php
Normal file
@ -0,0 +1,365 @@
|
||||
<?php
|
||||
/**
|
||||
* @copyright NetMonsters <team@netmonsters.ru>
|
||||
* @link http://netmonsters.ru
|
||||
* @package Majestic
|
||||
* @subpackage db
|
||||
* @since 2011-11-15
|
||||
*/
|
||||
|
||||
class MongoCommandBuilder
|
||||
{
|
||||
|
||||
const FIND = 'Find';
|
||||
|
||||
const COUNT = 'Count';
|
||||
|
||||
const INSERT = 'Insert';
|
||||
|
||||
const UPDATE = 'Update';
|
||||
|
||||
const REMOVE = 'Remove';
|
||||
|
||||
const COMMAND = 'Command';
|
||||
|
||||
|
||||
/**
|
||||
* @param string $type
|
||||
* @param MongoCollection $collection
|
||||
* @return MongoDbCommand
|
||||
*/
|
||||
static public function factory($type, $collection = null)
|
||||
{
|
||||
$class = ucfirst($type) . 'MongoCommand';
|
||||
$command = new $class();
|
||||
$command->setCollection($collection);
|
||||
return $command;
|
||||
}
|
||||
}
|
||||
|
||||
abstract class MongoDbCommand
|
||||
{
|
||||
|
||||
/**
|
||||
* @var MongoCollection
|
||||
*/
|
||||
protected $collection;
|
||||
|
||||
/**
|
||||
* Execute Mongo command/query
|
||||
*
|
||||
* @return mixed
|
||||
* @throws \Majestic\Exception\GeneralException
|
||||
*/
|
||||
public function execute()
|
||||
{
|
||||
if ($this->checkParams()) {
|
||||
return $this->concreteExecute();
|
||||
} else {
|
||||
throw new \Majestic\Exception\GeneralException(get_called_class() . ' error. Bind all required params first.');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $name Parameter name
|
||||
* @param mixed $value Parameter value
|
||||
* @return MongoDbCommand
|
||||
*/
|
||||
public function bindParam($name, $value)
|
||||
{
|
||||
if (property_exists($this, $name)) {
|
||||
$this->$name = $value;
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param MongoCollection $collection Mongo collection
|
||||
* @return MongoDbCommand
|
||||
*/
|
||||
public function setCollection($collection)
|
||||
{
|
||||
$this->collection = $collection;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert query parameters array to string
|
||||
*
|
||||
* @param array $array
|
||||
* @return string
|
||||
*/
|
||||
protected function arrayToString($array)
|
||||
{
|
||||
$string = '[';
|
||||
if(!empty($array)) {
|
||||
$string .= PHP_EOL;
|
||||
}
|
||||
foreach($array as $key => $value) {
|
||||
$string .= "\t" . $key . ' = ' . $value . PHP_EOL;
|
||||
}
|
||||
$string .= ']' . PHP_EOL;
|
||||
return $string;
|
||||
}
|
||||
|
||||
abstract protected function concreteExecute();
|
||||
|
||||
abstract protected function checkParams();
|
||||
}
|
||||
|
||||
class FindMongoCommand extends MongoDbCommand
|
||||
{
|
||||
protected $condition = array();
|
||||
|
||||
protected $fields = array();
|
||||
|
||||
protected $multiple = true;
|
||||
|
||||
protected function concreteExecute()
|
||||
{
|
||||
if ($this->multiple) {
|
||||
return $this->collection->find($this->condition, $this->fields);
|
||||
} else {
|
||||
return $this->collection->findOne($this->condition, $this->fields);
|
||||
}
|
||||
}
|
||||
|
||||
protected function checkParams()
|
||||
{
|
||||
if (isset($this->collection) && isset($this->condition) && isset($this->fields)) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public function __toString()
|
||||
{
|
||||
if ($this->checkParams()) {
|
||||
$result = PHP_EOL . 'Collection: ' . trim($this->collection, "\n") . PHP_EOL;
|
||||
$result .= 'Condition: ' . $this->arrayToString($this->condition);
|
||||
$result .= 'Type: FIND' . PHP_EOL;
|
||||
$result .= 'Fields: ' . $this->arrayToString($this->fields);
|
||||
$mult = $this->multiple ? 'TRUE' : 'FALSE';
|
||||
$result .= 'Multiple fields: ' . $mult . PHP_EOL;
|
||||
return $result;
|
||||
} else {
|
||||
return 'Command properties not set';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class CountMongoCommand extends MongoDbCommand
|
||||
{
|
||||
protected $condition = array();
|
||||
|
||||
protected $limit = 0;
|
||||
|
||||
protected $skip = 0;
|
||||
|
||||
protected $multiple = true;
|
||||
|
||||
protected function concreteExecute()
|
||||
{
|
||||
return $this->collection->count($this->condition, $this->limit, $this->skip);
|
||||
}
|
||||
|
||||
protected function checkParams()
|
||||
{
|
||||
if (isset($this->collection) && isset($this->condition) && isset($this->limit) && isset($this->skip)) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public function __toString()
|
||||
{
|
||||
if ($this->checkParams()) {
|
||||
$result = PHP_EOL . 'Collection: ' . trim($this->collection, "\n") . PHP_EOL;
|
||||
$result .= 'Type: COUNT' . PHP_EOL;
|
||||
$result .= 'Condition: ' . $this->arrayToString($this->condition);
|
||||
$result .= 'Limit: ' . $this->limit . PHP_EOL;
|
||||
$result .= 'Skip: ' . $this->skip . PHP_EOL;
|
||||
return $result;
|
||||
} else {
|
||||
return 'Command properties not set';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class InsertMongoCommand extends MongoDbCommand
|
||||
{
|
||||
protected $data;
|
||||
|
||||
protected $safe = true;
|
||||
|
||||
protected $insertId = false;
|
||||
|
||||
protected $multiple = false;
|
||||
|
||||
protected function concreteExecute()
|
||||
{
|
||||
$result = null;
|
||||
if (!$this->multiple) {
|
||||
$result = $this->collection->insert($this->data, array('safe' => $this->safe));
|
||||
$this->insertId = $this->data['_id'];
|
||||
} else {
|
||||
if (count($this->data)) {
|
||||
$result = $this->collection->batchInsert($this->data, array('safe' => $this->safe));
|
||||
}
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
protected function checkParams()
|
||||
{
|
||||
if (isset($this->collection) && isset($this->data) && isset($this->safe)) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public function getInsertId()
|
||||
{
|
||||
return $this->insertId;
|
||||
}
|
||||
|
||||
public function __toString()
|
||||
{
|
||||
if ($this->checkParams()) {
|
||||
$result = PHP_EOL . 'Collection: ' . trim($this->collection, "\n") . PHP_EOL;
|
||||
$result .= 'Type: INSERT' . PHP_EOL;
|
||||
$result .= 'Data: ' . $this->arrayToString($this->data);
|
||||
$mult = $this->multiple ? 'TRUE' : 'FALSE';
|
||||
$result .= 'Bulk insert: ' . $mult . PHP_EOL;
|
||||
$safe = $this->safe ? 'TRUE' : 'FALSE';
|
||||
$result .= 'Safe operation: ' . $safe . PHP_EOL;
|
||||
return $result;
|
||||
} else {
|
||||
return 'Command properties not set';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class UpdateMongoCommand extends MongoDbCommand
|
||||
{
|
||||
protected $condition;
|
||||
|
||||
protected $data;
|
||||
|
||||
protected $multiple = true;
|
||||
|
||||
protected $upsert = false;
|
||||
|
||||
protected $safe = true;
|
||||
|
||||
protected function concreteExecute()
|
||||
{
|
||||
return $this->collection->update($this->condition, $this->data,
|
||||
array('multiple' => $this->multiple, 'upsert' => $this->upsert, 'safe' => $this->safe));
|
||||
}
|
||||
|
||||
protected function checkParams()
|
||||
{
|
||||
if (isset($this->collection) && isset($this->condition) && isset($this->data) &&
|
||||
isset($this->upsert) && isset($this->safe)
|
||||
) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public function __toString()
|
||||
{
|
||||
if ($this->checkParams()) {
|
||||
$result = PHP_EOL . 'Collection: ' . trim($this->collection, "\n") . PHP_EOL;
|
||||
$result .= 'Type: UPDATE' . PHP_EOL;
|
||||
$result .= 'Condition: ' . $this->arrayToString($this->condition);
|
||||
$result .= 'Data: ' . $this->arrayToString($this->data);
|
||||
$mult = $this->multiple ? 'TRUE' : 'FALSE';
|
||||
$result .= 'Multiple fields: ' . $mult . PHP_EOL;
|
||||
$upsert = $this->upsert ? 'TRUE' : 'FALSE';
|
||||
$result .= 'Upsert: ' . $upsert . PHP_EOL;
|
||||
$safe = $this->safe ? 'TRUE' : 'FALSE';
|
||||
$result .= 'Safe operation: ' . $safe . PHP_EOL;
|
||||
return $result;
|
||||
} else {
|
||||
return 'Command properties not set';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class RemoveMongoCommand extends MongoDbCommand
|
||||
{
|
||||
protected $condition;
|
||||
|
||||
protected $safe = true;
|
||||
|
||||
protected function concreteExecute()
|
||||
{
|
||||
return $this->collection->remove($this->condition, array('safe' => $this->safe));
|
||||
}
|
||||
|
||||
protected function checkParams()
|
||||
{
|
||||
if (isset($this->collection) && isset($this->condition) && isset($this->safe)) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public function __toString()
|
||||
{
|
||||
if ($this->checkParams()) {
|
||||
$result = PHP_EOL . 'Collection: ' . trim($this->collection, "\n") . PHP_EOL;
|
||||
$result .= 'Type: REMOVE' . PHP_EOL;
|
||||
$result .= 'Condition: ' . $this->arrayToString($this->condition);
|
||||
$safe = $this->safe ? 'TRUE' : 'FALSE';
|
||||
$result .= 'Safe operation: ' . $safe . PHP_EOL;
|
||||
return $result;
|
||||
} else {
|
||||
return 'Command properties not set';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class CommandMongoCommand extends MongoDbCommand
|
||||
{
|
||||
protected $command;
|
||||
|
||||
protected function concreteExecute()
|
||||
{
|
||||
$db = $this->collection->db;
|
||||
if ($db instanceof MongoDB) {
|
||||
return $db->command($this->command);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
protected function checkParams()
|
||||
{
|
||||
if (isset($this->collection) && isset($this->command)) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public function __toString()
|
||||
{
|
||||
if ($this->checkParams()) {
|
||||
$result = PHP_EOL . 'Collection: ' . trim($this->collection, "\n") . PHP_EOL;
|
||||
$result .= 'Type: COMMAND' . PHP_EOL;
|
||||
$result .= 'Command: ' . $this->arrayToString($this->command);
|
||||
return $result;
|
||||
} else {
|
||||
return 'Command properties not set';
|
||||
}
|
||||
}
|
||||
}
|
170
Model/MongoDriver.php
Normal file
170
Model/MongoDriver.php
Normal file
@ -0,0 +1,170 @@
|
||||
<?php
|
||||
/**
|
||||
* @copyright NetMonsters <team@netmonsters.ru>
|
||||
* @link http://netmonsters.ru
|
||||
* @package Majestic
|
||||
* @subpackage db
|
||||
* @since 2011-11-10
|
||||
*/
|
||||
|
||||
/**
|
||||
* @property Mongo $connection
|
||||
*/
|
||||
class MongoDriver extends NoSqlDbDriver
|
||||
{
|
||||
protected $last_insert_id = 0;
|
||||
|
||||
protected $db_name = 'admin';
|
||||
|
||||
protected $db = null;
|
||||
|
||||
protected function getCollection($name)
|
||||
{
|
||||
if (!$this->connection) {
|
||||
$this->connect();
|
||||
}
|
||||
return $this->connection->selectCollection($this->db, $name);
|
||||
}
|
||||
|
||||
public function count($collection, $query = array(), $limit = 0, $skip = 0)
|
||||
{
|
||||
$command = MongoCommandBuilder::factory(MongoCommandBuilder::COUNT, $this->getCollection($collection));
|
||||
$params = array(
|
||||
'condition' => $query,
|
||||
'limit' => $limit,
|
||||
'skip' => $skip
|
||||
);
|
||||
|
||||
return $this->query($command, $params)->affectedRows();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $collection Mongo collection name to search in
|
||||
* @param array $condition Search conditions
|
||||
* @param array $fields Fields to return in result set
|
||||
* @return MongoStatement
|
||||
*/
|
||||
public function find($collection, $condition = array(), $fields = array())
|
||||
{
|
||||
$command = MongoCommandBuilder::factory(MongoCommandBuilder::FIND, $this->getCollection($collection));
|
||||
$params = array(
|
||||
'condition' => $condition,
|
||||
'fields' => $fields
|
||||
);
|
||||
|
||||
return $this->query($command, $params);
|
||||
}
|
||||
|
||||
public function findAndModify($collection, $query, $update, $sort = array(), $field = array(), $upsert = false, $new = false, $remove = false)
|
||||
{
|
||||
$command = MongoCommandBuilder::factory(MongoCommandBuilder::COMMAND, $this->getCollection($collection));
|
||||
$cmd = array(
|
||||
'findAndModify' => $collection,
|
||||
'query' => $query,
|
||||
'update' => $update,
|
||||
'sort' => $sort,
|
||||
'fields' => $field,
|
||||
'new' => $new,
|
||||
'upsert' => $upsert,
|
||||
'remove' => $remove
|
||||
);
|
||||
$params = array('command' => $cmd);
|
||||
return $this->query($command, $params);
|
||||
}
|
||||
|
||||
public function command($collection, $cmd)
|
||||
{
|
||||
$command = MongoCommandBuilder::factory(MongoCommandBuilder::COMMAND, $this->getCollection($collection));
|
||||
$params = array('command' => $cmd);
|
||||
return $this->query($command, $params);
|
||||
}
|
||||
|
||||
public function insert($collection, $data, $multiple = false, $safe = true)
|
||||
{
|
||||
$command = MongoCommandBuilder::factory(MongoCommandBuilder::INSERT, $this->getCollection($collection));
|
||||
$params = array(
|
||||
'data' => $data,
|
||||
'safe' => $safe,
|
||||
'multiple' => $multiple
|
||||
);
|
||||
$result = $this->query($command, $params);
|
||||
$this->last_insert_id = $result->getInsertId();
|
||||
return $result->affectedRows();
|
||||
}
|
||||
|
||||
public function update($collection, $data, $condition = array(), $multiple = true, $upsert = false, $safe = true)
|
||||
{
|
||||
$command = MongoCommandBuilder::factory(MongoCommandBuilder::UPDATE, $this->getCollection($collection));
|
||||
$params = array(
|
||||
'data' => $data,
|
||||
'condition' => $condition,
|
||||
'multiple' => $multiple,
|
||||
'upsert' => $upsert,
|
||||
'safe' => $safe
|
||||
);
|
||||
|
||||
return $this->query($command, $params)->affectedRows();
|
||||
}
|
||||
|
||||
public function delete($collection, $condition = array(), $safe = true)
|
||||
{
|
||||
$command = MongoCommandBuilder::factory(MongoCommandBuilder::REMOVE, $this->getCollection($collection));
|
||||
$params = array(
|
||||
'condition' => $condition,
|
||||
'safe' => $safe
|
||||
);
|
||||
|
||||
return $this->query($command, $params)->affectedRows();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param mixed $request
|
||||
* @return MongoStatement
|
||||
*/
|
||||
public function prepare($request)
|
||||
{
|
||||
return new MongoStatement($this, $request);
|
||||
}
|
||||
|
||||
public function getInsertId($table = null, $key = null)
|
||||
{
|
||||
return $this->last_insert_id;
|
||||
}
|
||||
|
||||
public function isConnected()
|
||||
{
|
||||
if (!is_null($this->connection)) {
|
||||
return $this->connection->connected;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public function disconnect()
|
||||
{
|
||||
if ($this->isConnected()) {
|
||||
$this->connection->close();
|
||||
}
|
||||
$this->connection = null;
|
||||
}
|
||||
|
||||
protected function connect()
|
||||
{
|
||||
if ($this->connection) {
|
||||
return;
|
||||
}
|
||||
|
||||
$host = $this->config['hostname'];
|
||||
$port = isset($this->config['port']) ? ':' . (string) $this->config['port'] : '';
|
||||
|
||||
$this->config = array(
|
||||
'username' => $this->config['username'],
|
||||
'password' => $this->config['password'],
|
||||
'db' => $this->config['database']
|
||||
);
|
||||
|
||||
$this->connection = new Mongo('mongodb://' . $host . $port, $this->config);
|
||||
$this->db = $this->connection->selectDB($this->config['db']);
|
||||
}
|
||||
}
|
220
Model/MongoModel.php
Normal file
220
Model/MongoModel.php
Normal file
@ -0,0 +1,220 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Класс модели данных
|
||||
*
|
||||
* @copyright NetMonsters <team@netmonsters.ru>
|
||||
* @link http://netmonsters.ru
|
||||
* @package Majestic
|
||||
* @subpackage Model
|
||||
* @since 2011-11-15
|
||||
*/
|
||||
|
||||
/**
|
||||
* @property MongoDriver $db
|
||||
*/
|
||||
abstract class MongoModel extends Model
|
||||
{
|
||||
|
||||
/**
|
||||
* @var string Mongo id field to use as key
|
||||
*/
|
||||
protected $key = '_id';
|
||||
|
||||
/**
|
||||
* @var bool Is Mongo key field uses original MongoId
|
||||
*/
|
||||
protected $useMongoId = true;
|
||||
|
||||
public function __construct($connection = 'default')
|
||||
{
|
||||
parent::__construct($connection);
|
||||
}
|
||||
|
||||
protected function count($query = array(), $limit = 0, $skip = 0)
|
||||
{
|
||||
return $this->db->count($this->table(), $query, $limit, $skip);
|
||||
}
|
||||
|
||||
public function get($id)
|
||||
{
|
||||
if ($this->useMongoId) {
|
||||
if (!$id instanceof MongoId) {
|
||||
$id = new MongoId($id);
|
||||
}
|
||||
}
|
||||
return $this->fetch(array($this->key => $id));
|
||||
}
|
||||
|
||||
public function batchInsert($data)
|
||||
{
|
||||
return $this->db->insert($this->table(), $data, true);
|
||||
}
|
||||
|
||||
public function update($data, $where)
|
||||
{
|
||||
if ($this->useMongoId) {
|
||||
if (!$where instanceof MongoId) {
|
||||
$where = new MongoId($where);
|
||||
}
|
||||
}
|
||||
return $this->db->update($this->table(), $data, array($this->key => $where));
|
||||
}
|
||||
|
||||
public function delete($id)
|
||||
{
|
||||
if ($this->useMongoId) {
|
||||
if (!$id instanceof MongoId) {
|
||||
$id = new MongoId($id);
|
||||
}
|
||||
}
|
||||
return $this->db->delete($this->table(), array($this->key => $id));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $data Request
|
||||
* @param array $params Request parameters
|
||||
* @param string $field Requested field name
|
||||
* @param CacheKey $cache_key Key for caching in
|
||||
* @return mixed
|
||||
*/
|
||||
protected function fetchField($data, $params = array(), $field, $cache_key = null)
|
||||
{
|
||||
if (!$cache_key || !$result = $cache_key->get()) {
|
||||
$result = $this->db
|
||||
->find($this->table(), $data, array($field => 1))
|
||||
->limit($this->getLimit($params))
|
||||
->skip($this->getSkip($params))
|
||||
->order($this->getOrder($params))
|
||||
->fetchField($field);
|
||||
if ($cache_key) {
|
||||
$cache_key->set($result);
|
||||
}
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $data Request
|
||||
* @param array $params Request parameters
|
||||
* @param CacheKey $cache_key Key for caching in
|
||||
* @return mixed
|
||||
*/
|
||||
protected function fetch($data, $params = array(), $cache_key = null)
|
||||
{
|
||||
if (!$cache_key || !$result = $cache_key->get()) {
|
||||
$result = $this->db
|
||||
->find($this->table(), $data, $this->getFields($params))
|
||||
->limit(1)
|
||||
->skip($this->getSkip($params))
|
||||
->order($this->getOrder($params))
|
||||
->fetch();
|
||||
if ($cache_key) {
|
||||
$cache_key->set($result);
|
||||
}
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $data
|
||||
* @param array $params
|
||||
* @param CacheKey $cache_key
|
||||
* @return array
|
||||
*/
|
||||
protected function fetchAll($data, $params = array(), $cache_key = null)
|
||||
{
|
||||
if (!$cache_key || !$result = $cache_key->get()) {
|
||||
$result = $this->db
|
||||
->find($this->table(), $data, $this->getFields($params))
|
||||
->limit($this->getLimit($params))
|
||||
->skip($this->getSkip($params))
|
||||
->order($this->getOrder($params))
|
||||
->fetchAll();
|
||||
if ($cache_key) {
|
||||
$cache_key->set($result);
|
||||
}
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $params Parameters for find query
|
||||
* @return int Query result limits rule
|
||||
* */
|
||||
private function getLimit($params = array())
|
||||
{
|
||||
return isset($params['limit']) ? (int) $params['limit'] : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $params Parameters for find query
|
||||
* @return int Query result skip rule
|
||||
* */
|
||||
private function getSkip($params = array())
|
||||
{
|
||||
return isset($params['skip']) ? (int) $params['skip'] : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $params Parameters for find query
|
||||
* @return array Query result sort rules
|
||||
* @throws \Majestic\Exception\GeneralException
|
||||
* */
|
||||
private function getOrder($params = array())
|
||||
{
|
||||
$order = array();
|
||||
if (isset($params['order'])) {
|
||||
if (is_string($params['order'])) {
|
||||
$order = array($params['order'] => 1);
|
||||
} elseif (is_array($params['order'])) {
|
||||
$order = $params['order'];
|
||||
} else {
|
||||
throw new \Majestic\Exception\GeneralException('Wrong order parameter given to query.');
|
||||
}
|
||||
}
|
||||
return $order;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $params Parameters for find query
|
||||
* @return array Query result sort rules
|
||||
* @throws \Majestic\Exception\GeneralException
|
||||
* */
|
||||
private function getFields($params)
|
||||
{
|
||||
$fields = array();
|
||||
if (isset($params['fields'])) {
|
||||
if (is_string($params['fields'])) {
|
||||
$fields = array($params['fields'] => 1);
|
||||
} elseif (is_array($params['fields'])) {
|
||||
if (array_keys($params['fields']) === range(0, count($params['fields']) - 1)) {
|
||||
foreach ($params['fields'] as $filed) {
|
||||
$fields[$filed] = 1;
|
||||
}
|
||||
} else {
|
||||
$fields = $params['fields'];
|
||||
}
|
||||
} else {
|
||||
throw new \Majestic\Exception\GeneralException('Wrong fields parameter given to query.');
|
||||
}
|
||||
}
|
||||
return $fields;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the additional condition if it is set
|
||||
*
|
||||
* @param array $query Initial query
|
||||
* @param string $filed Field name to set
|
||||
* @param mixed $value Field value to set
|
||||
* @return MongoModel Current model object
|
||||
*/
|
||||
protected function addCondition(&$query, $filed, $value)
|
||||
{
|
||||
if(!is_null($value) && $value !== false) {
|
||||
$query[$filed] = $value;
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
}
|
189
Model/MongoStatement.php
Normal file
189
Model/MongoStatement.php
Normal file
@ -0,0 +1,189 @@
|
||||
<?php
|
||||
/**
|
||||
* @copyright NetMonsters <team@netmonsters.ru>
|
||||
* @link http://netmonsters.ru
|
||||
* @package Majestic
|
||||
* @subpackage db
|
||||
* @since 2011-11-15
|
||||
*/
|
||||
|
||||
/**
|
||||
* @property MongoDriver $driver
|
||||
* @property MongoCursor $result
|
||||
*/
|
||||
class MongoStatement extends DbStatement
|
||||
{
|
||||
|
||||
protected $insertId = false;
|
||||
|
||||
public function count()
|
||||
{
|
||||
if ($this->result instanceof MongoCursor) {
|
||||
return $this->result->count();
|
||||
} else {
|
||||
throw new GeneralException('MongoStatement error. Impossible count result of opened cursor.');
|
||||
}
|
||||
}
|
||||
|
||||
public function order($sort = array())
|
||||
{
|
||||
if ($this->result instanceof MongoCursor) {
|
||||
$this->result->sort($sort);
|
||||
return $this;
|
||||
} else {
|
||||
throw new GeneralException('MongoStatement error. Impossible order results of opened cursor.');
|
||||
}
|
||||
}
|
||||
|
||||
public function skip($skip = 0)
|
||||
{
|
||||
if ($this->result instanceof MongoCursor) {
|
||||
$this->result->skip($skip);
|
||||
return $this;
|
||||
} else {
|
||||
throw new GeneralException('MongoStatement error. Impossible skip results of opened cursor.');
|
||||
}
|
||||
}
|
||||
|
||||
public function limit($limit = 0)
|
||||
{
|
||||
if ($this->result instanceof MongoCursor) {
|
||||
$this->result->limit($limit);
|
||||
return $this;
|
||||
} else {
|
||||
throw new GeneralException('MongoStatement error. Impossible limit results of opened cursor.');
|
||||
}
|
||||
}
|
||||
|
||||
public function fetch($style = Db::FETCH_OBJ)
|
||||
{
|
||||
if (!$this->result) {
|
||||
return false;
|
||||
}
|
||||
if (is_array($this->result) && isset($this->result['retval'])) {
|
||||
return $this->result['retval'];
|
||||
}
|
||||
|
||||
switch ($style) {
|
||||
case Db::FETCH_OBJ:
|
||||
$row = $this->fetchObject();
|
||||
break;
|
||||
case Db::FETCH_ASSOC:
|
||||
if ($this->result instanceof MongoCursor) {
|
||||
$row = $this->result->getNext();
|
||||
} else {
|
||||
$row = $this->result;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
throw new GeneralException('Invalid fetch mode "' . $style . '" specified');
|
||||
}
|
||||
return $row;
|
||||
}
|
||||
|
||||
public function fetchObject($class = 'stdClass')
|
||||
{
|
||||
if ($this->result instanceof MongoCursor) {
|
||||
$row = $this->result->getNext();
|
||||
} else {
|
||||
$row = $this->result;
|
||||
}
|
||||
if (is_array($row) && isset($row['_id'])) {
|
||||
$row = new ArrayObject($row, ArrayObject::ARRAY_AS_PROPS);
|
||||
} else {
|
||||
$row = false;
|
||||
}
|
||||
return $row;
|
||||
}
|
||||
|
||||
public function close()
|
||||
{
|
||||
$this->result = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int
|
||||
*/
|
||||
public function affectedRows()
|
||||
{
|
||||
if (is_array($this->result)) {
|
||||
if (isset($this->result['ok']) && $this->result['ok'] == 1) {
|
||||
if (isset($this->result['n'])) {
|
||||
return $this->result['n'];
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
} elseif (is_int($this->result) || $this->result instanceof MongoId) {
|
||||
return $this->result;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public function numRows()
|
||||
{
|
||||
if ($this->result instanceof MongoCursor) {
|
||||
return $this->result->count();
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param MongoDbCommand $request
|
||||
* @throws GeneralException
|
||||
* @return bool
|
||||
*/
|
||||
protected function driverExecute($request)
|
||||
{
|
||||
$this->result = false;
|
||||
$mongo = $this->driver->getConnection();
|
||||
if ($mongo instanceof Mongo) {
|
||||
if (Config::get('PROFILER_DETAILS')) {
|
||||
$profiler = Profiler::getInstance()->profilerCommand('Mongo', $request);
|
||||
$result = $request->execute();
|
||||
$profiler->end();
|
||||
} else {
|
||||
$result = $request->execute();
|
||||
}
|
||||
if ($result === false) {
|
||||
throw new GeneralException('MongoDB request error.');
|
||||
}
|
||||
if ($result instanceof MongoCursor || is_array($result)) {
|
||||
$this->result = $result;
|
||||
if (is_array($result) && isset($result['value'])) {
|
||||
$this->result = $result['value'];
|
||||
}
|
||||
if (is_array($result) && isset($result['values'])) {
|
||||
$this->result = $result['values'];
|
||||
}
|
||||
if (is_array($result) && isset($result['upserted'])) {
|
||||
$this->result = $result['n'] > 1 ? $result['n'] : $result['upserted'];
|
||||
}
|
||||
} elseif (is_int($result)) {
|
||||
$this->result = $result;
|
||||
}
|
||||
if ($request instanceof InsertMongoCommand) {
|
||||
$this->insertId = $request->getInsertId();
|
||||
}
|
||||
return true;
|
||||
} else {
|
||||
throw new GeneralException('No connection to MongoDB server.');
|
||||
}
|
||||
}
|
||||
|
||||
public function bindParam($param, &$value)
|
||||
{
|
||||
$this->request->bindParam($param, $value);
|
||||
}
|
||||
|
||||
protected function assemble()
|
||||
{
|
||||
return $this->request;
|
||||
}
|
||||
|
||||
public function getInsertId()
|
||||
{
|
||||
return $this->insertId;
|
||||
}
|
||||
}
|
123
Model/MySQLiDriver.php
Normal file
123
Model/MySQLiDriver.php
Normal file
@ -0,0 +1,123 @@
|
||||
<?php namespace Majestic\Model;
|
||||
/**
|
||||
* @copyright NetMonsters <team@netmonsters.ru>
|
||||
* @link http://netmonsters.ru
|
||||
* @package Majestic
|
||||
* @subpackage db
|
||||
* @since 2010-02-17
|
||||
*/
|
||||
|
||||
/**
|
||||
* @property \MySQLi $connection
|
||||
*/
|
||||
class MySQLiDriver extends SqlDbDriver
|
||||
{
|
||||
|
||||
public function insert($table, $bind, $on_duplicate = array())
|
||||
{
|
||||
$columns = array();
|
||||
foreach ($bind as $col => $val) {
|
||||
$columns[] = $this->quoteIdentifier($col);
|
||||
}
|
||||
$values = array_values($bind);
|
||||
|
||||
if ($on_duplicate) {
|
||||
$update = array();
|
||||
foreach ($on_duplicate as $col => $val) {
|
||||
$update[] = $this->quoteIdentifier($col) . '=' . $this->quote($val);
|
||||
}
|
||||
$on_duplicate = ' ON DUPLICATE KEY UPDATE ' . implode(', ', $update);
|
||||
}
|
||||
|
||||
$sql = 'INSERT INTO ' . $this->quoteIdentifier($table)
|
||||
. ' (' . implode(', ', $columns) . ') VALUES (' . $this->quote($values) . ')'
|
||||
. (($on_duplicate) ? $on_duplicate : '');
|
||||
return $this->query($sql)->affectedRows();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $sql
|
||||
* @return MySQLiStatement
|
||||
*/
|
||||
public function prepare($sql)
|
||||
{
|
||||
return new MySQLiStatement($this, $sql);
|
||||
}
|
||||
|
||||
public function getInsertId($table = null, $key = null)
|
||||
{
|
||||
return $this->connection->insert_id;
|
||||
}
|
||||
|
||||
public function isConnected()
|
||||
{
|
||||
return ($this->connection instanceof \MySQLi);
|
||||
}
|
||||
|
||||
public function disconnect()
|
||||
{
|
||||
if ($this->isConnected()) {
|
||||
$this->connection->close();
|
||||
}
|
||||
$this->connection = null;
|
||||
}
|
||||
|
||||
protected function connect()
|
||||
{
|
||||
if ($this->connection) {
|
||||
return;
|
||||
}
|
||||
|
||||
$port = isset($this->config['port']) ? (int) $this->config['port'] : null;
|
||||
$this->connection = mysqli_init();
|
||||
@mysqli_real_connect($this->connection,
|
||||
$this->config['hostname'],
|
||||
$this->config['username'],
|
||||
$this->config['password'],
|
||||
$this->config['database'],
|
||||
$port);
|
||||
// Connection errors check
|
||||
if (mysqli_connect_error()) {
|
||||
throw new GeneralException(mysqli_connect_error(), mysqli_connect_errno());
|
||||
}
|
||||
|
||||
$charset = (!empty($this->config['charset'])) ? $this->config['charset'] : 'utf8';
|
||||
$this->connection->set_charset($charset);
|
||||
}
|
||||
|
||||
protected function driverQuote($value)
|
||||
{
|
||||
if (is_int($value) || is_float($value)) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
if (is_bool($value)) {
|
||||
return (int) $value;
|
||||
}
|
||||
|
||||
if ($value === null) {
|
||||
return 'NULL';
|
||||
}
|
||||
|
||||
$this->connect();
|
||||
return '\'' . $this->connection->real_escape_string($value) . '\'';
|
||||
}
|
||||
|
||||
protected function driverBeginTransaction()
|
||||
{
|
||||
$this->connect();
|
||||
$this->connection->autocommit(false);
|
||||
}
|
||||
|
||||
protected function driverCommitTransaction()
|
||||
{
|
||||
$this->connection->commit();
|
||||
$this->connection->autocommit(true);
|
||||
}
|
||||
|
||||
protected function driverRollbackTransaction()
|
||||
{
|
||||
$this->connection->rollback();
|
||||
$this->connection->autocommit(true);
|
||||
}
|
||||
}
|
180
Model/MySQLiStatement.php
Normal file
180
Model/MySQLiStatement.php
Normal file
@ -0,0 +1,180 @@
|
||||
<?php namespace Majestic\Model;
|
||||
/**
|
||||
* @copyright NetMonsters <team@netmonsters.ru>
|
||||
* @link http://netmonsters.ru
|
||||
* @package Majestic
|
||||
* @subpackage db
|
||||
* @since 2010-02-19
|
||||
*/
|
||||
|
||||
/**
|
||||
* @property MySQLiDriver $driver
|
||||
* @property \MySQLi_Result $result
|
||||
*/
|
||||
class MySQLiStatement extends DbStatement
|
||||
{
|
||||
|
||||
protected $map = null;
|
||||
|
||||
public function bindParam($param, &$value)
|
||||
{
|
||||
if ($this->map === null) {
|
||||
$this->mapPlaceholders();
|
||||
}
|
||||
if (count($this->map) > 0) {
|
||||
if (!is_string($param) && !is_int($param)) {
|
||||
throw new \Majestic\Exception\GeneralException('Placeholder must be an integer or string');
|
||||
}
|
||||
if (is_object($value) && ! ($value instanceof DbExpr)) {
|
||||
throw new \Majestic\Exception\GeneralException('Objects excepts DbExpr not allowed.');
|
||||
}
|
||||
if (isset($this->map[$param])) {
|
||||
$this->params[$param] = &$value;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
protected function mapPlaceholders()
|
||||
{
|
||||
$matches = array();
|
||||
if(preg_match_all('/(\?|:[A-z][A-z0-9_]*+)/u', $this->request, $matches, PREG_OFFSET_CAPTURE)) {
|
||||
$noname = 0;
|
||||
foreach ($matches[0] as $id=>$match) {
|
||||
$match[2] = $matches[1][$id][0];
|
||||
$name = ($match[2][0] === ':') ? ltrim($match[2], ':') : $noname++;
|
||||
$this->map[$name]['placeholder'] = $match[0];
|
||||
$this->map[$name]['offset'][] = $match[1];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected function assemble()
|
||||
{
|
||||
if (empty($this->map)) {
|
||||
return $this->request;
|
||||
}
|
||||
|
||||
$query = $this->request;
|
||||
$placeholders = array();
|
||||
foreach($this->map as $name => $place) {
|
||||
$value = $this->driver->quote($this->params[$name]);
|
||||
foreach ($place['offset'] as $offset) {
|
||||
$placeholders[$offset] = array('placeholder' => $place['placeholder'], 'value' => $value);
|
||||
}
|
||||
}
|
||||
|
||||
ksort($placeholders);
|
||||
|
||||
$increment = 0;
|
||||
foreach($placeholders as $current_offset => $placeholder) {
|
||||
$offset = $current_offset + $increment;
|
||||
$length = mb_strlen($placeholder['placeholder']);
|
||||
$query = mb_substr($query, 0, $offset) . $placeholder['value'] . mb_substr($query, $offset + $length);
|
||||
$increment = (($increment - $length) + mb_strlen($placeholder['value']));
|
||||
}
|
||||
return $query;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches single row
|
||||
*
|
||||
* @param mixed $style
|
||||
* @return mixed
|
||||
* @throws \Majestic\Exception\GeneralException
|
||||
*/
|
||||
public function fetch($style = Db::FETCH_OBJ)
|
||||
{
|
||||
if (!$this->result) {
|
||||
return false;
|
||||
}
|
||||
|
||||
switch ($style) {
|
||||
case Db::FETCH_OBJ:
|
||||
$row = $this->result->fetch_object();
|
||||
break;
|
||||
case Db::FETCH_NUM:
|
||||
$row = $this->result->fetch_array(MYSQLI_NUM);
|
||||
break;
|
||||
case Db::FETCH_ASSOC:
|
||||
$row = $this->result->fetch_assoc();
|
||||
break;
|
||||
case Db::FETCH_BOTH:
|
||||
$row = $this->result->fetch_array(MYSQLI_BOTH);
|
||||
break;
|
||||
default:
|
||||
throw new \Majestic\Exception\GeneralException('Invalid fetch mode "' . $style . '" specified');
|
||||
}
|
||||
return $row;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $class
|
||||
* @return object
|
||||
*/
|
||||
public function fetchObject($class = 'stdClass')
|
||||
{
|
||||
return $this->result->fetch_object($class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function fetchPairs()
|
||||
{
|
||||
$data = array();
|
||||
while ($row = $this->fetch(Db::FETCH_NUM)) {
|
||||
$data[$row[0]] = $row[1];
|
||||
}
|
||||
return $data;
|
||||
}
|
||||
|
||||
public function close()
|
||||
{
|
||||
if ($this->result !== null) {
|
||||
$this->result->close();
|
||||
$this->result = null;
|
||||
}
|
||||
}
|
||||
|
||||
public function affectedRows()
|
||||
{
|
||||
return $this->driver->getConnection()->affected_rows;
|
||||
}
|
||||
|
||||
public function numRows()
|
||||
{
|
||||
if ($this->result) {
|
||||
return $this->result->num_rows;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public function getMysqliResult()
|
||||
{
|
||||
return $this->result;
|
||||
}
|
||||
|
||||
protected function driverExecute($request)
|
||||
{
|
||||
/**
|
||||
* @var \MySQLi
|
||||
*/
|
||||
$mysqli = $this->driver->getConnection();
|
||||
if (\Majestic\Config::get('PROFILER_DETAILS')) {
|
||||
$profiler = \Majestic\Util\Profiler\Profiler::getInstance()->profilerCommand('MySQL', $request);
|
||||
$result = $mysqli->query($request);
|
||||
$profiler->end();
|
||||
} else {
|
||||
$result = $mysqli->query($request);
|
||||
}
|
||||
if ($result === false) {
|
||||
$message = $mysqli->error . "\nQuery: \"" . $request . '"';
|
||||
throw new \Majestic\Exception\GeneralException($message, $mysqli->errno);
|
||||
}
|
||||
if ($result instanceof \MySQLi_Result) {
|
||||
$this->result = $result;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
14
Model/NoSqlDbDriver.php
Normal file
14
Model/NoSqlDbDriver.php
Normal file
@ -0,0 +1,14 @@
|
||||
<?php namespace Majestic\Model;
|
||||
/**
|
||||
* @copyright NetMonsters <team@netmonsters.ru>
|
||||
* @link http://netmonsters.ru
|
||||
* @package Majestic
|
||||
* @subpackage db
|
||||
* @since 2011-11-11
|
||||
*/
|
||||
|
||||
abstract class NoSqlDbDriver extends DbDriver
|
||||
{
|
||||
|
||||
abstract function find($collection, $condition = array(), $fields = array());
|
||||
}
|
263
Model/SqlCriteria.php
Normal file
263
Model/SqlCriteria.php
Normal file
@ -0,0 +1,263 @@
|
||||
<?php namespace Majestic\Model;
|
||||
|
||||
class SqlCriteria
|
||||
{
|
||||
const JOIN_TYPE_DEFAULT = 100;
|
||||
const JOIN_TYPE_LEFT = 101;
|
||||
const JOIN_TYPE_RIGHT = 102;
|
||||
const JOIN_TYPE_INNER = 103;
|
||||
const JOIN_TYPE_OUTER = 104;
|
||||
|
||||
private static $join_reserved_keyword = array(
|
||||
self::JOIN_TYPE_DEFAULT => 'JOIN',
|
||||
self::JOIN_TYPE_LEFT => 'LEFT JOIN',
|
||||
self::JOIN_TYPE_RIGHT => 'RIGHT JOIN',
|
||||
self::JOIN_TYPE_INNER => 'INNER JOIN',
|
||||
self::JOIN_TYPE_OUTER => 'OUTER JOIN',
|
||||
);
|
||||
|
||||
private $select = array();
|
||||
|
||||
private $distinct = '';
|
||||
|
||||
private $where = array();
|
||||
|
||||
private $group_by = array();
|
||||
|
||||
private $order = array('sort' => array(), 'order' => array());
|
||||
|
||||
private $limit = '';
|
||||
|
||||
/**
|
||||
* @var SqlModel
|
||||
*/
|
||||
private $model;
|
||||
|
||||
private $sql_expression;
|
||||
|
||||
private $sql_expression_params = array();
|
||||
|
||||
private $sql_join_expressions = array();
|
||||
|
||||
private $join_table_placeholder = array();
|
||||
|
||||
/**
|
||||
* @param $model SqlModel
|
||||
* @param $sql_expression string|null Sql expression with SELECT and FROM operators. If fetched, then SqlCriteria::select(), SqlCriteria::distinct() disabled for use.
|
||||
* @param $sql_expression_params array additional params to be replaced in sql expression
|
||||
*/
|
||||
public function __construct($model, $sql_expression = null, $sql_expression_params = array())
|
||||
{
|
||||
$this->model = $model;
|
||||
$this->sql_expression = $sql_expression;
|
||||
$this->sql_expression_params = $sql_expression_params;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return SqlResultProvider
|
||||
*/
|
||||
public function find()
|
||||
{
|
||||
$this->defineJoinExpressions();
|
||||
return $this->model->find($this->select, $this->distinct, $this->where, $this->order, $this->limit, null, $this->group_by, $this->sql_expression, $this->sql_expression_params);
|
||||
}
|
||||
|
||||
private function defineJoinExpressions()
|
||||
{
|
||||
if ($this->sql_join_expressions) {
|
||||
if (!$this->sql_expression) {
|
||||
$select = $this->model->getDb()->selectExpr($this->select, $this->distinct);
|
||||
$this->sql_expression = 'SELECT ' . $select . ' FROM :table';
|
||||
}
|
||||
$this->sql_expression .= ' ' . implode(' ', $this->sql_join_expressions);
|
||||
}
|
||||
}
|
||||
|
||||
public function delete()
|
||||
{
|
||||
return $this->model->find('', '', $this->where, null, null, null, null, 'DELETE FROM :table', $this->sql_expression_params)->affectedRows();
|
||||
}
|
||||
|
||||
public function count()
|
||||
{
|
||||
if ($this->sql_expression && strpos($this->sql_expression, 'COUNT(*) as count')) {
|
||||
;
|
||||
} else {
|
||||
$this->sql_expression = 'SELECT COUNT(*) as count FROM :table';
|
||||
}
|
||||
$this->defineJoinExpressions();
|
||||
return $this->model->find(array(), '', $this->where, null, null, null, null, $this->sql_expression, $this->sql_expression_params)->fetchField('count');
|
||||
}
|
||||
|
||||
private function defineJoinTablePlaceholder($table_name)
|
||||
{
|
||||
if (!isset($this->join_table_placeholder[$table_name])) {
|
||||
$this->join_table_placeholder[$table_name] = ':table' . (count($this->join_table_placeholder) + 1);
|
||||
}
|
||||
}
|
||||
|
||||
public function getTablePh($table_name)
|
||||
{
|
||||
$this->defineJoinTablePlaceholder($table_name);
|
||||
return $this->join_table_placeholder[$table_name];
|
||||
}
|
||||
|
||||
public function join($join_table_name, $join_field_name, $donor_table_name = null, $donor_field_name = null, $join_type = self::JOIN_TYPE_DEFAULT)
|
||||
{
|
||||
$donor_field_name = $donor_field_name ? : $join_field_name;
|
||||
$donor_table_placeholder = $donor_table_name ? $this->getTablePh($donor_table_name) : ':table';
|
||||
$join_table_placeholder = $this->getTablePh($join_table_name);
|
||||
$this->sql_join_expressions[] = self::$join_reserved_keyword[$join_type]
|
||||
. ' ' . $join_table_placeholder
|
||||
. ' ON ' . $donor_table_placeholder . '.' . $donor_field_name . '='
|
||||
. ' ' . $join_table_placeholder . '.' . $join_field_name;
|
||||
if ($donor_table_name) {
|
||||
$this->sql_expression_params[substr($donor_table_placeholder, 1)] = new DbExpr($this->model->identify($donor_table_name));
|
||||
}
|
||||
$this->sql_expression_params[substr($join_table_placeholder, 1)] = new DbExpr($this->model->identify($join_table_name));
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $cond string|array Condition with "?" placeholder @ex 'field=?' or 'field=1' or array('field=?' => 1', 'field=1')
|
||||
* @param $value string|array|DbExpr|null Value. Array transformed to DbExpr(implode(',' Array)) All elements in the array mast be integer
|
||||
* @return SqlCriteria
|
||||
* @desc Allow multiple calls
|
||||
*/
|
||||
public function where($cond, $value = null)
|
||||
{
|
||||
if (is_null($value)) {
|
||||
if (is_array($cond)) {
|
||||
$this->where = $this->where + $cond;
|
||||
} else {
|
||||
$this->where[] = $cond;
|
||||
}
|
||||
} else {
|
||||
$this->where[$cond] = $value;
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function whereJoin($join_table_name, $cond, $value)
|
||||
{
|
||||
$join_table_placeholder = $this->getTablePh($join_table_name);
|
||||
if (is_array($cond)) {
|
||||
$cond_replace = array();
|
||||
foreach ($cond as $key => $value) {
|
||||
$cond_replace[$this->getCondWithTablePlaceholderIfNeed($join_table_placeholder, $key)] = $value;
|
||||
}
|
||||
} else {
|
||||
$cond = $this->getCondWithTablePlaceholderIfNeed($join_table_placeholder, $cond);
|
||||
}
|
||||
return $this->where($cond, $value);
|
||||
}
|
||||
|
||||
private function getCondWithTablePlaceholderIfNeed($table_placeholder, $cond)
|
||||
{
|
||||
if (!strstr('.', $cond)) {
|
||||
$cond = $table_placeholder . '.' . $cond;
|
||||
}
|
||||
return $cond;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $field string
|
||||
* @param $value array
|
||||
* @return SqlCriteria
|
||||
*/
|
||||
public function whereIn($field, $value)
|
||||
{
|
||||
return $this->where($field . ' in ?', $value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $field string
|
||||
* @param $value array
|
||||
* @return SqlCriteria
|
||||
*/
|
||||
public function whereNotIn($field, $value)
|
||||
{
|
||||
return $this->where($field . ' not in ?', $value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $field string
|
||||
* @param $value array
|
||||
* @return SqlCriteria
|
||||
* @deprecated
|
||||
*/
|
||||
public function whereNot($field, $value)
|
||||
{
|
||||
return $this->whereNotIn($field, $value);
|
||||
}
|
||||
|
||||
public function groupBy($fields)
|
||||
{
|
||||
if (is_array($fields)) {
|
||||
$this->group_by = $this->group_by + $fields;
|
||||
} else {
|
||||
$this->group_by[] = $fields;
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $field string Field @ex 'field'
|
||||
* @param $order_desc bool Descendant sort direction
|
||||
* @return SqlCriteria
|
||||
* @desc Allow multiple calls
|
||||
*/
|
||||
public function order($field, $order_desc = false)
|
||||
{
|
||||
$this->order['sort'][] = $field;
|
||||
if ($order_desc) {
|
||||
$this->order['order'][$field] = 'desc';
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $offset int
|
||||
* @param $limit int
|
||||
* @return SqlCriteria
|
||||
*/
|
||||
public function limit($offset = 0, $limit)
|
||||
{
|
||||
if ($offset) {
|
||||
$this->limit = (int) $offset . ',';
|
||||
}
|
||||
$this->limit .= (int) $limit;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string|array $fields
|
||||
* @param bool $convert_to_db_expression
|
||||
* @ex SqlCriteria::select('field')
|
||||
* @ex SqlCriteria->select(array('field1', 'field2'))
|
||||
* @ex SqlCriteria->select('field1,field2')
|
||||
* @return SqlCriteria
|
||||
*/
|
||||
public function select($fields, $convert_to_db_expression = false)
|
||||
{
|
||||
if (!is_array($fields)) {
|
||||
$fields = explode(',', $fields);
|
||||
}
|
||||
$fields = array_map(function($item){return trim($item);},$fields);
|
||||
if ($convert_to_db_expression) {
|
||||
$fields = array_map(function($item){return new DbExpr($item);},$fields);
|
||||
}
|
||||
$this->select = array_merge($this->select,$fields);
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $field string|bool If true then distinct by *
|
||||
* @return SqlCriteria
|
||||
*/
|
||||
public function distinct($field)
|
||||
{
|
||||
$this->distinct = $field;
|
||||
return $this;
|
||||
}
|
||||
}
|
236
Model/SqlDbDriver.php
Normal file
236
Model/SqlDbDriver.php
Normal file
@ -0,0 +1,236 @@
|
||||
<?php namespace Majestic\Model;
|
||||
/**
|
||||
* @copyright NetMonsters <team@netmonsters.ru>
|
||||
* @link http://netmonsters.ru
|
||||
* @package Majestic
|
||||
* @subpackage db
|
||||
* @since 2011-11-11
|
||||
*/
|
||||
|
||||
abstract class SqlDbDriver extends DbDriver
|
||||
{
|
||||
|
||||
protected $identifier_quote = '`';
|
||||
|
||||
|
||||
|
||||
public function beginTransaction()
|
||||
{
|
||||
$this->connect();
|
||||
$this->driverBeginTransaction();
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function commit()
|
||||
{
|
||||
$this->connect();
|
||||
$this->driverCommitTransaction();
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function rollback()
|
||||
{
|
||||
$this->connect();
|
||||
$this->driverRollbackTransaction();
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $table
|
||||
* @param mixed $data
|
||||
* @param mixed $on_duplicate
|
||||
* @return int Affected rows count
|
||||
*/
|
||||
public function insert($table, $data, $on_duplicate = array())
|
||||
{
|
||||
$columns = array();
|
||||
foreach ($data as $col => $val) {
|
||||
$columns[] = $this->quoteIdentifier($col);
|
||||
}
|
||||
$values = array_values($data);
|
||||
|
||||
$sql = 'INSERT INTO ' . $this->quoteIdentifier($table)
|
||||
. ' (' . implode(', ', $columns) . ') VALUES (' . $this->quote($values) . ')';
|
||||
return $this->query($sql)->affectedRows();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $table
|
||||
* @param array $data
|
||||
* @param mixed $condition
|
||||
* @return int Number of updated rows
|
||||
*/
|
||||
public function update($table, $data, $condition = '')
|
||||
{
|
||||
$set = array();
|
||||
foreach ($data as $col => $val) {
|
||||
$set[] = $this->quoteIdentifier($col) . '=' . $this->quote($val);
|
||||
}
|
||||
$where = $this->whereExpr($condition);
|
||||
$sql = 'UPDATE ' . $this->quoteIdentifier($table) . ' SET ' . implode(', ', $set)
|
||||
. (($where) ? (' WHERE ' . $where) : '');
|
||||
return $this->query($sql)->affectedRows();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $table
|
||||
* @param mixed $condition
|
||||
* @return int
|
||||
*/
|
||||
public function delete($table, $condition = '')
|
||||
{
|
||||
$where = $this->whereExpr($condition);
|
||||
$sql = 'DELETE FROM ' . $this->quoteIdentifier($table) . (($where) ? (' WHERE ' . $where) : '');
|
||||
return $this->query($sql)->affectedRows();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $value
|
||||
* @return string
|
||||
*/
|
||||
public function quote($value)
|
||||
{
|
||||
if ($value instanceof DbExpr) {
|
||||
return (string) $value;
|
||||
}
|
||||
if (is_array($value)) {
|
||||
foreach ($value as &$val) {
|
||||
$val = $this->quote($val);
|
||||
}
|
||||
return implode(', ', $value);
|
||||
}
|
||||
return $this->driverQuote($value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $ident
|
||||
* @return string
|
||||
*/
|
||||
public function quoteIdentifier($ident)
|
||||
{
|
||||
$ident = explode('.', $ident);
|
||||
foreach ($ident as &$segment) {
|
||||
if (!preg_match('/^(\?|:[A-z][A-z0-9_]*+|\*)$/u', $segment)) {
|
||||
$segment = $this->identifier_quote . $segment . $this->identifier_quote;
|
||||
}
|
||||
}
|
||||
return implode('.', $ident);
|
||||
}
|
||||
|
||||
public function quoteInto($text, $value)
|
||||
{
|
||||
$pos = mb_strpos($text, '?');
|
||||
if ($pos === false) {
|
||||
return $text;
|
||||
}
|
||||
return mb_substr($text, 0, $pos) . $this->quote($value) . mb_substr($text, $pos + 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $where
|
||||
* @return string
|
||||
* @throws \ErrorException
|
||||
*/
|
||||
public function whereExpr($where)
|
||||
{
|
||||
if (empty($where)) {
|
||||
return $where;
|
||||
}
|
||||
|
||||
if (!is_array($where)) {
|
||||
$where = array($where);
|
||||
}
|
||||
foreach ($where as $cond => &$term) {
|
||||
if (is_int($cond)) {
|
||||
if (is_int($term)) {
|
||||
throw new \ErrorException('Condition in where expression as integer. ' . $term);
|
||||
}
|
||||
if ($term instanceof DbExpr) {
|
||||
$term = (string) $term;
|
||||
}
|
||||
} else {
|
||||
if (is_array($term)) {
|
||||
foreach ($term as &$val) {
|
||||
$val = $this->driverQuote($val);
|
||||
}
|
||||
$term = new DbExpr('(' . implode(',', $term) . ')');
|
||||
}
|
||||
$term = $this->quoteInto($cond, $term);
|
||||
}
|
||||
}
|
||||
return implode(' AND ', $where);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $group_by
|
||||
* @return string
|
||||
* @throws \ErrorException
|
||||
*/
|
||||
public function groupByExpr($group_by)
|
||||
{
|
||||
if (empty($group_by)) {
|
||||
return $group_by;
|
||||
}
|
||||
|
||||
if (!is_array($group_by)) {
|
||||
$group_by = array($group_by);
|
||||
}
|
||||
foreach ($group_by as &$term) {
|
||||
if ($term instanceof DbExpr) {
|
||||
$term = (string) $term;
|
||||
} else {
|
||||
$term = $this->quoteIdentifier($term);
|
||||
}
|
||||
}
|
||||
return implode(',', $group_by);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $select array
|
||||
* @param $distinct string|bool
|
||||
* @return string
|
||||
*/
|
||||
public function selectExpr($select, $distinct = false)
|
||||
{
|
||||
if (empty($distinct) && empty($select)) {
|
||||
return '*';
|
||||
}
|
||||
if (!is_array($select)) {
|
||||
$select = array($select);
|
||||
}
|
||||
if ($distinct) {
|
||||
$distinct = ((is_bool($distinct)) ? '*' : $this->quoteIdentifier($distinct));
|
||||
array_unshift($select, new DbExpr('DISTINCT ' . $distinct));
|
||||
}
|
||||
foreach ($select as $field => &$term) {
|
||||
if (is_int($field)) {
|
||||
if ($term instanceof DbExpr) {
|
||||
$term = (string) $term;
|
||||
} else {
|
||||
$term = $this->quoteIdentifier($term);
|
||||
}
|
||||
} else {
|
||||
$term = $this->quoteIdentifier($field) . ' as ' . $this->quoteIdentifier($term);
|
||||
}
|
||||
}
|
||||
return implode(',', $select);
|
||||
}
|
||||
|
||||
public function limitExpr($limit)
|
||||
{
|
||||
if (empty($limit)) {
|
||||
return $limit;
|
||||
}
|
||||
return implode(',',array_map(function($item){return intval($item);},explode(',',$limit)));
|
||||
}
|
||||
|
||||
abstract protected function driverQuote($value);
|
||||
|
||||
abstract protected function driverBeginTransaction();
|
||||
|
||||
abstract protected function driverCommitTransaction();
|
||||
|
||||
abstract protected function driverRollbackTransaction();
|
||||
|
||||
}
|
||||
|
238
Model/SqlModel.php
Normal file
238
Model/SqlModel.php
Normal file
@ -0,0 +1,238 @@
|
||||
<?php namespace Majestic\Model;
|
||||
|
||||
/**
|
||||
* Класс модели данных
|
||||
*
|
||||
* @copyright NetMonsters <team@netmonsters.ru>
|
||||
* @link http://netmonsters.ru
|
||||
* @package Majestic
|
||||
* @subpackage Model
|
||||
* @since 2011-11-11
|
||||
*/
|
||||
|
||||
/**
|
||||
* @property SqlDbDriver $db
|
||||
*/
|
||||
abstract class SqlModel extends Model
|
||||
{
|
||||
/**
|
||||
* @param string $ident
|
||||
* @return string Quoted identifier.
|
||||
*/
|
||||
public function identify($ident)
|
||||
{
|
||||
return $this->db->quoteIdentifier($ident);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $value
|
||||
* @return string Quoted value.
|
||||
*/
|
||||
public function quote($value)
|
||||
{
|
||||
return $this->db->quote($value);
|
||||
}
|
||||
|
||||
public function getDb()
|
||||
{
|
||||
return $this->db;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $id
|
||||
* @return object
|
||||
*/
|
||||
public function get($id)
|
||||
{
|
||||
$sql = 'SELECT * FROM :table WHERE :pk=?';
|
||||
return $this->fetch($sql, $id);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $data
|
||||
* @param mixed $where
|
||||
* @return int Number of affected rows
|
||||
*/
|
||||
public function update($data, $where)
|
||||
{
|
||||
if (is_int($where) || $where === (string)(int)$where) {
|
||||
$where = $this->identify($this->key) . '=' . (int)$where;
|
||||
}
|
||||
return parent::update($data, $where);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $id Int id
|
||||
* @return int Number of affected rows
|
||||
*/
|
||||
public function delete($id)
|
||||
{
|
||||
$where = $this->identify($this->key) . '=' . (int)$id;
|
||||
return $this->db->delete($this->table(), $where);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates order sql string
|
||||
*
|
||||
* @param array $params
|
||||
* @param array $sortable
|
||||
* @return string
|
||||
*/
|
||||
protected function order($params, $sortable = array('id'))
|
||||
{
|
||||
$sql = '';
|
||||
if (isset($params['sort'])) {
|
||||
if (!is_array($params['sort'])) {
|
||||
if (isset($params['order'])) {
|
||||
$params['order'] = array($params['sort'] => $params['order']);
|
||||
}
|
||||
$params['sort'] = array($params['sort']);
|
||||
}
|
||||
$order_list = array();
|
||||
for ($i = 0; $i < count($params['sort']); $i++) {
|
||||
$order = (isset($params['order'][$params['sort'][$i]]) && $params['order'][$params['sort'][$i]] == 'desc') ? 'DESC' : 'ASC';
|
||||
if (in_array($params['sort'][$i], $sortable)) {
|
||||
$order_list[] = $this->identify($params['sort'][$i]) . ' ' . $order;
|
||||
}
|
||||
}
|
||||
if ($order_list) {
|
||||
$sql = ' ORDER BY ' . implode(',', $order_list);
|
||||
}
|
||||
}
|
||||
return $sql;
|
||||
}
|
||||
|
||||
/**
|
||||
* Searches using like
|
||||
*
|
||||
* @param array $params
|
||||
* @param array $searchable
|
||||
* @param string $table_prefix
|
||||
* @return string
|
||||
*/
|
||||
protected function search($params, $searchable = array('id'), $table_prefix = '')
|
||||
{
|
||||
$sql = '';
|
||||
if (isset($params['q']) && isset($params['qt']) && in_array($params['qt'], $searchable)) {
|
||||
if ($table_prefix) {
|
||||
$sql = $table_prefix . '.';
|
||||
}
|
||||
$sql .= $this->identify($params['qt']) . ' LIKE ' . $this->quote('%' . $params['q'] . '%');
|
||||
}
|
||||
return $sql;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method appends to params table and primary key.
|
||||
* So they can be accessed through `:table` and `:pk` placeholders.
|
||||
*
|
||||
* @param string $sql
|
||||
* @param array $params
|
||||
* @return DbStatement
|
||||
*/
|
||||
protected function query($sql, $params = array())
|
||||
{
|
||||
if (!is_array($params)) {
|
||||
$params = array($params);
|
||||
}
|
||||
$params = array(
|
||||
'table' => new DbExpr($this->identify($this->table())),
|
||||
'pk' => new DbExpr($this->identify($this->key)),
|
||||
) + $params;
|
||||
return $this->db->query($sql, $params);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $data Request
|
||||
* @param array $params Request parameters
|
||||
* @param string $field Requested field name
|
||||
* @param CacheKey $cache_key Key for caching in
|
||||
* @return mixed
|
||||
*/
|
||||
protected function fetchField($data, $params = array(), $field, $cache_key = null)
|
||||
{
|
||||
if (!$cache_key || !$result = $cache_key->get()) {
|
||||
$result = $this->query($data, $params)->fetchField($field);
|
||||
if ($cache_key) {
|
||||
$cache_key->set($result);
|
||||
}
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $data Request
|
||||
* @param array $params Request parameters
|
||||
* @param CacheKey $cache_key Key for caching in
|
||||
* @return mixed
|
||||
*/
|
||||
protected function fetch($data, $params = array(), $cache_key = null)
|
||||
{
|
||||
if (!$cache_key || !$result = $cache_key->get()) {
|
||||
$result = $this->query($data, $params)->fetch();
|
||||
if ($cache_key) {
|
||||
$cache_key->set($result);
|
||||
}
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $data
|
||||
* @param array $params
|
||||
* @param CacheKey $cache_key
|
||||
* @return array
|
||||
*/
|
||||
protected function fetchAll($data, $params = array(), $cache_key = null)
|
||||
{
|
||||
if (!$cache_key || !$result = $cache_key->get()) {
|
||||
$result = $this->query($data, $params)->fetchAll();
|
||||
if ($cache_key) {
|
||||
$cache_key->set($result);
|
||||
}
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $select array
|
||||
* @param $distinct string|bool
|
||||
* @param $where array @ex array('field=?' => $value, 'field=1')
|
||||
* @param $order array @ex array('sort' => array('field1', 'field2'), 'order' => array('field2' => 'desc'))
|
||||
* @param $limit string @ex '30' or '30,30'
|
||||
* @param $heaving TODO
|
||||
* @param $group_by TODO
|
||||
* @param $sql_expression null|string
|
||||
* @param $sql_expression_params array
|
||||
* @param $cache_key CacheKey|null
|
||||
* @return SqlResultProvider
|
||||
*/
|
||||
public function find($select, $distinct, $where, $order, $limit, $heaving = null, $group_by = null, $sql_expression = null, $sql_expression_params = array(), $cache_key = null)
|
||||
{
|
||||
$select = $this->db->selectExpr($select, $distinct);
|
||||
$where = $this->db->whereExpr($where);
|
||||
$group_by = $this->db->groupByExpr($group_by);
|
||||
$order = isset($order['sort']) ? $this->order($order, $order['sort']) : false;
|
||||
$limit = $this->db->limitExpr($limit);
|
||||
$result = $this->query(
|
||||
(($sql_expression) ? $sql_expression : ('SELECT ' . $select . ' FROM ' . $this->identify($this->table())))
|
||||
. (($where) ? (' WHERE ' . $where) : '')
|
||||
. (($group_by) ? (' GROUP BY ' . $group_by) : '')
|
||||
. (($order) ? ($order) : '')
|
||||
. (($limit) ? (' LIMIT ' . $limit) : ''),
|
||||
$sql_expression_params,
|
||||
$cache_key
|
||||
);
|
||||
return new SqlResultProvider($result);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $sql_expression null
|
||||
* @param $sql_expression_params array
|
||||
* @return SqlCriteria
|
||||
*/
|
||||
public function criteria($sql_expression = null, $sql_expression_params = array())
|
||||
{
|
||||
return new SqlCriteria($this, $sql_expression, $sql_expression_params);
|
||||
}
|
||||
}
|
40
Model/SqlResultCollection.php
Normal file
40
Model/SqlResultCollection.php
Normal file
@ -0,0 +1,40 @@
|
||||
<?php namespace Majestic\Model;
|
||||
|
||||
class SqlResultCollection extends \ArrayIterator implements iSqlResultItems
|
||||
{
|
||||
private $items;
|
||||
|
||||
public function __construct($items)
|
||||
{
|
||||
$this->items = $items;
|
||||
foreach ($items as $item) {
|
||||
parent::append($item);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return DbStatement[]
|
||||
*/
|
||||
public function fetchAll()
|
||||
{
|
||||
return (array) $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $field
|
||||
* @return mixed
|
||||
*/
|
||||
public function fetchField($field)
|
||||
{
|
||||
$item = $this->offsetGet(0);
|
||||
return $item->{$field};
|
||||
}
|
||||
|
||||
/**
|
||||
* @return mixed
|
||||
*/
|
||||
public function fetch()
|
||||
{
|
||||
return $this->offsetGet(0);
|
||||
}
|
||||
}
|
122
Model/SqlResultProvider.php
Normal file
122
Model/SqlResultProvider.php
Normal file
@ -0,0 +1,122 @@
|
||||
<?php namespace Majestic\Model;
|
||||
|
||||
class SqlResultProvider implements iSqlResultItems
|
||||
{
|
||||
/**
|
||||
* @var DbStatement
|
||||
*/
|
||||
private $result;
|
||||
|
||||
/**
|
||||
* @var array
|
||||
* @desc my be changed in assoc method
|
||||
*/
|
||||
private $result_items;
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
private $result_items_base;
|
||||
|
||||
/**
|
||||
* @param $result DbStatement
|
||||
*/
|
||||
public function __construct($result)
|
||||
{
|
||||
$this->result = $result;
|
||||
}
|
||||
|
||||
private function defineResultItems()
|
||||
{
|
||||
if (is_null($this->result_items_base)) {
|
||||
$this->result_items_base = $this->result->fetchAll();
|
||||
$this->result_items = $this->result_items_base;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $field string
|
||||
* @param bool $assoc_as_array
|
||||
* @return $this SqlResultProvider
|
||||
* @throws \ErrorException
|
||||
*/
|
||||
public function assoc($field, $assoc_as_array = false)
|
||||
{
|
||||
$this->defineResultItems();
|
||||
$result_items_assoc = array();
|
||||
foreach ($this->result_items_base as $item) {
|
||||
if (!isset($item->{$field})) {
|
||||
throw new \ErrorException('Undefined field. ' . $field);
|
||||
}
|
||||
if ($assoc_as_array) {
|
||||
if (!isset($result_items_assoc[$item->{$field}])) {
|
||||
$result_items_assoc[$item->{$field}] = array();
|
||||
}
|
||||
$result_items_assoc[$item->{$field}][] = $item;
|
||||
} else {
|
||||
if (isset($result_items_assoc[$item->{$field}])) {
|
||||
throw new \ErrorException('Field not unique. May be use assoc_as_array. ' . $field);
|
||||
}
|
||||
$result_items_assoc[$item->{$field}] = $item;
|
||||
}
|
||||
}
|
||||
// Ассоциирование внутри каждого элемента массива
|
||||
if ($assoc_as_array) {
|
||||
foreach ($result_items_assoc as &$value) {
|
||||
$value = new SqlResultCollection($value);
|
||||
}
|
||||
}
|
||||
$this->result_items = $result_items_assoc;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getKeys()
|
||||
{
|
||||
$this->defineResultItems();
|
||||
return array_keys($this->result_items);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $key
|
||||
* @return mixed
|
||||
* метод актуален после вызова assoc
|
||||
*/
|
||||
public function fetchKey($key)
|
||||
{
|
||||
return $this->result_items[$key];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return DbStatement[]|SqlResultCollection[]
|
||||
*/
|
||||
public function fetchAll()
|
||||
{
|
||||
$this->defineResultItems();
|
||||
return $this->result_items;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $field
|
||||
* @return mixed
|
||||
*/
|
||||
public function fetchField($field)
|
||||
{
|
||||
return $this->result->fetchField($field);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return mixed
|
||||
*/
|
||||
public function fetch()
|
||||
{
|
||||
return $this->result->fetch(Db::FETCH_OBJ);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int
|
||||
*/
|
||||
public function affectedRows()
|
||||
{
|
||||
return $this->result->affectedRows();
|
||||
}
|
||||
}
|
10
Model/iSqlResultItems.php
Normal file
10
Model/iSqlResultItems.php
Normal file
@ -0,0 +1,10 @@
|
||||
<?php namespace Majestic\Model;
|
||||
|
||||
interface iSqlResultItems
|
||||
{
|
||||
public function fetchAll();
|
||||
|
||||
public function fetchField($field);
|
||||
|
||||
public function fetch();
|
||||
}
|
Reference in New Issue
Block a user