Duffer Derek
<?php namespace App\Repository\General;
use Exception;
/**
* Created by PhpStorm.
* User: jis
* Date: 6/4/15
* Time: 10:30 AM
*/
abstract class JModel extends MongoConnection
{
public $collection;
public function __construct($attributes = array())
{
// $conObj = new MongoConnection();
// $this->collection = $conObj->getCollection($attributes['table']);
$this->collection = $this->getCollection($attributes['table']);
}
public function createIndex($array)
{
$this->collection->createIndex($array);
}
public function create($data)
{
$data['created_at'] = time();
$data['updated_at'] = time();
$this->collection->insert($data);
return (String)$data['_id'];
}
public function delete($query)
{
$this->collection->remove($query);
}
public function firstOrCreate($data)
{
$result = $this->collection->findOne($data);
if ($result) {
return $result['_id'];
} else {
$data['created_at'] = time();
$this->collection->insert($data);
return $data['_id'];
}
}
public function createIfNotExists($data)
{
$result = $this->collection->findOne($data);
if ($result) {
return false; // data already exists
} else { // create new item
$data['created_at'] = time();
$this->collection->insert($data);
return $data['_id'];
}
}
public function update($query, $newData, $multiple = true)
{
$newData['updated_at'] = time();
if (isset($newData['_id']))
unset($newData['_id']);
$this->collection->update($query, array('$set' => $newData), array('multiple' => $multiple));
}
public function findOne($query)
{
return $this->collection->findOne($query);
}
public function find($query, $limit = null)
{
$cursor = $this->collection->find($query);
if ($cursor) {
try {
$cursor->sort(array('updated_at' => -1));
} catch (Exception $e) {
}
if ($limit) {
$cursor->limit($limit);
if ($limit == 1) {
if ($cursor->count() > 0) {
$cursor->getNext();
return $cursor->current();
}
}
}
if ($cursor->count() > 0) {
return $cursor;
}
}
return null;
}
public function findAndSortBy($query, $sort, $limit = null)
{
$cursor = $this->collection->find($query);
if ($cursor) {
try {
$cursor->sort(array($sort => -1));
} catch (Exception $e) {
}
if ($limit) {
$cursor->limit($limit);
if ($limit == 1) {
if ($cursor->count() > 0) {
$cursor->getNext();
return $cursor->current();
}
}
}
if ($cursor->count() > 0) {
return $cursor;
}
}
return null;
}
public function getCount($query)
{
$cursor = $this->collection->find($query);
if ($cursor) {
return $cursor->count();
}
return 0;
}
public function findPage($query, $page, $limit)
{
$skip = ($page - 1) * $limit;
$sort = array('updated_at' => -1);
$cursor = $this->collection->find($query)->skip($skip)->limit($limit)->sort($sort);;
if ($cursor) {
return $cursor;
}
return null;
}
}
Sindbad File Manager Version 1.0, Coded By Sindbad EG ~ The Terrorists