1. Go to this page and download the library: Download sokil/php-mongo library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
$document->triggerError('someField', 'email', 'E-mail must be at domain example.com');
class CustomDocument extends \Sokil\Mongo\Document
{
punlic function rules()
{
return array(
array(
'email',
'uniqueFieldValidator',
'message' => 'E-mail must be unique in collection'
),
);
}
/**
* Validator
*/
public function uniqueFieldValidator($fieldName, $params)
{
// Some logic of checking unique mail.
//
// Before version 1.7 this method must return true if validator passes,
// and false otherwise.
//
// Since version 1.7 this method return no values and must call
// Document::addError() method to add error into stack.
}
}
namespace Vendor\Mongo\Validator;
/**
* Validator class
*/
class MyOwnEqualsValidator extends \Sokil\Mongo\Validator
{
public function validateField(\Sokil\Mongo\Document $document, $fieldName, array $params)
{
if (!$document->get($fieldName)) {
return;
}
if ($document->get($fieldName) === $params['to']) {
return;
}
if (!isset($params['message'])) {
$params['message'] = 'Field "' . $fieldName . '" must be equals to "' . $params['to'] . '" in model ' . get_called_class();
}
$document->addError($fieldName, $this->getName(), $params['message']);
}
}
/**
* Registering validator in document
*/
class SomeDocument extends \Sokil\Mongo\Document
{
public function beforeConstruct()
{
$this->addValidatorNamespace('Vendor\Mongo\Validator');
}
public function rules()
{
return array(
// 'my_own_equals' converts to 'MyOwnEqualsValidator' class name
array('field', 'my_own_equals', 'to' => 42, 'message' => 'Not equals'),
);
}
}
/**
* Profile class
*/
class Profile extends \Sokil\Mongo\Structure
{
public function getBirthday() { return $this->get('birthday'); }
public function getGender() { return $this->get('gender'); }
public function getCountry() { return $this->get('country'); }
public function getCity() { return $this->get('city'); }
}
/**
* User model
*/
class User extends \Sokil\Mongo\Document
{
public function getProfile()
{
return $this->getObject('profile', '\Profile');
}
}
$birthday = $user->getProfile()->getBirthday();
/**
* Profile class
*/
class Profile extends \Sokil\Mongo\Structure
{
public function getBirthday() { return $this->get('birthday'); }
public function rules()
{
return array(
array('birthday', '
class Comment extends \Sokil\Mongo\Structure
{
public function getAuthor() { return $this->get('author'); }
public function getText() { return $this->get('text'); }
public function getDate() { return $this->get('date')->sec; }
}
class Post extends \Sokil\Mongo\Document
{
public function getComments()
{
return $this->getObjectList('comments', '\Comment');
}
}
// to new collection of same database
$collection
->find()
->where('condition', 1)
->copyToCollection('newCollection');
// to new collection in new database
$collection
->find()
->where('condition', 1)
->copyToCollection('newCollection', 'newDatabase');
// to new collection of same database
$collection
->find()
->where('condition', 1)
->moveToCollection('newCollection');
// to new collection in new database
$collection
->find()
->where('condition', 1)
->moveToCollection('newCollection', 'newDatabase');
// define expression in collection
class UserCollection extends \Sokil\Mongo\Collection
{
protected $_queryExpressionClass = 'UserExpression';
}
// use custom method for searching
$collection = $db->getCollection('user'); // instance of UserCollection
$queryBuilder = $collection->find(); // instance of UserExpression
// now methods available in query buider
$queryBuilder->whereAgeGreaterThan(18)->fetchRandom();
// since v.1.3.2 also supported query builder configuration through callable:
$collection
->find(function(UserExpression $e) {
$e->whereAgeGreaterThan(18);
})
->fetchRandom();
// creates index on location field
$collection->ensure2dSphereIndex('location');
// cerate compound index
$collection->ensureIndex(array(
'location' => '2dsphere',
'name' => -1,
));
php
// through array
$aggregator->match(array(
'field' => 'value'
));
// through callable
$aggregator->match(function($expression) {
$expression->whereLess('date', new \MongoDate);
});
php
/**
* @var array list of aggregation results
*/
$result = $aggregator->aggregate();
// or
$result = $collection->aggregate($aggregator);
php
// by array
$collection->aggregate(array(
array(
'$match' => array(
'field' => 'value',
),
),
));
// or callable
$collection->aggregate(function($aggregator) {
$aggregator->match(function($expression) {
$expression->whereLess('date', new \MongoDate);
});
});
php
// as argument of Pipeline::aggregate
$collection->createAggregator()->match()->group()->aggregate($options);
// as argument of Collection::aggregate
$collection->aggregate($pipelines, $options);
// as calling of Pipeline methods
$collection
->createAggregator()
->explain()
->allowDiskUse()
->setBatchSize(100);
php
// set explain option
$collection->aggregate($pipelines, ['explain' => true]);
// or configure pipeline
$collection->createAggregator()->match(...)->group(...)->explain()->aggregate();
php
// set as argument
$asCursor = true;
$collection->aggregate($pipelines, $options, $asCursor);
// or call method
$cursor = $collection->createAggregator()->match()->group()->aggregateCursor();
php
$listener = function(
\Sokil\Mongo\Event $event, // instance of event
string $eventName, // event name
\Symfony\Component\EventDispatcher\EventDispatcher $eventDispatcher // instance of dispatcher
) {}
php
$document->onMyOwnEvent($listener, $priority);
// which is equals to
$this->attachEvent('myOwnEvent', $listener, $priority);
php
class CustomDocument extends \Sokil\Mongo\Document
{
public function beforeConstruct()
{
$this->onBeforeSave(function() {
$this->set('date' => new \MongoDate);
});
}
}
php
$this->triggerEvent('myOwnEvent');
php
// create class
class OwnEvent extends \Sokil\Mongo\Event {
public $status;
}
// define listener
$document->attachEvent('someEvent', function(\OwnEvent $event) {
echo $event->status;
});
// configure event
$event = new \OwnEvent;
$event->status = 'ok';
// trigger event
$this->triggerEvent('someEvent', $event);
php
class SomeBehavior extends \Sokil\Mongo\Behavior
{
public function return42()
{
return 42;
}
}
php
class SomeBehavior extends \Sokil\Mongo\Behavior
{
public function getOwnerParam($selector)
{
return $this->getOwner()->get($selector);
}
}
php
class CustomDocument extends \Sokil\Mongo\Document
{
public function behaviors()
{
return [
'42behavior' => '\SomeBehavior',
];
}
}
php
// single behavior
$document->attachBehavior('42behavior', '\SomeBehavior');
// set of behaviors
$document->attachBehaviors([
'42behavior' => '\SomeBehavior',
]);
php
// class name
$document->attachBehavior('42behavior', '\SomeBehavior');
// array with parameters
$document->attachBehavior('42behavior', [
'class' => '\SomeBehavior',
'param1' => 1,
'param2' => 2,
]);
// Behavior instance
$document->attachBehavior('42behavior', new \SomeBehavior([
'param1' => 1,
'param2' => 2,
]);
php
class User extends \Sokil\Mongo\Document
{
protected $schema = [
'email' => null,
'password' => null,
];
public function relations()
{
return [
'postsRelation' => [self::RELATION_HAS_MANY, 'posts', 'user_id'],
];
}
}
class Posts extends \Sokil\Mongo\Document
{
protected $schema = [
'user_id' => null,
'message' => null,
];
public function relations()
{
return [
'userRelation' => [self::RELATION_BELONGS, 'user', 'user_id'],
];
}
public function getMessage()
{
return $this->get('message');
}
}
php
foreach($user->postsRelation as $post) {
echo $post->getMessage();
}
php
// this document contains field 'driver_id' where array of ids stored
class CarDocument extends \Sokil\Mongo\Document
{
protected $schema = [
'brand' => null,
];
public function relations()
{
return array(
'drivers' => array(self::RELATION_MANY_MANY, 'drivers', 'driver_id', true),
);
}
}
class DriverDocument extends \Sokil\Mongo\Document
{
protected $schema = [
'name' => null,
];
public function relations()
{
return array(
'cars' => array(self::RELATION_MANY_MANY, 'cars', 'driver_id'),
);
}
}
php
foreach($car->drivers as $driver) {
echo $driver->name;
}
php
$car->addRelation('drivers', $driver);
php
$car->removeRelation('drivers', $driver);
php
// in constructor
$client = new Client($dsn, array(
'readPreference' => 'nearest',
));
// by passing to \Sokil\Mongo\Client instance
$client->readNearest();
// by passing to database
$database = $client->getDatabase('databaseName')->readPrimaryOnly();
// by passing to collection
$collection = $database->getCollection('collectionName')->readSecondaryOnly();
php
// by passing to \Sokil\Mongo\Client instance
$client->setMajorityWriteConcern(10000);
// by passing to database
$database = $client->getDatabase('databaseName')->setMajorityWriteConcern(10000);
// by passing to collection
$collection = $database->getCollection('collectionName')->setWriteConcern(4, 1000);
php
// dump binary data to file
$file->dump($filename);
// get binary data
$file->getBytes();
// get resource
$file->getResource();
php
// define mapping of prefix to GridFS class
$database->map([
'GridFSPrefix' => '\GridFSClass',
]);
// define GridFSFile class
class GridFSClass extends \Sokil\Mongo\GridFS
{
public function getFileClassName(\MongoGridFSFile $fileData = null)
{
return '\GridFSFileClass';
}
}
// define file class
class GridFSFileClass extends \Sokil\Mongo\GridFSFile
{
public function getMetaParam()
{
return $this->get('meta.param');
}
}
// get file as instance of class \GridFSFileClass
$database->getGridFS('GridFSPrefix')->getFileById($id)->getMetaParam();