Abstract class Phalcon\Mvc\Collection

implements Phalcon\Mvc\EntityInterface, Phalcon\Mvc\CollectionInterface, Phalcon\Di\InjectionAwareInterface, Serializable

Source on GitHub

This component implements a high level abstraction for NoSQL databases which works with documents

Constants

integer OP_NONE

integer OP_CREATE

integer OP_UPDATE

integer OP_DELETE

integer DIRTY_STATE_PERSISTENT

integer DIRTY_STATE_TRANSIENT

integer DIRTY_STATE_DETACHED

Methods

final public __construct ([Phalcon\DiInterface $dependencyInjector], [Phalcon\Mvc\Collection\ManagerInterface $modelsManager])

Phalcon\Mvc\Collection constructor

public setId (mixed $id)

Sets a value for the _id property, creates a MongoId object if needed

public MongoId getId ()

Returns the value of the _id property

public setDI (Phalcon\DiInterface $dependencyInjector)

Sets the dependency injection container

public getDI ()

Returns the dependency injection container

protected setEventsManager (Phalcon\Mvc\Collection\ManagerInterface $eventsManager)

Sets a custom events manager

protected getEventsManager ()

Returns the custom events manager

public getCollectionManager ()

Returns the models manager related to the entity instance

public getReservedAttributes ()

Returns an array with reserved properties that cannot be part of the insert/update

protected useImplicitObjectIds (mixed $useImplicitObjectIds)

Sets if a model must use implicit objects ids

protected setSource (mixed $source)

Sets collection name which model should be mapped

public getSource ()

Returns collection name mapped in the model

public setConnectionService (mixed $connectionService)

Sets the DependencyInjection connection service name

public getConnectionService ()

Returns DependencyInjection connection service

public MongoDb getConnection ()

Retrieves a database connection

public mixed readAttribute (string $attribute)

Reads an attribute value by its name

  1. <?php
  2. echo $robot->readAttribute("name");

public writeAttribute (string $attribute, mixed $value)

Writes an attribute value by its name

  1. <?php
  2. $robot->writeAttribute("name", "Rosey");

public static cloneResult (Phalcon\Mvc\CollectionInterface $collection, array $document)

Returns a cloned collection

protected static array _getResultset (array $params, Phalcon\Mvc\Collection $collection, MongoDb $connection, boolean $unique)

Returns a collection resultset

protected static int _getGroupResultset (array $params, Phalcon\Mvc\Collection $collection, MongoDb $connection)

Perform a count over a resultset

final protected boolean _preSave (Phalcon\DiInterface $dependencyInjector, boolean $disableEvents, boolean $exists)

Executes internal hooks before save a document

final protected _postSave (mixed $disableEvents, mixed $success, mixed $exists)

Executes internal events after save a document

protected validate (mixed $validator)

Executes validators on every validation call

  1. <?php
  2. use Phalcon\Mvc\Model\Validator\ExclusionIn as ExclusionIn;
  3. class Subscriptors extends \Phalcon\Mvc\Collection
  4. {
  5. public function validation()
  6. {
  7. // Old, deprecated syntax, use new one below
  8. $this->validate(
  9. new ExclusionIn(
  10. [
  11. "field" => "status",
  12. "domain" => ["A", "I"],
  13. ]
  14. )
  15. );
  16. if ($this->validationHasFailed() == true) {
  17. return false;
  18. }
  19. }
  20. }
  1. <?php
  2. use Phalcon\Validation\Validator\ExclusionIn as ExclusionIn;
  3. use Phalcon\Validation;
  4. class Subscriptors extends \Phalcon\Mvc\Collection
  5. {
  6. public function validation()
  7. {
  8. $validator = new Validation();
  9. $validator->add("status",
  10. new ExclusionIn(
  11. [
  12. "domain" => ["A", "I"]
  13. ]
  14. )
  15. );
  16. return $this->validate($validator);
  17. }
  18. }

public validationHasFailed ()

Check whether validation process has generated any messages

  1. <?php
  2. use Phalcon\Mvc\Model\Validator\ExclusionIn as ExclusionIn;
  3. class Subscriptors extends \Phalcon\Mvc\Collection
  4. {
  5. public function validation()
  6. {
  7. $this->validate(
  8. new ExclusionIn(
  9. [
  10. "field" => "status",
  11. "domain" => ["A", "I"],
  12. ]
  13. )
  14. );
  15. if ($this->validationHasFailed() == true) {
  16. return false;
  17. }
  18. }
  19. }

public fireEvent (mixed $eventName)

Fires an internal event

public fireEventCancel (mixed $eventName)

Fires an internal event that cancels the operation

protected _cancelOperation (mixed $disableEvents)

Cancel the current operation

protected boolean _exists (MongoCollection $collection)

Checks if the document exists in the collection

public getMessages ()

Returns all the validation messages

  1. <?php
  2. $robot = new Robots();
  3. $robot->type = "mechanical";
  4. $robot->name = "Astro Boy";
  5. $robot->year = 1952;
  6. if ($robot->save() === false) {
  7. echo "Umh, We can't store robots right now ";
  8. $messages = $robot->getMessages();
  9. foreach ($messages as $message) {
  10. echo $message;
  11. }
  12. } else {
  13. echo "Great, a new robot was saved successfully!";
  14. }

