refactored MongoModel to hide fetch method, fixed PHPDoc errors

This commit is contained in:
Anton Grebnev
2012-10-19 20:15:26 +04:00
parent efb6c2d34c
commit 11a5968105
14 changed files with 436 additions and 187 deletions

View File

@ -31,6 +31,7 @@ class Db
* @param array $config Configuration array.
*
* @return DbDriver
* @throws InitializationException
*/
static public function connect($name = 'default', $config = null)
{

View File

@ -66,6 +66,7 @@ abstract class DbStatement
/**
* @param string $field
* @return array Value of queried field for all matching rows
*/
public function fetchColumn($field)
{
@ -78,6 +79,7 @@ abstract class DbStatement
/**
* @param string $field
* @return mixed Value of queried filed for first matching row
*/
public function fetchField($field)
{
@ -108,6 +110,7 @@ abstract class DbStatement
abstract public function numRows();
/**
* @param mixed $request
* @return bool
*/
abstract protected function driverExecute($request);

View File

@ -63,7 +63,6 @@ abstract class Model
/**
* @param array $data
* @param array $on_duplicate
* @return int Id of inserted row
*/
public function insert($data)
@ -152,22 +151,22 @@ abstract class Model
abstract public function delete($id);
/**
* @param string $sql
* @param array $params
* @param string $field
* @param CacheKey $cache_key
* @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 $sql
* @param array $params
* @param CacheKey $cache_key
* @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 $sql
* @param string $data
* @param array $params
* @param CacheKey $cache_key
*/

View File

@ -22,6 +22,12 @@ class MongoCommandBuilder
const COMMAND = 'Command';
/**
* @param string $type
* @param MongoCollection $collection
* @return MongoDbCommand
*/
static public function factory($type, $collection = null)
{
$class = ucfirst($type) . 'MongoCommand';
@ -33,8 +39,18 @@ class MongoCommandBuilder
abstract class MongoDbCommand
{
/**
* @var MongoCollection
*/
protected $collection;
/**
* Execute Mongo command/query
*
* @return mixed
* @throws GeneralException
*/
public function execute()
{
if ($this->checkParams()) {
@ -44,6 +60,12 @@ abstract class MongoDbCommand
}
}
/**
* @param string $name Parameter name
* @param mixed $value Parameter value
* @return MongoDbCommand
*/
public function bindParam($name, $value)
{
if (property_exists($this, $name)) {
@ -52,12 +74,22 @@ abstract class MongoDbCommand
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 = '[';

View File

@ -38,6 +38,12 @@ class MongoDriver extends NoSqlDbDriver
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));
@ -49,17 +55,6 @@ class MongoDriver extends NoSqlDbDriver
return $this->query($command, $params);
}
public function get($collection, $condition, $fields = array())
{
$command = MongoCommandBuilder::factory(MongoCommandBuilder::FIND, $this->getCollection($collection));
$params = array(
'condition' => $condition,
'fields' => $fields,
'multiple' => false
);
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));
@ -123,10 +118,9 @@ class MongoDriver extends NoSqlDbDriver
}
/**
* @param mixed $request
* @return DbStatement
* @return MongoStatement
*/
public function prepare($request)
{

View File

@ -10,9 +10,20 @@
* @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')
@ -20,16 +31,11 @@ abstract class MongoModel extends Model
parent::__construct($connection);
}
public function count($query = array(), $limit = 0, $skip = 0)
protected function count($query = array(), $limit = 0, $skip = 0)
{
return $this->db->count($this->table(), $query, $limit, $skip);
}
public function find($condition = array(), $fields = array())
{
return $this->db->find($this->table(), $condition, $fields);
}
public function get($id)
{
if ($this->useMongoId) {
@ -37,7 +43,7 @@ abstract class MongoModel extends Model
$id = new MongoId($id);
}
}
return $this->db->get($this->table(), array('_id' => $id))->fetch();
return $this->fetch(array($this->key => $id));
}
public function batchInsert($data)
@ -45,6 +51,16 @@ abstract class MongoModel extends Model
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) {
@ -52,18 +68,25 @@ abstract class MongoModel extends Model
$id = new MongoId($id);
}
}
return $this->db->delete($this->table(), array('_id' => $id));
}
public function deleteAll($query = array())
{
$this->db->delete($this->table(), $query);
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))->fetchField($field);
$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);
}
@ -71,10 +94,21 @@ abstract class MongoModel extends Model
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)->fetch();
$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);
}
@ -82,14 +116,105 @@ abstract class MongoModel extends Model
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)->fetchAll();
$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 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 GeneralException('Wrong order parameter given to query.');
}
}
return $order;
}
/**
* @param array $params Parameters for find query
* @return array Query result sort rules
* @throws 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 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;
}
}

View File

@ -114,7 +114,7 @@ class MongoStatement extends DbStatement
} else {
return false;
}
} elseif (is_int($this->result)) {
} elseif (is_int($this->result) || $this->result instanceof MongoId) {
return $this->result;
}
return false;
@ -156,6 +156,9 @@ class MongoStatement extends DbStatement
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;
}

View File

@ -14,7 +14,7 @@
*/
class MySQLiDriver extends SqlDbDriver
{
public function insert($table, $bind, $on_duplicate = array())
{
$columns = array();
@ -22,7 +22,7 @@ class MySQLiDriver extends SqlDbDriver
$columns[] = $this->quoteIdentifier($col);
}
$values = array_values($bind);
if ($on_duplicate) {
$update = array();
foreach ($on_duplicate as $col => $val) {
@ -30,16 +30,16 @@ class MySQLiDriver extends SqlDbDriver
}
$on_duplicate = ' ON DUPLICATE KEY UPDATE ' . implode(', ', $update);
}
$sql = 'INSERT INTO ' . $this->quoteIdentifier($table)
. ' (' . implode(', ', $columns) . ') VALUES (' . $this->quote($values) . ')'
. (($on_duplicate) ? $on_duplicate : '');
. ' (' . implode(', ', $columns) . ') VALUES (' . $this->quote($values) . ')'
. (($on_duplicate) ? $on_duplicate : '');
return $this->query($sql)->affectedRows();
}
/**
* @param mixed $sql
* @return DbStatement
* @return MySQLiStatement
*/
public function prepare($sql)
{
@ -50,73 +50,73 @@ class MySQLiDriver extends SqlDbDriver
{
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;
$this->connection = null;
}
protected function connect()
{
if ($this->connection) {
return;
}
$port = isset($this->config['port']) ? (int) $this->config['port'] : null;
$this->connection = mysqli_init();
$connected = @mysqli_real_connect($this->connection,
$this->config['hostname'],
$this->config['username'],
$this->config['password'],
$this->config['database'],
$port);
@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();

View File

@ -83,6 +83,7 @@ class MySQLiStatement extends DbStatement
*
* @param mixed $style
* @return mixed
* @throws GeneralException
*/
public function fetch($style = Db::FETCH_OBJ)
{
@ -90,7 +91,6 @@ class MySQLiStatement extends DbStatement
return false;
}
$row = false;
switch ($style) {
case Db::FETCH_OBJ:
$row = $this->result->fetch_object();
@ -112,6 +112,7 @@ class MySQLiStatement extends DbStatement
/**
* @param string $class
* @return object
*/
public function fetchObject($class = 'stdClass')
{

View File

@ -37,7 +37,7 @@ abstract class SqlDbDriver extends DbDriver
/**
* @param string $table
* @param mixed $bind
* @param mixed $data
* @param mixed $on_duplicate
* @return int Affected rows count
*/
@ -56,9 +56,9 @@ abstract class SqlDbDriver extends DbDriver
/**
* @param string $table
* @param array $bind
* @param mixed $where
* @return int
* @param array $data
* @param mixed $condition
* @return int Number of updated rows
*/
public function update($table, $data, $condition = '')
{
@ -74,7 +74,7 @@ abstract class SqlDbDriver extends DbDriver
/**
* @param string $table
* @param mixed $where
* @param mixed $condition
* @return int
*/
public function delete($table, $condition = '')
@ -152,10 +152,6 @@ abstract class SqlDbDriver extends DbDriver
return implode(' AND ', $where);
}
/**
* @return DbStatement
*/
abstract protected function driverQuote($value);
abstract protected function driverBeginTransaction();

View File

@ -10,6 +10,9 @@
* @since 2011-11-11
*/
/**
* @property SqlDbDriver $db
*/
abstract class SqlModel extends Model
{
@ -105,8 +108,10 @@ abstract class SqlModel extends Model
/**
* This method appends to params table and primary key.
* So they can be accessed thru `:table` and `:pk` placeholders.
* So they can be accessed through `:table` and `:pk` placeholders.
*
* @param string $sql
* @param array $params
* @return DbStatement
*/
protected function query($sql, $params = array())
@ -122,10 +127,11 @@ abstract class SqlModel extends Model
}
/**
* @param string $sql
* @param array $params
* @param string $field
* @param CacheKey $cache_key
* @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)
{
@ -139,9 +145,10 @@ abstract class SqlModel extends Model
}
/**
* @param string $sql
* @param array $params
* @param CacheKey $cache_key
* @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)
{
@ -155,9 +162,10 @@ abstract class SqlModel extends Model
}
/**
* @param string $sql
* @param string $data
* @param array $params
* @param CacheKey $cache_key
* @return array
*/
protected function fetchAll($data, $params = array(), $cache_key = null)
{