-
Notifications
You must be signed in to change notification settings - Fork 3
Accessing Collections
As of version 0.2.0, CakeMonga supports the usage of custom Collection classes. These
custom classes are located with the src/Model/MongoCollection
folder an extend the CakeMonga\MongoCollection\BaseCollection
class. Now you can
use these classes to encapsulate data layer logic into the appropriate class locations. These methods are direct abstractions of their Monga counterparts.
You can view the docs for these methods on the Monga API Docs. The BaseCollection
class provides the following methods for data access:
class BaseCollection {
public function getCollection();
public function find($query = [], $fields = [], $findOne = false);
public function findOne($query = [], $fields = []);
public function drop();
public function listIndexes();
public function save($document, $options = []);
public function update($values = [], $query = null, $options = []);
public function insert(array $data, $options = []);
public function remove($criteria, $options = []);
public function truncate();
public function aggregate($aggregation = []);
public function distinct($key, $query = []);
public function count($query = []);
}
Note that the MongoDB collection that is utilized by custom Collection classes is the tableized name of the Collection class itself. For example,
UsersCollection.php
would map to the users
collection inside of your MongoDB instance.
As of 0.2.0, custom Collection models extended from BaseCollection
can be retrieved using the CollectionRegistry
singleton
with the same syntax that TableRegistry
employs:
// Define a custom User collection at src/Model/MongoCollection/UserCollection.php.
use CakeMonga\MongoCollection\BaseCollection;
class UsersCollection extends BaseCollection
{
public function getUsersNamedJohn()
{
return $this->find(['name' => 'John']);
}
}
// We can retrieve this UsersCollection by using the static ::get() method on CollectionRegistry
use CakeMonga\MongoCollection\CollectionRegistry;
$users_collection = CollectionRegistry::get('Users');
By default, the CollectionRegistry utilizes the default connection defined as 'mongo_db' in your app.php file. Want to use a different Mongo datasource? No problem, just pass in a datasource string to the 'connection' attribute of the config array for CollectionRegistry::get():
$users_collection = CollectionRegistry::get('Users', [
'connection' => 'secondary_mongo_datasource'
]
This would construct the UsersCollection class with a connection to the other datasource.
The CollectionRegistry caches instances of Collection objects by default. If you need to clear the CollectionRegistry's cache of collections, just call the static method clear()
on the CollectionRegistry itself:
$users_collection = CollectionRegistry::get('Users'); // Users is now cached in registry
CollectionRegistry::clear(); // All collections are now cleared from registry
By default, the CollectionRegistry sources classes from the App\Model\MongoCollection
namespace. If you want to source your Collection classes from a different location, you can use the setNamespace()
method on the CollectionRegistry during application bootstrap:
// In bootstrap.php
CollectionRegistry::setNamespace('App\\Model\\AlternativeCollectionLocation');
Alternatively, if you need to swap back to the default namespace on the fly, you can use the defaultNamespace()
method and it will reset back to the default:
CollectionRegistry::defaultNamespace();
By default, when getting a Collection object using the registry, it injects the relevant MongoConnection object defined in your Datasources array with the mongo_db
key. You can alter the connection used by the CollectionRegistry at runtime by using the setDefaultConnection()
method on the CollectionRegistry itself:
use CakeMonga\MongoCollection\CollectionRegistry;
// Connection is 'mongo_db' my default:
$default = ConnectionRegistry::getDefaultConnection(); // returns 'mongo_db'
// Let's set the default connection to 'alt_mongo_db':
ConnectionRegistry::setDefaultConnection('alt_mongo_db');
$new_default = ConnectionRegistry::getDefaultConnection(); // returns 'alt_mongo_db'
The CollectionRegistry will now create Collection objects with the 'alt_mongo_db' data source instead.
The BaseCollection class allows for the usage of behaviors in the same manner as the Table class does. The interface for modifying behaviors on the BaseCollection class is the same as the table class:
class BaseCollection {
public function behaviors();
public function addBehavior($name, array $options = []);
public function removeBehavior($name);
public function hasBehavior($name);
}
To create a behavior for a Collection, instead of extending the Behavior
class, you will instead extend the MongoBehavior
class. The primary difference between these two classes is that Behavior is tied intrinsically to a Table object and the MongoBehavior class is tied intrinsically to a BaseCollection object.
The MongoBehavior class provides the same functionality to a BaseCollection as a Behavior class would to a Table object. This includes defining additional implemented events, mixin methods, as well as custom finders on the BaseCollection class itself.
The Collection class has 9 different event hooks that can be tapped into to alter the execution of your collection's functionality. It is important to note that if you want to use an event to intercept an argument for changing before a method is run, such as altering a $document before saving to include timestamp values, you will need to update the argument DIRECTLY on the $event->data[]
array.
use CakeMonga\MongoCollection\BaseCollection;
class CustomCollection extends BaseCollection
{
public function beforeFind($event, $query, $fields, $findOne);
public function beforeSave($event, $document);
public function afterSave($event, $document)
public function beforeInsert($event, $data);
public function afterInsert($event, $results)
public function beforeUpdate($event, $values, $query)
public function afterUpdate($event, $document);
public function beforeRemove($event, $criteria);
public function afterRemove($event, $result, $criteria);
}
- $event - Event - The event object that is being handled by the event manager.
- $query - Array - The query passed into the
find()
orfindOne()
method. - $fields - Array - The selected fields passed into the find method.
- $findOne - boolean - Whether the find method was
find()
orfindOne()
- $event - Event - The event object that is being handled by the event manager.
- $document - Array - The document being saved
- $options - Array - The options array passed into the
save()
method
- $event - Event - The event object that is being handled by the event manager.
- $results - boolean - Whether or not the save was successful
- $document - Array - The document that was saved
- $options - Array - The options array passed into
save()
.
- $event - Event - The event object that is being handled by the event manager.
- $data - Array - The data to be inserted into the collection.
- $event - Event - The event object that is being handled by the event manager.
- $ids - Array - An array of the MongoId objects of each inserted document.
- $results - Array - The array of saved documents with id included
- $event - Event - The event object that is being handled by the event manager.
- $values - Array - The update values being applied to the selected documents.
- $query - Array - The query for which documents are being selected for update.
- $event - Event - The event object that is being handled by the event manager.
- $results - boolean - Whether the update was successful.
- $query - Array - The query for which documents are being selected for update.
- $values - Array - The update values to be applied to the selected documents.
- $event - Event - The event object that is being handled by the event manager.
- $criteria - Array - The where criteria for which documents are being selected for removal.
- $event - Event - The event object that is being handled by the event manager.
- $result - boolean - Whether the remove was successful or not.
- $criteria - Array - The where criteria for which documents are selected for removal.
You can add your own event hooks to your Mongo Collection in the same manner that you would with a regular Table class, by overriding the implementedEvents()
method on your collection class:
public function implementedEvents()
{
$eventMap = [
'Model.beforeFind' => 'beforeFind',
'Model.beforeSave' => 'beforeSave',
'Model.afterSave' => 'afterSave',
'Model.beforeInsert' => 'beforeInsert',
'Model.afterInsert' => 'afterInsert',
'Model.beforeUpdate' => 'beforeUpdate',
'Model.afterUpdate' => 'afterUpdate',
'Model.beforeRemove' => 'beforeRemove',
'Model.afterRemove' => 'afterRemove',
// Add
// Additional
// Event Listeners
// Here
];
$events = [];
foreach ($eventMap as $event => $method) {
if (!method_exists($this, $method)) {
continue;
}
$events[$event] = $method;
}
return $events;
}
Now, on to Query Logging.