public appendMessage (Phalcon\Mvc\Model\MessageInterface $message)

Appends a customized message on the validation process

  1. <?php
  2. use \Phalcon\Mvc\Model\Message as Message;
  3. class Robots extends \Phalcon\Mvc\Model
  4. {
  5. public function beforeSave()
  6. {
  7. if ($this->name === "Peter") {
  8. $message = new Message(
  9. "Sorry, but a robot cannot be named Peter"
  10. );
  11. $this->appendMessage(message);
  12. }
  13. }
  14. }

protected prepareCU ()

Shared Code for CU Operations Prepares Collection

public save ()

Creates/Updates a collection based on the values in the attributes

public create ()

Creates a collection based on the values in the attributes

public createIfNotExist (array $criteria)

Creates a document based on the values in the attributes, if not found by criteria Preferred way to avoid duplication is to create index on attribute

  1. <?php
  2. $robot = new Robot();
  3. $robot->name = "MyRobot";
  4. $robot->type = "Droid";
  5. // Create only if robot with same name and type does not exist
  6. $robot->createIfNotExist(
  7. [
  8. "name",
  9. "type",
  10. ]
  11. );

public update ()

Creates/Updates a collection based on the values in the attributes

public static findById (mixed $id)

Find a document by its id (_id)

  1. <?php
  2. // Find user by using \MongoId object
  3. $user = Users::findById(
  4. new \MongoId("545eb081631d16153a293a66")
  5. );
  6. // Find user by using id as sting
  7. $user = Users::findById("45cbc4a0e4123f6920000002");
  8. // Validate input
  9. if ($user = Users::findById($_POST["id"])) {
  10. // ...
  11. }

public static findFirst ([array $parameters])

Allows to query the first record that match the specified conditions

  1. <?php
  2. // What's the first robot in the robots table?
  3. $robot = Robots::findFirst();
  4. echo "The robot name is ", $robot->name, "\n";
  5. // What's the first mechanical robot in robots table?
  6. $robot = Robots::findFirst(
  7. [
  8. [
  9. "type" => "mechanical",
  10. ]
  11. ]
  12. );
  13. echo "The first mechanical robot name is ", $robot->name, "\n";
  14. // Get first virtual robot ordered by name
  15. $robot = Robots::findFirst(
  16. [
  17. [
  18. "type" => "mechanical",
  19. ],
  20. "order" => [
  21. "name" => 1,
  22. ],
  23. ]
  24. );
  25. echo "The first virtual robot name is ", $robot->name, "\n";
  26. // Get first robot by id (_id)
  27. $robot = Robots::findFirst(
  28. [
  29. [
  30. "_id" => new \MongoId("45cbc4a0e4123f6920000002"),
  31. ]
  32. ]
  33. );
  34. echo "The robot id is ", $robot->_id, "\n";

public static find ([array $parameters])

Allows to query a set of records that match the specified conditions

  1. <?php
  2. // How many robots are there?
  3. $robots = Robots::find();
  4. echo "There are ", count($robots), "\n";
  5. // How many mechanical robots are there?
  6. $robots = Robots::find(
  7. [
  8. [
  9. "type" => "mechanical",
  10. ]
  11. ]
  12. );
  13. echo "There are ", count(robots), "\n";
  14. // Get and print virtual robots ordered by name
  15. $robots = Robots::findFirst(
  16. [
  17. [
  18. "type" => "virtual"
  19. ],
  20. "order" => [
  21. "name" => 1,
  22. ]
  23. ]
  24. );
  25. foreach ($robots as $robot) {
  26. echo $robot->name, "\n";
  27. }
  28. // Get first 100 virtual robots ordered by name
  29. $robots = Robots::find(
  30. [
  31. [
  32. "type" => "virtual",
  33. ],
  34. "order" => [
  35. "name" => 1,
  36. ],
  37. "limit" => 100,
  38. ]
  39. );
  40. foreach ($robots as $robot) {
  41. echo $robot->name, "\n";
  42. }

public static count ([array $parameters])

Perform a count over a collection

  1. <?php
  2. echo "There are ", Robots::count(), " robots";

public static aggregate ([array $parameters])

Perform an aggregation using the Mongo aggregation framework

public static summatory (mixed $field, [mixed $conditions], [mixed $finalize])

Allows to perform a summatory group for a column in the collection

public delete ()

Deletes a model instance. Returning true on success or false otherwise.

  1. <?php
  2. $robot = Robots::findFirst();
  3. $robot->delete();
  4. $robots = Robots::find();
  5. foreach ($robots as $robot) {
  6. $robot->delete();
  7. }

public setDirtyState (mixed $dirtyState)

Sets the dirty state of the object using one of the DIRTY_STATE_* constants

public getDirtyState ()

Returns one of the DIRTY_STATE_* constants telling if the document exists in the collection or not

protected addBehavior (Phalcon\Mvc\Collection\BehaviorInterface $behavior)

Sets up a behavior in a collection

public skipOperation (mixed $skip)

Skips the current operation forcing a success state

public toArray ()

Returns the instance as an array representation

  1. <?php
  2. print_r(
  3. $robot->toArray()
  4. );

public serialize ()

Serializes the object ignoring connections or protected properties

public unserialize (mixed $data)

Unserializes the object from a serialized string