Trying a new generation script
@@ -0,0 +1,20 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>Doctrine ODM</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>Doctrine ODM</string>
|
||||
<key>DashDocSetFamily</key>
|
||||
<string>python</string>
|
||||
<key>DocSetPlatformFamily</key>
|
||||
<string>doctrine odm</string>
|
||||
<key>dashIndexFilePath</key>
|
||||
<string>index.html</string>
|
||||
<key>isDashDocset</key>
|
||||
<true/>
|
||||
<key>isJavaScriptEnabled</key>
|
||||
<false/>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,4 @@
|
||||
# Sphinx build info version 1
|
||||
# This file hashes the configuration used when building these files. When it is not found, a full rebuild will be done.
|
||||
config: b9a0aa75b165bda23dea90cac5cdb554
|
||||
tags: 645f666f9bcd5a90fca523b33c5a78b7
|
||||
@@ -0,0 +1,210 @@
|
||||
Blending the ORM and MongoDB ODM
|
||||
================================
|
||||
|
||||
Since the start of the `Doctrine MongoDB Object Document Mapper`_ project people have asked how it can be integrated with the `ORM`_. This article will demonstrates how you can integrate the two transparently, maintaining a clean domain model.
|
||||
|
||||
This example will have a `Product` that is stored in MongoDB and the `Order` stored in a MySQL database.
|
||||
|
||||
Define Product
|
||||
--------------
|
||||
|
||||
First lets define our `Product` document:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
namespace Documents;
|
||||
|
||||
/** @Document */
|
||||
class Product
|
||||
{
|
||||
/** @Id */
|
||||
private $id;
|
||||
|
||||
/** @Field(type="string") */
|
||||
private $title;
|
||||
|
||||
public function getId()
|
||||
{
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
public function getTitle()
|
||||
{
|
||||
return $this->title;
|
||||
}
|
||||
|
||||
public function setTitle($title)
|
||||
{
|
||||
$this->title = $title;
|
||||
}
|
||||
}
|
||||
|
||||
Define Entity
|
||||
-------------
|
||||
|
||||
Next create the `Order` entity that has a `$product` and `$productId` property linking it to the `Product` that is stored with MongoDB:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
namespace Entities;
|
||||
|
||||
use Documents\Product;
|
||||
|
||||
/**
|
||||
* @Entity
|
||||
* @Table(name="orders")
|
||||
*/
|
||||
class Order
|
||||
{
|
||||
/**
|
||||
* @Id @Column(type="integer")
|
||||
* @GeneratedValue(strategy="AUTO")
|
||||
*/
|
||||
private $id;
|
||||
|
||||
/**
|
||||
* @Column(type="string")
|
||||
*/
|
||||
private $productId;
|
||||
|
||||
/**
|
||||
* @var Documents\Product
|
||||
*/
|
||||
private $product;
|
||||
|
||||
public function getId()
|
||||
{
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
public function getProductId()
|
||||
{
|
||||
return $this->productId;
|
||||
}
|
||||
|
||||
public function setProduct(Product $product)
|
||||
{
|
||||
$this->productId = $product->getId();
|
||||
$this->product = $product;
|
||||
}
|
||||
|
||||
public function getProduct()
|
||||
{
|
||||
return $this->product;
|
||||
}
|
||||
}
|
||||
|
||||
Event Subscriber
|
||||
----------------
|
||||
|
||||
Now we need to setup an event subscriber that will set the `$product` property of all `Order` instances to a reference to the document product so it can be lazily loaded when it is accessed the first time. So first register a new event subscriber:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$eventManager = $em->getEventManager();
|
||||
$eventManager->addEventListener(
|
||||
array(\Doctrine\ORM\Events::postLoad), new MyEventSubscriber($dm)
|
||||
);
|
||||
|
||||
So now we need to define a class named `MyEventSubscriber` and pass a dependency to the `DocumentManager`. It will have a `postLoad()` method that sets the product document reference:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
use Doctrine\ODM\MongoDB\DocumentManager;
|
||||
use Doctrine\ORM\Event\LifecycleEventArgs;
|
||||
|
||||
class MyEventSubscriber
|
||||
{
|
||||
public function __construct(DocumentManager $dm)
|
||||
{
|
||||
$this->dm = $dm;
|
||||
}
|
||||
|
||||
public function postLoad(LifecycleEventArgs $eventArgs)
|
||||
{
|
||||
$order = $eventArgs->getEntity();
|
||||
$em = $eventArgs->getEntityManager();
|
||||
$productReflProp = $em->getClassMetadata('Entities\Order')
|
||||
->reflClass->getProperty('product');
|
||||
$productReflProp->setAccessible(true);
|
||||
$productReflProp->setValue(
|
||||
$order, $this->dm->getReference('Documents\Product', $order->getProductId())
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
The `postLoad` method will be invoked after an ORM entity is loaded from the database. This allows us to use the `DocumentManager` to set the `$product` property with a reference to the `Product` document with the product id we previously stored.
|
||||
|
||||
Working with Products and Orders
|
||||
--------------------------------
|
||||
|
||||
First create a new `Product`:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$product = new \Documents\Product();
|
||||
$product->setTitle('Test Product');
|
||||
$dm->persist($product);
|
||||
$dm->flush();
|
||||
|
||||
Now create a new `Order` and link it to a `Product` in MySQL:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$order = new \Entities\Order();
|
||||
$order->setProduct($product);
|
||||
$em->persist($order);
|
||||
$em->flush();
|
||||
|
||||
Later we can retrieve the entity and lazily load the reference to the document in MongoDB:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$order = $em->find('Order', $order->getId());
|
||||
|
||||
// Instance of an uninitialized product proxy
|
||||
$product = $order->getProduct();
|
||||
|
||||
// Initializes proxy and queries the database
|
||||
echo "Order Title: " . $product->getTitle();
|
||||
|
||||
If you were to print the `$order` you would see that we got back regular PHP objects:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
print_r($order);
|
||||
|
||||
The above would output the following:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
Order Object
|
||||
(
|
||||
[id:Entities\Order:private] => 53
|
||||
[productId:Entities\Order:private] => 4c74a1868ead0ed7a9000000
|
||||
[product:Entities\Order:private] => Proxies\DocumentsProductProxy Object
|
||||
(
|
||||
[__isInitialized__] => 1
|
||||
[id:Documents\Product:private] => 4c74a1868ead0ed7a9000000
|
||||
[title:Documents\Product:private] => Test Product
|
||||
)
|
||||
)
|
||||
|
||||
.. _Doctrine MongoDB Object Document Mapper: http://www.doctrine-project.org/projects/mongodb_odm
|
||||
.. _ORM: http://www.doctrine-project.org/projects/orm
|
||||
@@ -0,0 +1,123 @@
|
||||
Implementing ArrayAccess for Domain Objects
|
||||
===========================================
|
||||
|
||||
.. sectionauthor:: Roman Borschel (roman@code-factory.org)
|
||||
|
||||
This recipe will show you how to implement ArrayAccess for your
|
||||
domain objects in order to allow more uniform access, for example
|
||||
in templates. In these examples we will implement ArrayAccess on a
|
||||
`Layer Supertype <http://martinfowler.com/eaaCatalog/layerSupertype.html>`_
|
||||
for all our domain objects.
|
||||
|
||||
Option 1
|
||||
--------
|
||||
|
||||
In this implementation we will make use of PHPs highly dynamic
|
||||
nature to dynamically access properties of a subtype in a supertype
|
||||
at runtime. Note that this implementation has 2 main caveats:
|
||||
|
||||
- It will not work with private fields
|
||||
- It will not go through any getters/setters
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
abstract class DomainObject implements ArrayAccess
|
||||
{
|
||||
public function offsetExists($offset)
|
||||
{
|
||||
return isset($this->$offset);
|
||||
}
|
||||
|
||||
public function offsetSet($offset, $value)
|
||||
{
|
||||
$this->$offset = $value;
|
||||
}
|
||||
|
||||
public function offsetGet($offset)
|
||||
{
|
||||
return $this->$offset;
|
||||
}
|
||||
|
||||
public function offsetUnset($offset)
|
||||
{
|
||||
$this->$offset = null;
|
||||
}
|
||||
}
|
||||
|
||||
Option 2
|
||||
--------
|
||||
|
||||
In this implementation we will dynamically invoke getters/setters.
|
||||
Again we use PHPs dynamic nature to invoke methods on a subtype
|
||||
from a supertype at runtime. This implementation has the following
|
||||
caveats:
|
||||
|
||||
- It relies on a naming convention
|
||||
- The semantics of offsetExists can differ
|
||||
- offsetUnset will not work with typehinted setters
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
abstract class DomainObject implements ArrayAccess
|
||||
{
|
||||
public function offsetExists($offset)
|
||||
{
|
||||
// In this example we say that exists means it is not null
|
||||
$value = $this->{"get$offset"}();
|
||||
return $value !== null;
|
||||
}
|
||||
|
||||
public function offsetSet($offset, $value)
|
||||
{
|
||||
$this->{"set$offset"}($value);
|
||||
}
|
||||
|
||||
public function offsetGet($offset)
|
||||
{
|
||||
return $this->{"get$offset"}();
|
||||
}
|
||||
|
||||
public function offsetUnset($offset)
|
||||
{
|
||||
$this->{"set$offset"}(null);
|
||||
}
|
||||
}
|
||||
|
||||
Read-only
|
||||
---------
|
||||
|
||||
You can slightly tweak option 1 or option 2 in order to make array
|
||||
access read-only. This will also circumvent some of the caveats of
|
||||
each option. Simply make offsetSet and offsetUnset throw an
|
||||
exception (i.e. BadMethodCallException).
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
abstract class DomainObject implements ArrayAccess
|
||||
{
|
||||
public function offsetExists($offset)
|
||||
{
|
||||
// option 1 or option 2
|
||||
}
|
||||
|
||||
public function offsetSet($offset, $value)
|
||||
{
|
||||
throw new BadMethodCallException("Array access of class " . get_class($this) . " is read-only!");
|
||||
}
|
||||
|
||||
public function offsetGet($offset)
|
||||
{
|
||||
// option 1 or option 2
|
||||
}
|
||||
|
||||
public function offsetUnset($offset)
|
||||
{
|
||||
throw new BadMethodCallException("Array access of class " . get_class($this) . " is read-only!");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
Implementing the Notify ChangeTracking Policy
|
||||
=============================================
|
||||
|
||||
.. sectionauthor:: Roman Borschel (roman@code-factory.org)
|
||||
|
||||
The NOTIFY change-tracking policy is the most effective
|
||||
change-tracking policy provided by Doctrine but it requires some
|
||||
boilerplate code. This recipe will show you how this boilerplate
|
||||
code should look like. We will implement it on a
|
||||
`Layer Supertype <http://martinfowler.com/eaaCatalog/layerSupertype.html>`_
|
||||
for all our domain objects.
|
||||
|
||||
Implementing NotifyPropertyChanged
|
||||
----------------------------------
|
||||
|
||||
The NOTIFY policy is based on the assumption that the entities
|
||||
notify interested listeners of changes to their properties. For
|
||||
that purpose, a class that wants to use this policy needs to
|
||||
implement the ``NotifyPropertyChanged`` interface from the
|
||||
``Doctrine\Common`` namespace.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
use Doctrine\Common\NotifyPropertyChanged,
|
||||
Doctrine\Common\PropertyChangedListener;
|
||||
|
||||
abstract class DomainObject implements NotifyPropertyChanged
|
||||
{
|
||||
private $_listeners = array();
|
||||
|
||||
public function addPropertyChangedListener(PropertyChangedListener $listener)
|
||||
{
|
||||
$this->_listeners[] = $listener;
|
||||
}
|
||||
|
||||
/** Notifies listeners of a change. */
|
||||
protected function _onPropertyChanged($propName, $oldValue, $newValue)
|
||||
{
|
||||
if ($this->_listeners) {
|
||||
foreach ($this->_listeners as $listener) {
|
||||
$listener->propertyChanged($this, $propName, $oldValue, $newValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Then, in each property setter of concrete, derived domain classes,
|
||||
you need to invoke \_onPropertyChanged as follows to notify
|
||||
listeners:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
// Mapping not shown, either in annotations, xml or yaml as usual
|
||||
class MyEntity extends DomainObject
|
||||
{
|
||||
private $data;
|
||||
// ... other fields as usual
|
||||
|
||||
public function setData($data)
|
||||
{
|
||||
if ($data != $this->data) { // check: is it actually modified?
|
||||
$this->_onPropertyChanged('data', $this->data, $data);
|
||||
$this->data = $data;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
The check whether the new value is different from the old one is
|
||||
not mandatory but recommended. That way you can avoid unnecessary
|
||||
updates and also have full control over when you consider a
|
||||
property changed.
|
||||
@@ -0,0 +1,77 @@
|
||||
Implementing Wakeup or Clone
|
||||
============================
|
||||
|
||||
.. sectionauthor:: Roman Borschel (roman@code-factory.org)
|
||||
|
||||
As explained in the
|
||||
:doc:`restrictions for document classes in the manual <../reference/architecture>`.
|
||||
it is usually not allowed for a document to implement ``__wakeup``
|
||||
or ``__clone``, because Doctrine makes special use of them.
|
||||
However, it is quite easy to make use of these methods in a safe
|
||||
way by guarding the custom wakeup or clone code with a document
|
||||
identity check, as demonstrated in the following sections.
|
||||
|
||||
Safely implementing \_\_wakeup
|
||||
------------------------------
|
||||
|
||||
To safely implement ``__wakeup``, simply enclose your
|
||||
implementation code in an identity check as follows:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
class MyDocument
|
||||
{
|
||||
private $id; // This is the identifier of the document.
|
||||
//...
|
||||
|
||||
public function __wakeup()
|
||||
{
|
||||
// If the document has an identity, proceed as normal.
|
||||
if ($this->id) {
|
||||
// ... Your code here as normal ...
|
||||
}
|
||||
// otherwise do nothing, do NOT throw an exception!
|
||||
}
|
||||
|
||||
//...
|
||||
}
|
||||
|
||||
Safely implementing \_\_clone
|
||||
-----------------------------
|
||||
|
||||
Safely implementing ``__clone`` is pretty much the same:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
class MyDocument
|
||||
{
|
||||
private $id; // This is the identifier of the document.
|
||||
//...
|
||||
|
||||
public function __clone()
|
||||
{
|
||||
// If the document has an identity, proceed as normal.
|
||||
if ($this->id) {
|
||||
// ... Your code here as normal ...
|
||||
}
|
||||
// otherwise do nothing, do NOT throw an exception!
|
||||
}
|
||||
|
||||
//...
|
||||
}
|
||||
|
||||
Summary
|
||||
-------
|
||||
|
||||
As you have seen, it is quite easy to safely make use of
|
||||
``__wakeup`` and ``__clone`` in your documents without adding any
|
||||
really Doctrine-specific or Doctrine-dependant code.
|
||||
|
||||
These implementations are possible and safe because when Doctrine
|
||||
invokes these methods, the documents never have an identity (yet).
|
||||
Furthermore, it is possibly a good idea to check for the identity
|
||||
in your code anyway, since it's rarely the case that you want to
|
||||
unserialize or clone a document with no identity.
|
||||
@@ -0,0 +1,232 @@
|
||||
Mapping Classes to the ORM and ODM
|
||||
==================================
|
||||
|
||||
Because of the non intrusive design of Doctrine it is possible for you to have plain PHP classes
|
||||
that are mapped to both a relational database with the Doctrine2 Object Relational Mapper and
|
||||
MongoDB with the Doctrine MongoDB Object Document Mapper, or any other persistence layer that
|
||||
implements the Doctrine Common `persistence`_ interfaces.
|
||||
|
||||
Test Subject
|
||||
------------
|
||||
|
||||
For this cookbook entry we need to define a class that can be persisted to both MySQL and MongoDB.
|
||||
We'll use a ``BlogPost`` as you may want to write some generic blogging functionality that has support
|
||||
for multiple Doctrine persistence layers:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
namespace Doctrine\Blog;
|
||||
|
||||
class BlogPost
|
||||
{
|
||||
private $id;
|
||||
private $title;
|
||||
private $body;
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
Mapping Information
|
||||
-------------------
|
||||
|
||||
Now we just need to provide the mapping information for the Doctrine persistence layers so they know
|
||||
how to consume the objects and persist them to the database.
|
||||
|
||||
ORM
|
||||
~~~
|
||||
|
||||
First define the mapping for the ORM:
|
||||
|
||||
.. configuration-block::
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
namespace Doctrine\Blog;
|
||||
|
||||
/** @Entity(repositoryClass="Doctrine\Blog\ORM\BlogPostRepository") */
|
||||
class BlogPost
|
||||
{
|
||||
/** @Id @Column(type="integer") */
|
||||
private $id;
|
||||
|
||||
/** @Column(type="string") */
|
||||
private $title;
|
||||
|
||||
/** @Column(type="text") */
|
||||
private $body;
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping
|
||||
http://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
|
||||
|
||||
<entity name="Documents\BlogPost" repository-class="Doctrine\Blog\ORM\BlogPostRepository">
|
||||
<id name="id" type="integer" />
|
||||
<field name="name" type="string" />
|
||||
<field name="email" type="text" />
|
||||
</entity>
|
||||
</doctrine-mapping>
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
Documents\BlogPost:
|
||||
repositoryClass: Doctrine\Blog\ORM\BlogPostRepository
|
||||
id:
|
||||
id:
|
||||
type: integer
|
||||
fields:
|
||||
title:
|
||||
type: string
|
||||
body:
|
||||
type: text
|
||||
|
||||
Now you are able to persist the ``Documents\BlogPost`` with an instance of ``EntityManager``:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$blogPost = new BlogPost()
|
||||
$blogPost->setTitle('test');
|
||||
|
||||
$em->persist($blogPost);
|
||||
$em->flush();
|
||||
|
||||
You can find the blog post:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$blogPost = $em->getRepository('Documents\BlogPost')->findOneByTitle('test');
|
||||
|
||||
MongoDB ODM
|
||||
~~~~~~~~~~~
|
||||
|
||||
Now map the same class to the Doctrine MongoDB ODM:
|
||||
|
||||
.. configuration-block::
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
namespace Documents;
|
||||
|
||||
/** @Document(repositoryClass="Doctrine\Blog\ODM\MongoDB\BlogPostRepository") */
|
||||
class BlogPost
|
||||
{
|
||||
/** @Id */
|
||||
private $id;
|
||||
|
||||
/** @Field(type="string") */
|
||||
private $title;
|
||||
|
||||
/** @Field(type="string") */
|
||||
private $body;
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<doctrine-mongo-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping
|
||||
http://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
|
||||
|
||||
<document name="Documents\BlogPost" repository-class="Doctrine\Blog\ODM\MongoDB\BlogPostRepository">
|
||||
<field fieldName="id" type="id" />
|
||||
<field fieldName="name" type="string" />
|
||||
<field fieldName="email" type="text" />
|
||||
</document>
|
||||
</doctrine-mongo-mapping>
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
Documents\BlogPost:
|
||||
repositoryClass: Doctrine\Blog\ODM\MongoDB\BlogPostRepository
|
||||
fields:
|
||||
id:
|
||||
type: id
|
||||
title:
|
||||
type: string
|
||||
body:
|
||||
type: text
|
||||
|
||||
Now the same class is able to be persisted in the same way using an instance of ``DocumentManager``:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$blogPost = new BlogPost()
|
||||
$blogPost->setTitle('test');
|
||||
|
||||
$dm->persist($blogPost);
|
||||
$dm->flush();
|
||||
|
||||
You can find the blog post:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$blogPost = $dm->getRepository('Documents\BlogPost')->findOneByTitle('test');
|
||||
|
||||
Repository Classes
|
||||
------------------
|
||||
|
||||
You can implement the same repository interface for the ORM and MongoDB ODM easily:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
namespace Doctrine\Blog\ORM;
|
||||
|
||||
use Doctrine\ORM\EntityRepository;
|
||||
|
||||
class BlogPostRepository extends EntityRepository
|
||||
{
|
||||
public function findPostById($id)
|
||||
{
|
||||
return $this->findOneBy(array('id' => $id));
|
||||
}
|
||||
}
|
||||
|
||||
Now define the same repository methods for the MongoDB ODM:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
namespace Doctrine\Blog\ODM\MongoDB;
|
||||
|
||||
use Doctrine\ODM\MongoDB\DocumentRepository;
|
||||
|
||||
class BlogPostRepository extends DocumentRepository
|
||||
{
|
||||
public function findPostById($id)
|
||||
{
|
||||
return $this->findOneBy(array('id' => $id));
|
||||
}
|
||||
}
|
||||
|
||||
As you can see the repositories are the same and the final returned data is the same vanilla
|
||||
PHP objects. The data is transparently injected to the objects for you automatically so you
|
||||
are not forced to extend some base class or shape your domain in any certain way for it to work
|
||||
with the Doctrine persistence layers.
|
||||
|
||||
.. _persistence: https://github.com/doctrine/common/tree/master/lib/Doctrine/Common/Persistence
|
||||
@@ -0,0 +1,139 @@
|
||||
Keeping Your Modules Independent
|
||||
================================
|
||||
|
||||
One of the goals of using modules is to create discrete units of functionality
|
||||
that do not have many (if any) dependencies, allowing you to use that
|
||||
functionality in other applications without including unnecessary items.
|
||||
|
||||
Doctrine MongoDB ODM includes a utility called
|
||||
``ResolveTargetDocumentListener``, that functions by intercepting certain calls
|
||||
inside Doctrine and rewriting ``targetDocument`` parameters in your metadata
|
||||
mapping at runtime. This allows your bundle to use an interface or abstract
|
||||
class in its mappings while still allowing the mapping to resolve to a concrete
|
||||
document class at runtime.
|
||||
|
||||
This functionality allows you to define relationships between different
|
||||
documents without creating hard dependencies.
|
||||
|
||||
Background
|
||||
----------
|
||||
|
||||
In the following example, we have an `InvoiceModule` that provides invoicing
|
||||
functionality, and a `CustomerModule` that contains customer management tools.
|
||||
We want to keep these separated, because they can be used in other systems
|
||||
without each other; however, we'd like to use them together in our application.
|
||||
|
||||
In this case, we have an ``Invoice`` document with a relationship to a
|
||||
non-existent object, an ``InvoiceSubjectInterface``. The goal is to get
|
||||
the ``ResolveTargetDocumentListener`` to replace any mention of the interface
|
||||
with a real class that implements that interface.
|
||||
|
||||
Configuration
|
||||
-------------
|
||||
|
||||
We're going to use the following basic documents (which are incomplete
|
||||
for brevity) to explain how to set up and use the
|
||||
``ResolveTargetDocumentListener``.
|
||||
|
||||
A Customer document:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
// src/Acme/AppModule/Document/Customer.php
|
||||
|
||||
namespace Acme\AppModule\Document;
|
||||
|
||||
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
|
||||
use Acme\CustomerModule\Document\Customer as BaseCustomer;
|
||||
use Acme\InvoiceModule\Model\InvoiceSubjectInterface;
|
||||
|
||||
/**
|
||||
* @ODM\Document
|
||||
*/
|
||||
class Customer extends BaseCustomer implements InvoiceSubjectInterface
|
||||
{
|
||||
// In our example, any methods defined in the InvoiceSubjectInterface
|
||||
// are already implemented in the BaseCustomer
|
||||
}
|
||||
|
||||
An Invoice document:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
// src/Acme/InvoiceModule/Document/Invoice.php
|
||||
|
||||
namespace Acme\InvoiceModule\Document;
|
||||
|
||||
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
|
||||
use Acme\InvoiceModule\Model\InvoiceSubjectInterface;
|
||||
|
||||
/**
|
||||
* @ODM\Document
|
||||
*/
|
||||
class Invoice
|
||||
{
|
||||
/**
|
||||
* @ODM\ReferenceOne(targetDocument="Acme\InvoiceModule\Model\InvoiceSubjectInterface")
|
||||
* @var InvoiceSubjectInterface
|
||||
*/
|
||||
protected $subject;
|
||||
}
|
||||
|
||||
An InvoiceSubjectInterface:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
// src/Acme/InvoiceModule/Model/InvoiceSubjectInterface.php
|
||||
|
||||
namespace Acme\InvoiceModule\Model;
|
||||
|
||||
/**
|
||||
* An interface that the invoice Subject object should implement.
|
||||
* In most circumstances, only a single object should implement
|
||||
* this interface as the ResolveTargetDocumentListener can only
|
||||
* change the target to a single object.
|
||||
*/
|
||||
interface InvoiceSubjectInterface
|
||||
{
|
||||
// List any additional methods that your InvoiceModule
|
||||
// will need to access on the subject so that you can
|
||||
// be sure that you have access to those methods.
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getName();
|
||||
}
|
||||
|
||||
Next, we need to configure the listener. Add this to the area where you setup
|
||||
Doctrine MongoDB ODM. You must set this up in the way outlined below, otherwise
|
||||
you cannot be guaranteed that the targetDocument resolution will occur reliably:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
$evm = new \Doctrine\Common\EventManager;
|
||||
$rtdl = new \Doctrine\ODM\MongoDB\Tools\ResolveTargetDocumentListener;
|
||||
|
||||
// Adds a target-document class
|
||||
$rtdl->addResolveTargetDocument(
|
||||
'Acme\\InvoiceModule\\Model\\InvoiceSubjectInterface',
|
||||
'Acme\\CustomerModule\\Document\\Customer',
|
||||
array()
|
||||
);
|
||||
|
||||
// Add the ResolveTargetDocumentListener
|
||||
$evm->addEventListener(\Doctrine\ODM\MongoDB\Events::loadClassMetadata, $rtdl);
|
||||
|
||||
// Create the document manager as you normally would
|
||||
$dm = \Doctrine\ODM\MongoDB\DocumentManager::create($connectionOptions, $config, $evm);
|
||||
|
||||
Final Thoughts
|
||||
--------------
|
||||
|
||||
With ``ResolveTargetDocumentListener``, we are able to decouple our bundles so
|
||||
that they are usable by themselves and easier to maintain independently, while
|
||||
still being able to define relationships between different objects.
|
||||
@@ -0,0 +1,170 @@
|
||||
Simple Search Engine
|
||||
====================
|
||||
|
||||
It is very easy to implement a simple keyword search engine with MongoDB. Because of
|
||||
its flexible schema less nature we can store the keywords we want to search through directly
|
||||
on the document. MongoDB is capable of indexing the embedded documents so the results are fast
|
||||
and scalable.
|
||||
|
||||
Sample Model: Product
|
||||
---------------------
|
||||
|
||||
Imagine you had a ``Product`` document and you want to search the products by keywords. You can
|
||||
setup a document like the following with a ``$keywords`` property that is mapped as a collection:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
namespace Documents;
|
||||
|
||||
/** @Document */
|
||||
class Product
|
||||
{
|
||||
/** @Id */
|
||||
private $id;
|
||||
|
||||
/** @Field(type="string") */
|
||||
private $title;
|
||||
|
||||
/** @Field(type="collection") @Index */
|
||||
private $keywords = array();
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
Working with Keywords
|
||||
---------------------
|
||||
|
||||
Now, create a product and add some keywords:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$product = new Product();
|
||||
$product->setTitle('Nike Air Jordan 2011');
|
||||
$product->addKeyword('nike shoes');
|
||||
$product->addKeyword('jordan shoes');
|
||||
$product->addKeyword('air jordan');
|
||||
$product->addKeyword('shoes');
|
||||
$product->addKeyword('2011');
|
||||
|
||||
$dm->persist($product);
|
||||
$dm->flush();
|
||||
|
||||
The above example populates the keywords manually but you could very easily write some code which
|
||||
automatically generates your keywords from a string built by the Product that may include the title,
|
||||
description and other fields. You could also use a tool like the `AlchemyAPI`_ if you want to do
|
||||
some more intelligent keyword extraction.
|
||||
|
||||
Searching Keywords
|
||||
------------------
|
||||
|
||||
Searching the keywords in the ``Product`` collection is easy! You can run a query like the following
|
||||
to find documents that have at least one of the keywords:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$keywords = array('nike shoes', 'air jordan');
|
||||
|
||||
$qb = $dm->createQueryBuilder('Product')
|
||||
->field('keywords')->in($keywords);
|
||||
|
||||
You can make the query more strict by using the ``all()`` method instead of ``in()``:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$keywords = array('nike shoes', 'air jordan');
|
||||
|
||||
$qb = $dm->createQueryBuilder('Product')
|
||||
->field('keywords')->all($keywords);
|
||||
|
||||
The above query would only return products that have both of the keywords!
|
||||
|
||||
User Input
|
||||
~~~~~~~~~~
|
||||
|
||||
You can easily build keywords from a user search form by exploding whitespace and passing
|
||||
the results to your query. Here is an example:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$queryString = $_REQUEST['q'];
|
||||
$keywords = explode(' ', $queryString);
|
||||
|
||||
$qb = $dm->createQueryBuilder('Product')
|
||||
->field('keywords')->all($keywords);
|
||||
|
||||
Embedded Documents
|
||||
------------------
|
||||
|
||||
If you want to use an embedded document instead of just an array then you can. It will allow you to store
|
||||
additional information with each keyword, like its weight.
|
||||
|
||||
Definition
|
||||
~~~~~~~~~~
|
||||
|
||||
You can setup a ``Keyword`` document like the following:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/** @EmbeddedDocument */
|
||||
class Keyword
|
||||
{
|
||||
/** @Field(type="string") @Index */
|
||||
private $keyword;
|
||||
|
||||
/** @Field(type="int") */
|
||||
private $weight;
|
||||
|
||||
public function __construct($keyword, $weight)
|
||||
{
|
||||
$this->keyword = $keyword;
|
||||
$this->weight = $weight;
|
||||
}
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
Now you can embed the ``Keyword`` document many times in the ``Product``:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
namespace Documents;
|
||||
|
||||
/** @Document */
|
||||
class Product
|
||||
{
|
||||
// ...
|
||||
|
||||
/** @EmbedMany(targetDocument="Keyword") */
|
||||
private $keywords;
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
With the new embedded document to add a keyword to a ``Product`` the API is a little different,
|
||||
you would have to do the following:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$product->addKeyword(new Keyword('nike shoes', 1));
|
||||
|
||||
This is a very basic search engine example and can work for many small and simple applications. If you
|
||||
need better searching functionality you can look at integrating something like `Solr`_ in your project.
|
||||
|
||||
.. _AlchemyAPI: http://www.alchemyapi.com
|
||||
.. _Solr: http://lucene.apache.org/solr
|
||||
@@ -0,0 +1,224 @@
|
||||
Soft Delete Extension
|
||||
=====================
|
||||
|
||||
Sometimes you may not want to delete data from your database completely, but you want to
|
||||
disable or temporarily delete some records so they do not appear anymore in your frontend.
|
||||
Then, later you might want to restore that deleted data like it was never deleted.
|
||||
|
||||
This is possible with the ``SoftDelete`` extension which can be found on `github`_.
|
||||
|
||||
Installation
|
||||
------------
|
||||
|
||||
First you just need to get the code by cloning the `github`_ repository:
|
||||
|
||||
.. code-block:: console
|
||||
|
||||
$ git clone git://github.com/doctrine/mongodb-odm-softdelete.git
|
||||
|
||||
Now once you have the code you can setup the autoloader for it:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$classLoader = new ClassLoader('Doctrine\ODM\MongoDB\SoftDelete', 'mongodb-odm-softdelete/lib');
|
||||
$classLoader->register();
|
||||
|
||||
Setup
|
||||
-----
|
||||
|
||||
Now you can autoload the classes you need to setup the ``SoftDeleteManager`` instance you need to manage
|
||||
the soft delete state of your documents:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
use Doctrine\ODM\MongoDB\SoftDelete\Configuration;
|
||||
use Doctrine\ODM\MongoDB\SoftDelete\UnitOfWork;
|
||||
use Doctrine\ODM\MongoDB\SoftDelete\SoftDeleteManager;
|
||||
use Doctrine\Common\EventManager;
|
||||
|
||||
// $dm is a DocumentManager instance we should already have
|
||||
|
||||
$config = new Configuration();
|
||||
$evm = new EventManager();
|
||||
$sdm = new SoftDeleteManager($dm, $config, $evm);
|
||||
|
||||
SoftDeleteable Interface
|
||||
------------------------
|
||||
|
||||
In order for your documents to work with the SoftDelete functionality they must implement
|
||||
the ``SoftDeleteable`` interface:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
interface SoftDeleteable
|
||||
{
|
||||
function getDeletedAt();
|
||||
}
|
||||
|
||||
Example Implementation
|
||||
----------------------
|
||||
|
||||
An implementation might look like this in a ``User`` document:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
use Doctrine\ODM\MongoDB\SoftDelete\SoftDeleteable;
|
||||
|
||||
/** @mongodb:Document */
|
||||
class User implements SoftDeleteable
|
||||
{
|
||||
// ...
|
||||
|
||||
/** @mongodb:Date @mongodb:Index */
|
||||
private $deletedAt;
|
||||
|
||||
public function getDeletedAt()
|
||||
{
|
||||
return $this->deletedAt;
|
||||
}
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
Usage
|
||||
-----
|
||||
|
||||
Once you have the ``$sdm`` you can start managing the soft delete state of your documents:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$jwage = $dm->getRepository('User')->findOneByUsername('jwage');
|
||||
$fabpot = $dm->getRepository('User')->findOneByUsername('fabpot');
|
||||
$sdm->delete($jwage);
|
||||
$sdm->delete($fabpot);
|
||||
$sdm->flush();
|
||||
|
||||
The call to ``SoftDeleteManager#flush()`` would persist the deleted state to the database
|
||||
for all the documents it knows about and run a query like the following:
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
db.users.update({ _id : { $in : userIds }}, { $set : { deletedAt : new Date() } })
|
||||
|
||||
Now if we were to restore the documents:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$sdm->restore($jwage);
|
||||
$sdm->flush();
|
||||
|
||||
It would execute a query like the following:
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
db.users.update({ _id : { $in : userIds }}, { $unset : { deletedAt : true } })
|
||||
|
||||
Events
|
||||
------
|
||||
|
||||
We trigger some additional lifecycle events when documents are soft deleted and restored:
|
||||
|
||||
- Events::preSoftDelete
|
||||
- Events::postSoftDelete
|
||||
- Events::preRestore
|
||||
- Events::postRestore
|
||||
|
||||
Using the events is easy, just define a class like the following:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
class TestEventSubscriber implements \Doctrine\Common\EventSubscriber
|
||||
{
|
||||
public function preSoftDelete(LifecycleEventArgs $args)
|
||||
{
|
||||
$document = $args->getDocument();
|
||||
$sdm = $args->getSoftDeleteManager();
|
||||
}
|
||||
|
||||
public function getSubscribedEvents()
|
||||
{
|
||||
return array(Events::preSoftDelete);
|
||||
}
|
||||
}
|
||||
|
||||
Now we just need to add the event subscriber to the EventManager:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$eventSubscriber = new TestEventSubscriber();
|
||||
$evm->addEventSubscriber($eventSubscriber);
|
||||
|
||||
When we soft delete something the preSoftDelete() method will be invoked before any queries are sent
|
||||
to the database:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$sdm->delete($fabpot);
|
||||
$sdm->flush();
|
||||
|
||||
Cascading Soft Deletes
|
||||
----------------------
|
||||
|
||||
You can easily implement cascading soft deletes by using events in a certain way. Imagine you have
|
||||
a User and Post document and you want to soft delete a users posts when you delete him.
|
||||
|
||||
You just need to setup an event listener like the following:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
use Doctrine\Common\EventSubscriber;
|
||||
use Doctrine\ODM\MongoDB\SoftDelete\Event\LifecycleEventArgs;
|
||||
|
||||
class CascadingSoftDeleteListener implements EventSubscriber
|
||||
{
|
||||
public function preSoftDelete(LifecycleEventArgs $args)
|
||||
{
|
||||
$sdm = $args->getSoftDeleteManager();
|
||||
$document = $args->getDocument();
|
||||
if ($document instanceof User) {
|
||||
$sdm->deleteBy('Post', array('user.id' => $document->getId()));
|
||||
}
|
||||
}
|
||||
|
||||
public function preRestore(LifecycleEventArgs $args)
|
||||
{
|
||||
$sdm = $args->getSoftDeleteManager();
|
||||
$document = $args->getDocument();
|
||||
if ($document instanceof User) {
|
||||
$sdm->restoreBy('Post', array('user.id' => $document->getId()));
|
||||
}
|
||||
}
|
||||
|
||||
public function getSubscribedEvents()
|
||||
{
|
||||
return array(
|
||||
Events::preSoftDelete,
|
||||
Events::preRestore
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Now when you delete an instance of User it will also delete any Post documents where they
|
||||
reference the User being deleted. If you restore the User, his Post documents will also be restored.
|
||||
|
||||
.. _github: https://github.com/doctrine/mongodb-odm-softdelete
|
||||
@@ -0,0 +1,130 @@
|
||||
Validation of Documents
|
||||
=======================
|
||||
|
||||
.. sectionauthor:: Benjamin Eberlei <kontakt@beberlei.de>
|
||||
|
||||
Doctrine does not ship with any internal validators, the reason
|
||||
being that we think all the frameworks out there already ship with
|
||||
quite decent ones that can be integrated into your Domain easily.
|
||||
What we offer are hooks to execute any kind of validation.
|
||||
|
||||
.. note::
|
||||
|
||||
You don't need to validate your documents in the lifecycle
|
||||
events. Its only one of many options. Of course you can also
|
||||
perform validations in value setters or any other method of your
|
||||
documents that are used in your code.
|
||||
|
||||
Documents can register lifecycle event methods with Doctrine that
|
||||
are called on different occasions. For validation we would need to
|
||||
hook into the events called before persisting and updating. Even
|
||||
though we don't support validation out of the box, the
|
||||
implementation is even simpler than in Doctrine 1 and you will get
|
||||
the additional benefit of being able to re-use your validation in
|
||||
any other part of your domain.
|
||||
|
||||
Say we have an ``Order`` with several ``OrderLine`` instances. We
|
||||
never want to allow any customer to order for a larger sum than he
|
||||
is allowed to:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
class Order
|
||||
{
|
||||
public function assertCustomerAllowedBuying()
|
||||
{
|
||||
$orderLimit = $this->customer->getOrderLimit();
|
||||
|
||||
$amount = 0;
|
||||
foreach ($this->orderLines AS $line) {
|
||||
$amount += $line->getAmount();
|
||||
}
|
||||
|
||||
if ($amount > $orderLimit) {
|
||||
throw new CustomerOrderLimitExceededException();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Now this is some pretty important piece of business logic in your
|
||||
code, enforcing it at any time is important so that customers with
|
||||
a unknown reputation don't owe your business too much money.
|
||||
|
||||
We can enforce this constraint in any of the metadata drivers.
|
||||
First Annotations:
|
||||
|
||||
.. configuration-block::
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/** @Document @HasLifecycleCallbacks */
|
||||
class Order
|
||||
{
|
||||
/** @PrePersist @PreUpdate */
|
||||
public function assertCustomerAllowedBuying() {}
|
||||
}
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<doctrine-mapping>
|
||||
<document name="Order">
|
||||
<lifecycle-callbacks>
|
||||
<lifecycle-callback type="prePersist" method="assertCustomerallowedBuying" />
|
||||
<lifecycle-callback type="preUpdate" method="assertCustomerallowedBuying" />
|
||||
</lifecycle-callbacks>
|
||||
</document>
|
||||
</doctrine-mapping>
|
||||
|
||||
Now validation is performed whenever you call
|
||||
``DocumentManager#persist($order)`` or when you call
|
||||
``DocumentManager#flush()`` and an order is about to be updated. Any
|
||||
Exception that happens in the lifecycle callbacks will be cached by
|
||||
the DocumentManager and the current transaction is rolled back.
|
||||
|
||||
Of course you can do any type of primitive checks, not null,
|
||||
email-validation, string size, integer and date ranges in your
|
||||
validation callbacks.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/** @Document @HasLifecycleCallbacks */
|
||||
class Order
|
||||
{
|
||||
/** @PrePersist @PreUpdate */
|
||||
public function validate()
|
||||
{
|
||||
if (!($this->plannedShipDate instanceof DateTime)) {
|
||||
throw new ValidateException();
|
||||
}
|
||||
|
||||
if ($this->plannedShipDate->format('U') < time()) {
|
||||
throw new ValidateException();
|
||||
}
|
||||
|
||||
if ($this->customer == null) {
|
||||
throw new OrderRequiresCustomerException();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
What is nice about lifecycle events is, you can also re-use the
|
||||
methods at other places in your domain, for example in combination
|
||||
with your form library. Additionally there is no limitation in the
|
||||
number of methods you register on one particular event, i.e. you
|
||||
can register multiple methods for validation in "PrePersist" or
|
||||
"PreUpdate" or mix and share them in any combinations between those
|
||||
two events.
|
||||
|
||||
There is no limit to what you can and can't validate in
|
||||
"PrePersist" and "PreUpdate" as long as you don't create new document
|
||||
instances. This was already discussed in the previous blog post on
|
||||
the Versionable extension, which requires another type of event
|
||||
called "onFlush".
|
||||
|
||||
Further readings: :doc:`Lifecycle Events <../reference/events>`
|
||||
@@ -0,0 +1,107 @@
|
||||
Doctrine MongoDB ODM's documentation!
|
||||
=====================================
|
||||
|
||||
The Doctrine MongoDB ODM documentation is comprised of tutorials, a reference section and
|
||||
cookbook articles that explain different parts of the Object Document mapper.
|
||||
|
||||
Getting Help
|
||||
------------
|
||||
|
||||
If this documentation is not helping to answer questions you have about
|
||||
Doctrine MongoDB ODM don't panic. You can get help from different sources:
|
||||
|
||||
- The `Doctrine Mailing List <http://groups.google.com/group/doctrine-user>`_
|
||||
- Internet Relay Chat (IRC) in `#doctrine on Freenode <irc://irc.freenode.net/doctrine>`_
|
||||
- Report a bug on `GitHub <https://github.com/doctrine/mongodb-odm/issues>`_.
|
||||
- On `StackOverflow <http://stackoverflow.com/questions/tagged/doctrine-odm>`_
|
||||
|
||||
Getting Started
|
||||
---------------
|
||||
|
||||
:doc:`Getting Started <tutorials/getting-started>` |
|
||||
:doc:`Introduction <reference/introduction>` |
|
||||
:doc:`Architecture <reference/architecture>`
|
||||
|
||||
Mapping Objects onto a Database
|
||||
-------------------------------
|
||||
|
||||
* **Basic Reference**:
|
||||
:doc:`Objects and Fields <reference/basic-mapping>` |
|
||||
:doc:`References <reference/reference-mapping>` |
|
||||
:doc:`Bi-Directional References <reference/bidirectional-references>` |
|
||||
:doc:`Complex References <reference/complex-references>` |
|
||||
:doc:`Indexes <reference/indexes>` |
|
||||
:doc:`Inheritance <reference/inheritance-mapping>`
|
||||
|
||||
* **Embedded Data**:
|
||||
:doc:`Embedded <reference/embedded-mapping>` |
|
||||
:doc:`Trees <reference/trees>`
|
||||
|
||||
* **GridFS**:
|
||||
:doc:`Storing Files in GridFS <reference/storing-files-with-mongogridfs>`
|
||||
|
||||
* **Mapping Driver References**:
|
||||
:doc:`XML <reference/xml-mapping>` |
|
||||
:doc:`YAML <reference/yml-mapping>` |
|
||||
:doc:`Docblock Annotations <reference/annotations-reference>` |
|
||||
:doc:`Metadata Drivers <reference/metadata-drivers>`
|
||||
|
||||
Working with Objects
|
||||
--------------------
|
||||
|
||||
* **Basic Reference**:
|
||||
:doc:`Documents <reference/working-with-objects>` |
|
||||
:doc:`Repositories <reference/document-repositories>` |
|
||||
:doc:`Events <reference/events>` |
|
||||
:doc:`Migrations <reference/migrating-schemas>`
|
||||
|
||||
* **Query Reference**:
|
||||
:doc:`Query Builder API <reference/query-builder-api>` |
|
||||
:doc:`Aggregation Pipeline queries <reference/aggregation-builder>` |
|
||||
:doc:`Geo Spatial Queries <reference/geospatial-queries>` |
|
||||
:doc:`Slave Okay Queries <reference/slave-okay-queries>` |
|
||||
:doc:`Find and Update <reference/find-and-update>` |
|
||||
:doc:`Filters <reference/filters>` |
|
||||
:doc:`Priming References <reference/priming-references>` |
|
||||
:doc:`Eager Cursors <reference/eager-cursors>` |
|
||||
:doc:`Map Reduce <reference/map-reduce>`
|
||||
|
||||
Advanced Topics
|
||||
---------------
|
||||
|
||||
* **Collections**:
|
||||
:doc:`Capped Collections <reference/capped-collections>` |
|
||||
:doc:`Storage Strategies <reference/storage-strategies>` |
|
||||
:doc:`Custom Collections <reference/custom-collections>` |
|
||||
:doc:`Sharded setups <reference/sharding>`
|
||||
|
||||
* **Transactions and Concurrency**:
|
||||
:doc:`Transactions and Concurrency <reference/transactions-and-concurrency>`
|
||||
|
||||
* **Best Practices**:
|
||||
:doc:`Best Practices <reference/best-practices>`
|
||||
|
||||
* **Performance**:
|
||||
:doc:`Change Tracking Policies <reference/change-tracking-policies>`
|
||||
|
||||
* **Logging**:
|
||||
:doc:`Logging <reference/logging>`
|
||||
|
||||
Cookbook
|
||||
--------
|
||||
|
||||
* **Examples**:
|
||||
:doc:`Soft Delete <cookbook/soft-delete-extension>` |
|
||||
:doc:`Simple Search Engine <cookbook/simple-search-engine>`
|
||||
|
||||
* **Tricks**:
|
||||
:doc:`Blending ORM and MongoDB ODM <cookbook/blending-orm-and-mongodb-odm>` |
|
||||
:doc:`Mapping classes to ORM and ODM <cookbook/mapping-classes-to-orm-and-odm>`
|
||||
|
||||
* **Implementation**:
|
||||
:doc:`Array Access <cookbook/implementing-array-access-for-domain-objects>` |
|
||||
:doc:`Notify ChangeTracking Example <cookbook/implementing-the-notify-changetracking-policy>` |
|
||||
:doc:`Using Wakeup Or Clone <cookbook/implementing-wakeup-or-clone>` |
|
||||
:doc:`Validation <cookbook/validation-of-documents>` |
|
||||
:doc:`Simple Search Engine <cookbook/simple-search-engine>` |
|
||||
:doc:`Keeping Your Modules Independent <cookbook/resolve-target-document-listener>`
|
||||
@@ -0,0 +1,814 @@
|
||||
Aggregation builder
|
||||
===================
|
||||
|
||||
.. note::
|
||||
This feature is introduced in version 1.2
|
||||
|
||||
The aggregation framework provides an easy way to process records and return
|
||||
computed results. The aggregation builder helps to build complex aggregation
|
||||
pipelines.
|
||||
|
||||
Creating an Aggregation Builder
|
||||
-------------------------------
|
||||
|
||||
You can easily create a new ``Aggregation\Builder`` object with the
|
||||
``DocumentManager::createAggregationBuilder()`` method:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$builder = $dm->createAggregationBuilder(\Documents\User::class);
|
||||
|
||||
The first argument indicates the document for which you want to create the
|
||||
builder.
|
||||
|
||||
Adding pipeline stages
|
||||
~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
To add a pipeline stage to the builder, call the corresponding method on the
|
||||
builder object:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$builder = $dm->createAggregationBuilder(\Documents\Orders::class);
|
||||
$builder
|
||||
->match()
|
||||
->field('purchaseDate')
|
||||
->gte($from)
|
||||
->lt($to)
|
||||
->field('user')
|
||||
->references($user)
|
||||
->group()
|
||||
->field('id')
|
||||
->expression('$user')
|
||||
->field('numPurchases')
|
||||
->sum(1)
|
||||
->field('amount')
|
||||
->sum('$amount');
|
||||
|
||||
Just like the query builder, the aggregation builder takes care of converting
|
||||
``DateTime`` objects into ``MongoDate`` objects.
|
||||
|
||||
Nesting expressions
|
||||
~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
You can create more complex aggregation stages by using the ``expr()`` method in
|
||||
the aggregation builder.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$builder = $dm->createAggregationBuilder(\Documents\Orders::class);
|
||||
$builder
|
||||
->match()
|
||||
->field('purchaseDate')
|
||||
->gte($from)
|
||||
->lt($to)
|
||||
->field('user')
|
||||
->references($user)
|
||||
->group()
|
||||
->field('id')
|
||||
->expression(
|
||||
$builder->expr()
|
||||
->field('month')
|
||||
->month('purchaseDate')
|
||||
->field('year')
|
||||
->year('purchaseDate')
|
||||
)
|
||||
->field('numPurchases')
|
||||
->sum(1)
|
||||
->field('amount')
|
||||
->sum('$amount');
|
||||
|
||||
This aggregation would group all purchases by their month and year by projecting
|
||||
those values into an embedded object for the ``id`` field. For example:
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
{
|
||||
_id: {
|
||||
month: 1,
|
||||
year: 2016
|
||||
},
|
||||
numPurchases: 1,
|
||||
amount: 27.89
|
||||
}
|
||||
|
||||
Executing an aggregation pipeline
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
You can execute a pipeline using the ``execute()`` method. This will run the
|
||||
aggregation pipeline and return a cursor for you to iterate over the results:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$builder = $dm->createAggregationBuilder(\Documents\User::class);
|
||||
$result = $builder->execute();
|
||||
|
||||
If you instead want to look at the built aggregation pipeline, call the
|
||||
``Builder::getPipeline()`` method.
|
||||
|
||||
Hydration
|
||||
~~~~~~~~~
|
||||
|
||||
By default, aggregation results are returned as PHP arrays. This is because the
|
||||
result of an aggregation pipeline may look completely different from the source
|
||||
document. In order to get hydrated aggregation results, you first have to map
|
||||
a ``QueryResultDocument``. These are written like regular mapped documents, but
|
||||
they can't be persisted to the database.
|
||||
|
||||
.. configuration-block::
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
namespace Documents;
|
||||
|
||||
/** @QueryResultDocument */
|
||||
class UserPurchases
|
||||
{
|
||||
/** @ReferenceOne(targetDocument="User", name="_id") */
|
||||
private $user;
|
||||
|
||||
/** @Field(type="int") */
|
||||
private $numPurchases;
|
||||
|
||||
/** @Field(type="float") */
|
||||
private $amount;
|
||||
}
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<doctrine-mongo-mapping xmlns="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping
|
||||
http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping.xsd">
|
||||
<query-result-document name="Documents\UserPurchases">
|
||||
<field fieldName="numPurchases" type="int" />
|
||||
<field fieldName="amount" type="float" />
|
||||
<reference-one field="user" target-document="Documents\User" name="_id" />
|
||||
</query-result-document>
|
||||
</doctrine-mongo-mapping>
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
Documents\User:
|
||||
type: queryResultDocument
|
||||
fields:
|
||||
user:
|
||||
name: _id
|
||||
targetDocument: Documents\User
|
||||
numPurchases:
|
||||
type: int
|
||||
amount:
|
||||
type: float
|
||||
|
||||
Once you have mapped the document, use the ``hydrate()`` method to tell the
|
||||
aggregation builder about this document:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$builder = $dm->createAggregationBuilder(\Documents\Orders::class);
|
||||
$builder
|
||||
->hydrate(\Documents\UserPurchases::class)
|
||||
->match()
|
||||
->field('purchaseDate')
|
||||
->gte($from)
|
||||
->lt($to)
|
||||
->field('user')
|
||||
->references($user)
|
||||
->group()
|
||||
->field('id')
|
||||
->expression('$user')
|
||||
->field('numPurchases')
|
||||
->sum(1)
|
||||
->field('amount')
|
||||
->sum('$amount');
|
||||
|
||||
When you run the queries, all results will be returned as instances of the
|
||||
specified document.
|
||||
|
||||
.. note::
|
||||
|
||||
Query result documents can use all features regular documents can use: you
|
||||
can map embedded documents, define references, and even use discriminators
|
||||
to get different result documents according to the aggregation result.
|
||||
|
||||
Aggregation pipeline stages
|
||||
---------------------------
|
||||
|
||||
MongoDB provides the following aggregation pipeline stages:
|
||||
|
||||
- `$addFields <https://docs.mongodb.com/manual/reference/operator/aggregation/addFields/>`_
|
||||
- `$bucket <https://docs.mongodb.com/manual/reference/operator/aggregation/bucket/>`_
|
||||
- `$bucketAuto <https://docs.mongodb.com/manual/reference/operator/aggregation/bucketAuto/>`_
|
||||
- `$collStats <https://docs.mongodb.com/manual/reference/operator/aggregation/collStats/>`_
|
||||
- `$count <https://docs.mongodb.com/manual/reference/operator/aggregation/count/>`_
|
||||
- `$facet <https://docs.mongodb.com/manual/reference/operator/aggregation/facet/>`_
|
||||
- `$geoNear <https://docs.mongodb.com/manual/reference/operator/aggregation/geoNear/>`_
|
||||
- `$graphLookup <https://docs.mongodb.com/manual/reference/operator/aggregation/graphLookup/>`_
|
||||
- `$group <https://docs.mongodb.com/manual/reference/operator/aggregation/group/>`_
|
||||
- `$indexStats <https://docs.mongodb.com/manual/reference/operator/aggregation/indexStats/>`_
|
||||
- `$limit <https://docs.mongodb.com/manual/reference/operator/aggregation/limit/>`_
|
||||
- `$lookup <https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/>`_
|
||||
- `$match <https://docs.mongodb.com/manual/reference/operator/aggregation/match/>`_
|
||||
- `$out <https://docs.mongodb.com/manual/reference/operator/aggregation/out/>`_
|
||||
- `$project <https://docs.mongodb.com/manual/reference/operator/aggregation/project/>`_
|
||||
- `$redact <https://docs.mongodb.com/manual/reference/operator/aggregation/redact/>`_
|
||||
- `$replaceRoot <https://docs.mongodb.com/manual/reference/operator/aggregation/replaceRoot/>`_
|
||||
- `$sample <https://docs.mongodb.com/manual/reference/operator/aggregation/sample/>`_
|
||||
- `$skip <https://docs.mongodb.com/manual/reference/operator/aggregation/skip/>`_
|
||||
- `$sort <https://docs.mongodb.com/manual/reference/operator/aggregation/project/>`_
|
||||
- `$sortByCount <https://docs.mongodb.com/manual/reference/operator/aggregation/sortByCount/>`_
|
||||
- `$unwind <https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/>`_
|
||||
|
||||
.. note::
|
||||
|
||||
The ``$lookup``, ``$sample`` and ``$indexStats`` stages were added in MongoDB
|
||||
3.2. The ``$addFields``, ``$bucket``, ``$bucketAuto``, ``$sortByCount``,
|
||||
``$replaceRoot``, ``$facet``, ``$graphLookup``, ``$coun`` and ``$collStats``
|
||||
stages were added in MongoDB 3.4.
|
||||
|
||||
$addFields
|
||||
~~~~~~~~~~
|
||||
|
||||
Adds new fields to documents. ``$addFields`` outputs documents that contain all
|
||||
existing fields from the input documents and newly added fields.
|
||||
|
||||
The ``$addFields`` stage is equivalent to a ``$project`` stage that explicitly
|
||||
specifies all existing fields in the input documents and adds the new fields.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$builder = $dm->createAggregationBuilder(\Documents\Orders::class);
|
||||
$builder
|
||||
->addFields()
|
||||
->field('purchaseYear')
|
||||
->year('$purchaseDate');
|
||||
|
||||
$bucket
|
||||
~~~~~~~
|
||||
|
||||
Categorizes incoming documents into groups, called buckets, based on a specified
|
||||
expression and bucket boundaries.
|
||||
|
||||
Each bucket is represented as a document in the output. The document for each
|
||||
bucket contains an _id field, whose value specifies the inclusive lower bound of
|
||||
the bucket and a count field that contains the number of documents in the bucket.
|
||||
The count field is included by default when the output is not specified.
|
||||
|
||||
``$bucket`` only produces output documents for buckets that contain at least one
|
||||
input document.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$builder = $dm->createAggregationBuilder(\Documents\Orders::class);
|
||||
$builder
|
||||
->bucket()
|
||||
->groupBy('$itemCount')
|
||||
->boundaries(1, 2, 3, 4, 5, '5+')
|
||||
->defaultBucket('5+')
|
||||
->output()
|
||||
->field('lowestValue')
|
||||
->min('$value')
|
||||
->field('highestValue')
|
||||
->max('$value')
|
||||
;
|
||||
|
||||
$bucketAuto
|
||||
~~~~~~~~~~~
|
||||
|
||||
Similar to ``$bucket``, except that boundaries are automatically determined in
|
||||
an attempt to evenly distribute the documents into the specified number of
|
||||
buckets.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$builder = $dm->createAggregationBuilder(\Documents\Orders::class);
|
||||
$builder
|
||||
->bucketAuto()
|
||||
->groupBy('$itemCount')
|
||||
->buckets(5)
|
||||
->output()
|
||||
->field('lowestValue')
|
||||
->min('$value')
|
||||
->field('highestValue')
|
||||
->max('$value')
|
||||
;
|
||||
|
||||
$collStats
|
||||
~~~~~~~~~~
|
||||
|
||||
The ``$collStats`` stage returns statistics regarding a collection or view.
|
||||
|
||||
$count
|
||||
~~~~~~
|
||||
|
||||
Returns a document that contains a count of the number of documents input to the
|
||||
stage.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$builder = $dm->createAggregationBuilder(\Documents\Orders::class);
|
||||
$builder
|
||||
->match()
|
||||
->field('itemCount')
|
||||
->eq(1)
|
||||
->count('numSingleItemOrders')
|
||||
;
|
||||
|
||||
The example above returns a single document with the ``numSingleItemOrders``
|
||||
containing the number of orders found.
|
||||
|
||||
$facet
|
||||
~~~~~~
|
||||
|
||||
Processes multiple aggregation pipelines within a single stage on the same set
|
||||
of input documents. Each sub-pipeline has its own field in the output document
|
||||
where its results are stored as an array of documents.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$builder = $dm->createAggregationBuilder(\Documents\Orders::class);
|
||||
$builder
|
||||
->facet()
|
||||
->field('groupedByItemCount')
|
||||
->pipeline(
|
||||
$dm->createAggregationBuilder(\Documents\Orders::class)->group()
|
||||
->field('id')
|
||||
->expression('$itemCount')
|
||||
->field('lowestValue')
|
||||
->min('$value')
|
||||
->field('highestValue')
|
||||
->max('$value')
|
||||
->field('totalValue')
|
||||
->sum('$value')
|
||||
->field('averageValue')
|
||||
->avg('$value')
|
||||
)
|
||||
->field('groupedByYear')
|
||||
->pipeline(
|
||||
$dm->createAggregationBuilder(\Documents\Orders::class)->group()
|
||||
->field('id')
|
||||
->year('purchaseDate')
|
||||
->field('lowestValue')
|
||||
->min('$value')
|
||||
->field('highestValue')
|
||||
->max('$value')
|
||||
->field('totalValue')
|
||||
->sum('$value')
|
||||
->field('averageValue')
|
||||
->avg('$value')
|
||||
)
|
||||
;
|
||||
|
||||
$geoNear
|
||||
~~~~~~~~
|
||||
|
||||
The ``$geoNear`` stage finds and outputs documents in order of nearest to
|
||||
farthest from a specified point.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$builder = $this->dm->createAggregationBuilder(\Documents\City::class);
|
||||
$builder
|
||||
->geoNear(120, 40)
|
||||
->spherical(true)
|
||||
->distanceField('distance')
|
||||
// Convert radians to kilometers (use 3963.192 for miles)
|
||||
->distanceMultiplier(6378.137);
|
||||
|
||||
.. note::
|
||||
|
||||
The ``$geoNear`` stage must be the first stage in the pipeline and the
|
||||
collection must contain a single geospatial index. You must include the
|
||||
``distanceField`` option for the stage to work.
|
||||
|
||||
$graphLookup
|
||||
~~~~~~~~~~~~
|
||||
|
||||
Performs a recursive search on a collection, with options for restricting the
|
||||
search by recursion depth and query filter. The ``$graphLookup`` stage can be
|
||||
used to resolve association graphs and flatten them into a single list.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$builder = $this->dm->createAggregationBuilder(\Documents\Traveller::class);
|
||||
$builder
|
||||
->graphLookup('nearestAirport')
|
||||
->connectFromField('connections')
|
||||
->maxDepth(2)
|
||||
->depthField('numConnections')
|
||||
->alias('destinations');
|
||||
|
||||
.. note::
|
||||
|
||||
The target document of the reference used in ``connectFromField`` must be
|
||||
the very same document. The aggregation builder will throw an exception if
|
||||
you try to resolve a different document.
|
||||
|
||||
.. note::
|
||||
|
||||
Due to a limitation in MongoDB, the ``$graphLookup`` stage can not be used
|
||||
with references that are stored as DBRef. To use references in a
|
||||
``$graphLookup`` stage, store the reference as ID or ``ref``. This is
|
||||
explained in the :doc:`Reference mapping <reference-mapping>` chapter.
|
||||
|
||||
.. _aggregation_builder_group:
|
||||
|
||||
$group
|
||||
~~~~~~
|
||||
|
||||
The ``$group`` stage is used to do calculations based on previously matched
|
||||
documents:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$builder = $dm->createAggregationBuilder(\Documents\Orders::class);
|
||||
$builder
|
||||
->match()
|
||||
->field('user')
|
||||
->references($user)
|
||||
->group()
|
||||
->field('id')
|
||||
->expression(
|
||||
$builder->expr()
|
||||
->field('month')
|
||||
->month('purchaseDate')
|
||||
->field('year')
|
||||
->year('purchaseDate')
|
||||
)
|
||||
->field('numPurchases')
|
||||
->sum(1)
|
||||
->field('amount')
|
||||
->sum('$amount');
|
||||
|
||||
$indexStats
|
||||
~~~~~~~~~~~
|
||||
|
||||
The ``$indexStats`` stage returns statistics regarding the use of each index for
|
||||
the collection. More information can be found in the `official Documentation <https://docs.mongodb.com/manual/reference/operator/aggregation/indexStats/>`_
|
||||
|
||||
$lookup
|
||||
~~~~~~~
|
||||
|
||||
.. note::
|
||||
|
||||
The ``$lookup`` stage was introduced in MongoDB 3.2. Using it on older servers
|
||||
will result in an error.
|
||||
|
||||
The ``$lookup`` stage is used to fetch documents from different collections in
|
||||
pipeline stages. Take the following relationship for example:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @ReferenceMany(
|
||||
* targetDocument="Documents\Item",
|
||||
* cascade="all",
|
||||
* storeAs="id"
|
||||
* )
|
||||
*/
|
||||
private $items;
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$builder = $dm->createAggregationBuilder(\Documents\Orders::class);
|
||||
$builder
|
||||
->lookup('items')
|
||||
->alias('items');
|
||||
|
||||
The resulting array will contain all matched item documents in an array. This has
|
||||
to be considered when looking up one-to-one relationships:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @ReferenceOne(
|
||||
* targetDocument="Documents\Item",
|
||||
* cascade="all",
|
||||
* storeAs="id"
|
||||
* )
|
||||
*/
|
||||
private $items;
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$builder = $dm->createAggregationBuilder(\Documents\Orders::class);
|
||||
$builder
|
||||
->lookup('user')
|
||||
->alias('user')
|
||||
->unwind('$user');
|
||||
|
||||
MongoDB will always return an array, even if the lookup only returned a single
|
||||
document. Thus, when looking up one-to-one references the result must be flattened
|
||||
using the ``$unwind`` operator.
|
||||
|
||||
.. note::
|
||||
|
||||
Due to a limitation in MongoDB, the ``$lookup`` stage can not be used with
|
||||
references that are stored as DBRef. To use references in a ``$lookup``
|
||||
stage, store the reference as ID or ``ref``. This is explained in the
|
||||
:doc:`Reference mapping <reference-mapping>` chapter.
|
||||
|
||||
You can also configure your lookup manually if you don't have it mapped in your
|
||||
document:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$builder = $dm->createAggregationBuilder(\Documents\Orders::class);
|
||||
$builder
|
||||
->lookup('unmappedCollection')
|
||||
->localField('_id')
|
||||
->foreignField('userId')
|
||||
->alias('items');
|
||||
|
||||
$match
|
||||
~~~~~~
|
||||
|
||||
The ``$match`` stage lets you filter documents according to certain criteria. It
|
||||
works just like the query builder:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$builder = $dm->createAggregationBuilder(\Documents\Orders::class);
|
||||
$builder
|
||||
->match()
|
||||
->field('purchaseDate')
|
||||
->gte($from)
|
||||
->lt($to)
|
||||
->field('user')
|
||||
->references($user);
|
||||
|
||||
You can also use fields defined in previous stages:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$builder = $dm->createAggregationBuilder(\Documents\Orders::class);
|
||||
$builder
|
||||
->project()
|
||||
->excludeIdField()
|
||||
->includeFields(['purchaseDate', 'user'])
|
||||
->field('purchaseYear')
|
||||
->year('$purchaseDate')
|
||||
->match()
|
||||
->field('purchaseYear')
|
||||
->equals(2016);
|
||||
|
||||
$out
|
||||
~~~~
|
||||
|
||||
The ``$out`` stage is used to store the result of the aggregation pipeline in a
|
||||
collection instead of returning an iterable cursor of results. This must be the
|
||||
last stage in an aggregation pipeline.
|
||||
|
||||
If the collection specified by the ``$out`` operation already exists, then upon
|
||||
completion of the aggregation, the existing collection is atomically replaced.
|
||||
Any indexes that existed on the collection are left intact. If the aggregation
|
||||
fails, the ``$out`` operation does not remove the data from an existing
|
||||
collection.
|
||||
|
||||
.. note::
|
||||
|
||||
The aggregation pipeline will fail to complete if the result would violate
|
||||
any unique index constraints, including those on the ``id`` field.
|
||||
|
||||
$project
|
||||
~~~~~~~~
|
||||
|
||||
The ``$project`` stage lets you reshape the current document or define a completely
|
||||
new one:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$builder = $dm->createAggregationBuilder(\Documents\Orders::class);
|
||||
$builder
|
||||
->project()
|
||||
->excludeIdField()
|
||||
->includeFields(['purchaseDate', 'user'])
|
||||
->field('purchaseYear')
|
||||
->year('$purchaseDate');
|
||||
|
||||
$redact
|
||||
~~~~~~~
|
||||
|
||||
The redact stage can be used to restrict the contents of the documents based on
|
||||
information stored in the documents themselves. You can read more about the
|
||||
``$redact`` stage in the `MongoDB documentation <https://docs.mongodb.com/manual/reference/operator/aggregation/redact/>`_.
|
||||
|
||||
The following example taken from the official documentation checks the ``level``
|
||||
field on all document levels and evaluates it to grant or deny access:
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
{
|
||||
_id: 1,
|
||||
level: 1,
|
||||
acct_id: "xyz123",
|
||||
cc: {
|
||||
level: 5,
|
||||
type: "yy",
|
||||
num: 000000000000,
|
||||
exp_date: ISODate("2015-11-01T00:00:00.000Z"),
|
||||
billing_addr: {
|
||||
level: 5,
|
||||
addr1: "123 ABC Street",
|
||||
city: "Some City"
|
||||
},
|
||||
shipping_addr: [
|
||||
{
|
||||
level: 3,
|
||||
addr1: "987 XYZ Ave",
|
||||
city: "Some City"
|
||||
},
|
||||
{
|
||||
level: 3,
|
||||
addr1: "PO Box 0123",
|
||||
city: "Some City"
|
||||
}
|
||||
]
|
||||
},
|
||||
status: "A"
|
||||
}
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$builder = $dm->createAggregationBuilder(\Documents\Orders::class);
|
||||
$builder
|
||||
->redact()
|
||||
->cond(
|
||||
$builder->expr()->gte('$$level', 5),
|
||||
'$$PRUNE',
|
||||
'$$DESCEND'
|
||||
)
|
||||
|
||||
$replaceRoot
|
||||
~~~~~~~~~~~~
|
||||
|
||||
Promotes a specified document to the top level and replaces all other fields.
|
||||
The operation replaces all existing fields in the input document, including the
|
||||
``_id`` field. You can promote an existing embedded document to the top level,
|
||||
or create a new document for promotion.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$builder = $dm->createAggregationBuilder(\Documents\Orders::class);
|
||||
$builder
|
||||
->replaceRoot('$embeddedField');
|
||||
|
||||
$builder = $dm->createAggregationBuilder(\Documents\Orders::class);
|
||||
$builder
|
||||
->replaceRoot()
|
||||
->field('averagePricePerItem')
|
||||
->divide('$value', '$itemCount');
|
||||
|
||||
$sample
|
||||
~~~~~~~
|
||||
|
||||
The sample stage can be used to randomly select a subset of documents in the
|
||||
aggregation pipeline. It behaves like the ``$limit`` stage, but instead of
|
||||
returning the first ``n`` documents it returns ``n`` random documents.
|
||||
|
||||
$sort, $limit and $skip
|
||||
~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
The ``$sort``, ``$limit`` and ``$skip`` stages behave like the corresponding
|
||||
query options, allowing you to control the order and subset of results returned
|
||||
by the aggregation pipeline.
|
||||
|
||||
$sortByCount
|
||||
~~~~~~~~~~~~
|
||||
|
||||
Groups incoming documents based on the value of a specified expression, then
|
||||
computes the count of documents in each distinct group.
|
||||
|
||||
Each output document contains two fields: an _id field containing the distinct
|
||||
grouping value, and a count field containing the number of documents belonging
|
||||
to that grouping or category.
|
||||
|
||||
The documents are sorted by count in descending order.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$builder = $dm->createAggregationBuilder(\Documents\Orders::class);
|
||||
$builder->sortByCount('$items');
|
||||
|
||||
The example above is equivalent to the following pipeline:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$builder = $dm->createAggregationBuilder(\Documents\Orders::class);
|
||||
$builder
|
||||
->group()
|
||||
->field('_id')
|
||||
->expression('$items')
|
||||
->field('count')
|
||||
->sum(1)
|
||||
->sort(['count' => -1])
|
||||
;
|
||||
|
||||
$unwind
|
||||
~~~~~~~
|
||||
|
||||
The ``$unwind`` stage flattens an array in a document, returning a copy for each
|
||||
item. Take this sample document:
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
{
|
||||
_id: {
|
||||
month: 1,
|
||||
year: 2016
|
||||
},
|
||||
purchaseDates: [
|
||||
'2016-01-07',
|
||||
'2016-03-10',
|
||||
'2016-06-25'
|
||||
]
|
||||
}
|
||||
|
||||
To flatten the ``purchaseDates`` array, we would apply the following pipeline
|
||||
stage:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$builder = $dm->createAggregationBuilder(\Documents\User::class);
|
||||
$builder->unwind('$purchaseDates');
|
||||
|
||||
The stage would return three documents, each containing a single purchase date:
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
{
|
||||
_id: {
|
||||
month: 1,
|
||||
year: 2016
|
||||
},
|
||||
purchaseDates: '2016-01-07'
|
||||
},
|
||||
{
|
||||
_id: {
|
||||
month: 1,
|
||||
year: 2016
|
||||
},
|
||||
purchaseDates: '2016-03-10'
|
||||
},
|
||||
{
|
||||
_id: {
|
||||
month: 1,
|
||||
year: 2016
|
||||
},
|
||||
purchaseDates: '2016-06-25'
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
Architecture
|
||||
============
|
||||
|
||||
This chapter gives an overview of the overall architecture,
|
||||
terminology and constraints of Doctrine. It is recommended to
|
||||
read this chapter carefully.
|
||||
|
||||
Documents
|
||||
---------
|
||||
|
||||
A document is a lightweight, persistent domain object. A document can
|
||||
be any regular PHP class observing the following restrictions:
|
||||
|
||||
- A document class must not be final or contain final methods.
|
||||
- All persistent properties/field of any document class should
|
||||
always be private or protected, otherwise lazy-loading might not
|
||||
work as expected.
|
||||
- A document class must not implement ``__clone`` or
|
||||
:doc:`do so safely <../cookbook/implementing-wakeup-or-clone>`.
|
||||
- A document class must not implement ``__wakeup`` or
|
||||
:doc:`do so safely <../cookbook/implementing-wakeup-or-clone>`.
|
||||
Also consider implementing
|
||||
`Serializable <http://de3.php.net/manual/en/class.serializable.php>`_
|
||||
instead.
|
||||
- Any two document classes in a class hierarchy that inherit
|
||||
directly or indirectly from one another must not have a mapped
|
||||
property with the same name. That is, if B inherits from A then B
|
||||
must not have a mapped field with the same name as an already
|
||||
mapped field that is inherited from A.
|
||||
|
||||
Documents support inheritance, polymorphic associations, and
|
||||
polymorphic queries. Both abstract and concrete classes can be
|
||||
documents. Documents may extend non-document classes as well as document
|
||||
classes, and non-document classes may extend document classes.
|
||||
|
||||
.. tip::
|
||||
|
||||
The constructor of a document is only ever invoked when
|
||||
*you* construct a new instance with the *new* keyword. Doctrine
|
||||
never calls document constructors, thus you are free to use them as
|
||||
you wish and even have it require arguments of any type.
|
||||
|
||||
Document states
|
||||
~~~~~~~~~~~~~~~
|
||||
|
||||
A document instance can be characterized as being NEW, MANAGED, DETACHED or REMOVED.
|
||||
|
||||
- A NEW document instance has no persistent identity, and is not yet
|
||||
associated with a DocumentManager and a UnitOfWork (i.e. those just
|
||||
created with the "new" operator).
|
||||
- A MANAGED document instance is an instance with a persistent
|
||||
identity that is associated with a DocumentManager and whose
|
||||
persistence is thus managed.
|
||||
- A DETACHED document instance is an instance with a persistent
|
||||
identity that is not (or no longer) associated with a
|
||||
DocumentManager and a UnitOfWork.
|
||||
- A REMOVED document instance is an instance with a persistent
|
||||
identity, associated with a DocumentManager, that will be removed
|
||||
from the database upon transaction commit.
|
||||
|
||||
Persistent fields
|
||||
~~~~~~~~~~~~~~~~~
|
||||
|
||||
The persistent state of a document is represented by instance
|
||||
variables. An instance variable must be directly accessed only from
|
||||
within the methods of the document by the document instance itself.
|
||||
Instance variables must not be accessed by clients of the document.
|
||||
The state of the document is available to clients only through the
|
||||
document's methods, i.e. accessor methods (getter/setter methods) or
|
||||
other business methods.
|
||||
|
||||
Collection-valued persistent fields and properties must be defined
|
||||
in terms of the ``Doctrine\Common\Collections\Collection``
|
||||
interface. The collection implementation type may be used by the
|
||||
application to initialize fields or properties before the document is
|
||||
made persistent. Once the document becomes managed (or detached),
|
||||
subsequent access must be through the interface type.
|
||||
|
||||
Serializing documents
|
||||
~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Serializing documents can be problematic and is not really
|
||||
recommended, at least not as long as a document instance still holds
|
||||
references to proxy objects or is still managed by an
|
||||
DocumentManager. If you intend to serialize (and unserialize) document
|
||||
instances that still hold references to proxy objects you may run
|
||||
into problems with private properties because of technical
|
||||
limitations. Proxy objects implement ``__sleep`` and it is not
|
||||
possible for ``__sleep`` to return names of private properties in
|
||||
parent classes. On the other hand it is not a solution for proxy
|
||||
objects to implement ``Serializable`` because Serializable does not
|
||||
work well with any potential cyclic object references (at least we
|
||||
did not find a way yet, if you did, please contact us).
|
||||
|
||||
The DocumentManager
|
||||
-------------------
|
||||
|
||||
The ``DocumentManager`` class is a central access point to the ODM
|
||||
functionality provided by Doctrine. The ``DocumentManager`` API is
|
||||
used to manage the persistence of your objects and to query for
|
||||
persistent objects.
|
||||
|
||||
Transactional write-behind
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
An ``DocumentManager`` and the underlying ``UnitOfWork`` employ a
|
||||
strategy called "transactional write-behind" that delays the
|
||||
execution of query statements in order to execute them in the most
|
||||
efficient way and to execute them at the end of a transaction so
|
||||
that all write locks are quickly released. You should see Doctrine
|
||||
as a tool to synchronize your in-memory objects with the database
|
||||
in well defined units of work. Work with your objects and modify
|
||||
them as usual and when you're done call ``DocumentManager#flush()``
|
||||
to make your changes persistent.
|
||||
|
||||
The Unit of Work
|
||||
~~~~~~~~~~~~~~~~
|
||||
|
||||
Internally an ``DocumentManager`` uses a ``UnitOfWork``, which is a
|
||||
typical implementation of the
|
||||
`Unit of Work pattern <http://martinfowler.com/eaaCatalog/unitOfWork.html>`_,
|
||||
to keep track of all the things that need to be done the next time
|
||||
``flush`` is invoked. You usually do not directly interact with a
|
||||
``UnitOfWork`` but with the ``DocumentManager`` instead.
|
||||
@@ -0,0 +1,621 @@
|
||||
Basic Mapping
|
||||
=============
|
||||
|
||||
This chapter explains the basic mapping of objects and properties.
|
||||
Mapping of references and embedded documents will be covered in the
|
||||
next chapter "Reference Mapping".
|
||||
|
||||
Mapping Drivers
|
||||
---------------
|
||||
|
||||
Doctrine provides several different ways for specifying object
|
||||
document mapping metadata:
|
||||
|
||||
- Docblock Annotations
|
||||
- XML
|
||||
- YAML
|
||||
- Raw PHP Code
|
||||
|
||||
.. note::
|
||||
|
||||
If you're wondering which mapping driver gives the best
|
||||
performance, the answer is: None. Once the metadata of a class has
|
||||
been read from the source (annotations, xml or yaml) it is stored
|
||||
in an instance of the
|
||||
``Doctrine\ODM\MongoDB\Mapping\ClassMetadata`` class and these
|
||||
instances are stored in the metadata cache. Therefore at the end of
|
||||
the day all drivers perform equally well. If you're not using a
|
||||
metadata cache (not recommended!) then the XML driver might have a
|
||||
slight edge in performance due to the powerful native XML support
|
||||
in PHP.
|
||||
|
||||
Introduction to Docblock Annotations
|
||||
------------------------------------
|
||||
|
||||
You've probably used docblock annotations in some form already,
|
||||
most likely to provide documentation metadata for a tool like
|
||||
``PHPDocumentor`` (@author, @link, ...). Docblock annotations are a
|
||||
tool to embed metadata inside the documentation section which can
|
||||
then be processed by some tool. Doctrine generalizes the concept of
|
||||
docblock annotations so that they can be used for any kind of
|
||||
metadata and so that it is easy to define new docblock annotations.
|
||||
In order to allow more involved annotation values and to reduce the
|
||||
chances of clashes with other docblock annotations, the Doctrine
|
||||
docblock annotations feature an alternative syntax that is heavily
|
||||
inspired by the Annotation syntax introduced in Java 5.
|
||||
|
||||
The implementation of these enhanced docblock annotations is
|
||||
located in the ``Doctrine\Common\Annotations`` namespace and
|
||||
therefore part of the Common package. Doctrine docblock annotations
|
||||
support namespaces and nested annotations among other things. The
|
||||
Doctrine MongoDB ODM defines its own set of docblock annotations
|
||||
for supplying object document mapping metadata.
|
||||
|
||||
.. note::
|
||||
|
||||
If you're not comfortable with the concept of docblock
|
||||
annotations, don't worry, as mentioned earlier Doctrine 2 provides
|
||||
XML and YAML alternatives and you could easily implement your own
|
||||
favorite mechanism for defining ORM metadata.
|
||||
|
||||
Persistent classes
|
||||
------------------
|
||||
|
||||
In order to mark a class for object-relational persistence it needs
|
||||
to be designated as a document. This can be done through the
|
||||
``@Document`` marker annotation.
|
||||
|
||||
.. configuration-block::
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
namespace Documents;
|
||||
|
||||
/** @Document */
|
||||
class User
|
||||
{
|
||||
}
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<doctrine-mongo-mapping xmlns="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping
|
||||
http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping.xsd">
|
||||
<document name="Documents\User">
|
||||
</document>
|
||||
</doctrine-mongo-mapping>
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
Documents\User:
|
||||
type: document
|
||||
|
||||
By default, the document will be persisted to a database named
|
||||
doctrine and a collection with the same name as the class name. In
|
||||
order to change that, you can use the ``db`` and ``collection``
|
||||
option as follows:
|
||||
|
||||
.. configuration-block::
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
namespace Documents;
|
||||
|
||||
/** @Document(db="my_db", collection="users") */
|
||||
class User
|
||||
{
|
||||
}
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<doctrine-mongo-mapping xmlns="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping
|
||||
http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping.xsd">
|
||||
<document name="Documents\User" db="my_db" collection="users">
|
||||
</document>
|
||||
</doctrine-mongo-mapping>
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
Documents\User:
|
||||
type: document
|
||||
db: my_db
|
||||
collection: users
|
||||
|
||||
Now instances of ``Documents\User`` will be persisted into a
|
||||
collection named ``users`` in the database ``my_db``.
|
||||
|
||||
If you want to omit the db attribute you can configure the default db
|
||||
to use with the ``setDefaultDB`` method:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$config->setDefaultDB('my_db');
|
||||
|
||||
.. _doctrine_mapping_types:
|
||||
|
||||
Doctrine Mapping Types
|
||||
----------------------
|
||||
|
||||
A Doctrine Mapping Type defines the mapping between a PHP type and
|
||||
an MongoDB type. You can even write your own custom mapping types.
|
||||
|
||||
Here is a quick overview of the built-in mapping types:
|
||||
|
||||
- ``bin``
|
||||
- ``bin_bytearray``
|
||||
- ``bin_custom``
|
||||
- ``bin_func``
|
||||
- ``bin_md5``
|
||||
- ``bin_uuid``
|
||||
- ``boolean``
|
||||
- ``collection``
|
||||
- ``custom_id``
|
||||
- ``date``
|
||||
- ``file``
|
||||
- ``float``
|
||||
- ``hash``
|
||||
- ``id``
|
||||
- ``int``
|
||||
- ``key``
|
||||
- ``object_id``
|
||||
- ``raw``
|
||||
- ``string``
|
||||
- ``timestamp``
|
||||
|
||||
You can read more about the available MongoDB types on `php.net <http://us.php.net/manual/en/mongo.types.php>`_.
|
||||
|
||||
.. note::
|
||||
|
||||
The Doctrine mapping types are used to convert the local PHP types to the MongoDB types
|
||||
when persisting so that your domain is not bound to MongoDB-specific types. For example a
|
||||
DateTime instance may be converted to MongoDate when you persist your documents, and vice
|
||||
versa during hydration.
|
||||
|
||||
Generally, the name of each built-in mapping type hints as to how the value will be converted.
|
||||
This list explains some of the less obvious mapping types:
|
||||
|
||||
- ``bin``: string to MongoBinData instance with a "generic" type (default)
|
||||
- ``bin_bytearray``: string to MongoBinData instance with a "byte array" type
|
||||
- ``bin_custom``: string to MongoBinData instance with a "custom" type
|
||||
- ``bin_func``: string to MongoBinData instance with a "function" type
|
||||
- ``bin_md5``: string to MongoBinData instance with a "md5" type
|
||||
- ``bin_uuid``: string to MongoBinData instance with a "uuid" type
|
||||
- ``collection``: numerically indexed array to MongoDB array
|
||||
- ``date``: DateTime to MongoDate
|
||||
- ``hash``: associative array to MongoDB object
|
||||
- ``id``: string to MongoId by default, but other formats are possible
|
||||
- ``timestamp``: string to MongoTimestamp
|
||||
- ``raw``: any type
|
||||
|
||||
.. note::
|
||||
|
||||
If you are using the hash type, values within the associative array are
|
||||
passed to MongoDB directly, without being prepared. Only formats suitable for
|
||||
the Mongo driver should be used. If your hash contains values which are not
|
||||
suitable you should either use an embedded document or use formats provided
|
||||
by the MongoDB driver (e.g. ``\MongoDate`` instead of ``\DateTime``).
|
||||
|
||||
Property Mapping
|
||||
----------------
|
||||
|
||||
After a class has been marked as a document it can specify
|
||||
mappings for its instance fields. Here we will only look at simple
|
||||
fields that hold scalar values like strings, numbers, etc.
|
||||
References to other objects and embedded objects are covered in the
|
||||
chapter "Reference Mapping".
|
||||
|
||||
.. _basic_mapping_identifiers:
|
||||
|
||||
Identifiers
|
||||
~~~~~~~~~~~
|
||||
|
||||
Every document class needs an identifier. You designate the field
|
||||
that serves as the identifier with the ``@Id`` marker annotation.
|
||||
Here is an example:
|
||||
|
||||
.. configuration-block::
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
namespace Documents;
|
||||
|
||||
/** @Document */
|
||||
class User
|
||||
{
|
||||
/** @Id */
|
||||
private $id;
|
||||
}
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<doctrine-mongo-mapping xmlns="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping
|
||||
http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping.xsd">
|
||||
<document name="Documents\User">
|
||||
<field fieldName="id" id="true" />
|
||||
</document>
|
||||
</doctrine-mongo-mapping>
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
Documents\User:
|
||||
fields:
|
||||
id:
|
||||
type: id
|
||||
id: true
|
||||
|
||||
You can configure custom ID strategies if you don't want to use the default MongoId.
|
||||
The available strategies are:
|
||||
|
||||
- ``AUTO`` - Uses the native generated MongoId.
|
||||
- ``ALNUM`` - Generates an alpha-numeric string (based on an incrementing value).
|
||||
- ``CUSTOM`` - Defers generation to a AbstractIdGenerator implementation specified in the ``class`` option.
|
||||
- ``INCREMENT`` - Uses another collection to auto increment an integer identifier.
|
||||
- ``UUID`` - Generates a UUID identifier.
|
||||
- ``NONE`` - Do not generate any identifier. ID must be manually set.
|
||||
|
||||
Here is an example how to manually set a string identifier for your documents:
|
||||
|
||||
.. configuration-block::
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/** Document */
|
||||
class MyPersistentClass
|
||||
{
|
||||
/** @Id(strategy="NONE", type="string") */
|
||||
private $id;
|
||||
|
||||
public function setId($id)
|
||||
{
|
||||
$this->id = $id;
|
||||
}
|
||||
|
||||
//...
|
||||
}
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<doctrine-mongo-mapping xmlns="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping
|
||||
http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping.xsd">
|
||||
|
||||
<document name="MyPersistentClass">
|
||||
<field name="id" id="true" strategy="NONE" type="string" />
|
||||
</document>
|
||||
</doctrine-mongo-mapping>
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
MyPersistentClass:
|
||||
fields:
|
||||
id:
|
||||
type: string
|
||||
id: true
|
||||
strategy: NONE
|
||||
|
||||
When using the ``NONE`` strategy you will have to explicitly set an id before persisting the document:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
//...
|
||||
|
||||
$document = new MyPersistentClass();
|
||||
$document->setId('my_unique_identifier');
|
||||
$dm->persist($document);
|
||||
$dm->flush();
|
||||
|
||||
Now you can retrieve the document later:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
//...
|
||||
|
||||
$document = $dm->find('MyPersistentClass', 'my_unique_identifier');
|
||||
|
||||
You can define your own ID generator by extending the
|
||||
``Doctrine\ODM\MongoDB\Id\AbstractIdGenerator`` class and specifying the class
|
||||
as an option for the ``CUSTOM`` strategy:
|
||||
|
||||
.. configuration-block::
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/** Document */
|
||||
class MyPersistentClass
|
||||
{
|
||||
/** @Id(strategy="CUSTOM", type="string", options={"class"="Vendor\Specific\Generator"}) */
|
||||
private $id;
|
||||
|
||||
public function setId($id)
|
||||
{
|
||||
$this->id = $id;
|
||||
}
|
||||
|
||||
//...
|
||||
}
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<doctrine-mongo-mapping xmlns="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping
|
||||
http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping.xsd">
|
||||
|
||||
<document name="MyPersistentClass">
|
||||
<field name="id" id="true" strategy="CUSTOM" type="string">
|
||||
<id-generator-option name="class" value="Vendor\Specific\Generator" />
|
||||
</field>
|
||||
</document>
|
||||
</doctrine-mongo-mapping>
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
MyPersistentClass:
|
||||
fields:
|
||||
id:
|
||||
id: true
|
||||
strategy: CUSTOM
|
||||
type: string
|
||||
options:
|
||||
class: Vendor\Specific\Generator
|
||||
|
||||
|
||||
|
||||
Fields
|
||||
~~~~~~
|
||||
|
||||
To mark a property for document persistence the ``@Field`` docblock
|
||||
annotation can be used. This annotation usually requires at least 1
|
||||
attribute to be set, the ``type``. The ``type`` attribute specifies
|
||||
the Doctrine Mapping Type to use for the field. If the type is not
|
||||
specified, 'string' is used as the default mapping type since it is
|
||||
the most flexible.
|
||||
|
||||
Example:
|
||||
|
||||
.. configuration-block::
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
namespace Documents;
|
||||
|
||||
/** @Document */
|
||||
class User
|
||||
{
|
||||
// ...
|
||||
|
||||
/** @Field(type="string") */
|
||||
private $username;
|
||||
}
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<doctrine-mongo-mapping xmlns="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping
|
||||
http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping.xsd">
|
||||
<document name="Documents\User">
|
||||
<field fieldName="id" id="true" />
|
||||
<field fieldName="username" type="string" />
|
||||
</document>
|
||||
</doctrine-mongo-mapping>
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
Documents\User:
|
||||
fields:
|
||||
id:
|
||||
type: id
|
||||
id: true
|
||||
username:
|
||||
type: string
|
||||
|
||||
In that example we mapped the property ``id`` to the field ``id``
|
||||
using the mapping type ``id`` and the property ``name`` is mapped
|
||||
to the field ``name`` with the default mapping type ``string``. As
|
||||
you can see, by default the mongo field names are assumed to be the
|
||||
same as the property names. To specify a different name for the
|
||||
field, you can use the ``name`` attribute of the Field annotation
|
||||
as follows:
|
||||
|
||||
.. configuration-block::
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/** @Field(name="db_name") */
|
||||
private $name;
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<field fieldName="name" name="db_name" />
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
name:
|
||||
name: db_name
|
||||
|
||||
Custom Mapping Types
|
||||
--------------------
|
||||
|
||||
Doctrine allows you to create new mapping types. This can come in
|
||||
handy when you're missing a specific mapping type or when you want
|
||||
to replace the existing implementation of a mapping type.
|
||||
|
||||
In order to create a new mapping type you need to subclass
|
||||
``Doctrine\ODM\MongoDB\Types\Type`` and implement/override
|
||||
the methods. Here is an example skeleton of such a custom type
|
||||
class:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
namespace My\Project\Types;
|
||||
|
||||
use Doctrine\ODM\MongoDB\Types\Type;
|
||||
|
||||
/**
|
||||
* My custom datatype.
|
||||
*/
|
||||
class MyType extends Type
|
||||
{
|
||||
public function convertToPHPValue($value)
|
||||
{
|
||||
// Note: this function is only called when your custom type is used
|
||||
// as an identifier. For other cases, closureToPHP() will be called.
|
||||
return new \DateTime('@' . $value->sec);
|
||||
}
|
||||
|
||||
public function closureToPHP()
|
||||
{
|
||||
// Return the string body of a PHP closure that will receive $value
|
||||
// and store the result of a conversion in a $return variable
|
||||
return '$return = new \DateTime($value);';
|
||||
}
|
||||
|
||||
public function convertToDatabaseValue($value)
|
||||
{
|
||||
// This is called to convert a PHP value to its Mongo equivalent
|
||||
return new \MongoDate($value);
|
||||
}
|
||||
}
|
||||
|
||||
Restrictions to keep in mind:
|
||||
|
||||
-
|
||||
If the value of the field is *NULL* the method
|
||||
``convertToDatabaseValue()`` is not called.
|
||||
-
|
||||
The ``UnitOfWork`` never passes values to the database convert
|
||||
method that did not change in the request.
|
||||
|
||||
When you have implemented the type you still need to let Doctrine
|
||||
know about it. This can be achieved through the
|
||||
``Doctrine\ODM\MongoDB\Types\Type#registerType($name, $class)``
|
||||
method.
|
||||
|
||||
Here is an example:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
// in bootstrapping code
|
||||
|
||||
// ...
|
||||
|
||||
use Doctrine\ODM\MongoDB\Types\Type;
|
||||
|
||||
// ...
|
||||
|
||||
// Register my type
|
||||
Type::addType('mytype', 'My\Project\Types\MyType');
|
||||
|
||||
As can be seen above, when registering the custom types in the
|
||||
configuration you specify a unique name for the mapping type and
|
||||
map that to the corresponding |FQCN|. Now you can use your new
|
||||
type in your mapping like this:
|
||||
|
||||
.. configuration-block::
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
class MyPersistentClass
|
||||
{
|
||||
/** @Field(type="mytype") */
|
||||
private $field;
|
||||
}
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<field fieldName="field" type="mytype" />
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
field:
|
||||
type: mytype
|
||||
|
||||
Multiple Document Types in a Collection
|
||||
---------------------------------------
|
||||
|
||||
You can easily store multiple types of documents in a single collection. This
|
||||
requires specifying the same collection name, ``discriminatorField``, and
|
||||
(optionally) ``discriminatorMap`` mapping options for each class that will share
|
||||
the collection. Here is an example:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @Document(collection="my_documents")
|
||||
* @DiscriminatorField("type")
|
||||
* @DiscriminatorMap({"article"="Article", "album"="Album"})
|
||||
*/
|
||||
class Article
|
||||
{
|
||||
// ...
|
||||
}
|
||||
|
||||
/**
|
||||
* @Document(collection="my_documents")
|
||||
* @DiscriminatorField("type")
|
||||
* @DiscriminatorMap({"article"="Article", "album"="Album"})
|
||||
*/
|
||||
class Album
|
||||
{
|
||||
// ...
|
||||
}
|
||||
|
||||
All instances of ``Article`` and ``Album`` will be stored in the
|
||||
``my_documents`` collection. You can query for the documents of a particular
|
||||
class just like you normally would and the results will automatically be limited
|
||||
based on the discriminator value for that class.
|
||||
|
||||
If you wish to query for multiple types of documents from the collection, you
|
||||
may pass an array of document class names when creating a query builder:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$query = $dm->createQuery(array('Article', 'Album'));
|
||||
$documents = $query->execute();
|
||||
|
||||
The above will return a cursor that will allow you to iterate over all
|
||||
``Article`` and ``Album`` documents in the collections.
|
||||
|
||||
.. |FQCN| raw:: html
|
||||
<abbr title="Fully-Qualified Class Name">FQCN</abbr>
|
||||
@@ -0,0 +1,70 @@
|
||||
Best Practices
|
||||
==============
|
||||
|
||||
Here are some best practices you can follow when working with the Doctrine MongoDB ODM.
|
||||
|
||||
Constrain relationships as much as possible
|
||||
-------------------------------------------
|
||||
|
||||
It is important to constrain relationships as much as possible. This means:
|
||||
|
||||
- Impose a traversal direction (avoid bidirectional associations if possible)
|
||||
- Eliminate nonessential associations
|
||||
|
||||
This has several benefits:
|
||||
|
||||
- Reduced coupling in your domain model
|
||||
- Simpler code in your domain model (no need to maintain bidirectionality properly)
|
||||
- Less work for Doctrine
|
||||
|
||||
Use events judiciously
|
||||
----------------------
|
||||
|
||||
The event system of Doctrine is great and fast. Even though making
|
||||
heavy use of events, especially lifecycle events, can have a
|
||||
negative impact on the performance of your application. Thus you
|
||||
should use events judiciously.
|
||||
|
||||
Use cascades judiciously
|
||||
------------------------
|
||||
|
||||
Automatic cascades of the persist/remove/merge/etc. operations are
|
||||
very handy but should be used wisely. Do NOT simply add all
|
||||
cascades to all associations. Think about which cascades actually
|
||||
do make sense for you for a particular association, given the
|
||||
scenarios it is most likely used in.
|
||||
|
||||
Don't use special characters
|
||||
----------------------------
|
||||
|
||||
Avoid using any non-ASCII characters in class, field, table or
|
||||
column names. Doctrine itself is not unicode-safe in many places
|
||||
and will not be until PHP itself is fully unicode-aware.
|
||||
|
||||
Initialize collections in the constructor
|
||||
-----------------------------------------
|
||||
|
||||
It is recommended best practice to initialize any business
|
||||
collections in documents in the constructor.
|
||||
|
||||
Example:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
namespace MyProject\Model;
|
||||
|
||||
use Doctrine\Common\Collections\ArrayCollection;
|
||||
|
||||
class User
|
||||
{
|
||||
private $addresses;
|
||||
private $articles;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->addresses = new ArrayCollection;
|
||||
$this->articles = new ArrayCollection;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
Bi-Directional References
|
||||
=========================
|
||||
|
||||
By default when you map a bi-directional reference, the reference is maintained on both sides
|
||||
of the relationship and there is not a single "owning side". Both sides are considered owning
|
||||
and changes are tracked and persisted separately. Here is an example:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/** @Document */
|
||||
class BlogPost
|
||||
{
|
||||
// ...
|
||||
|
||||
/** @ReferenceOne(targetDocument="User") */
|
||||
private $user;
|
||||
}
|
||||
|
||||
/** @Document */
|
||||
class User
|
||||
{
|
||||
// ...
|
||||
|
||||
/** @ReferenceMany(targetDocument="BlogPost") */
|
||||
private $posts;
|
||||
}
|
||||
|
||||
When I persist some instances of the above classes the references would exist on both sides! The
|
||||
``BlogPost`` collection would have a `DBRef`_ stored on the ``$user`` property and the ``User``
|
||||
collection would have a `DBRef`_ stored in the ``$posts`` property.
|
||||
|
||||
Owning and Inverse Sides
|
||||
------------------------
|
||||
|
||||
A user may have lots of posts and we don't need to store a reference to each post on the user, we
|
||||
can get the users post by running a query like the following:
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
db.BlogPost.find({ 'user.$id' : user.id })
|
||||
|
||||
In order to map this you can use the ``inversedBy`` and ``mappedBy`` options. Here is the same
|
||||
example above where we implement this:
|
||||
|
||||
One to Many
|
||||
~~~~~~~~~~~
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/** @Document */
|
||||
class BlogPost
|
||||
{
|
||||
// ...
|
||||
|
||||
/** @ReferenceOne(targetDocument="User", inversedBy="posts") */
|
||||
private $user;
|
||||
}
|
||||
|
||||
/** @Document */
|
||||
class User
|
||||
{
|
||||
// ...
|
||||
|
||||
/** @ReferenceMany(targetDocument="BlogPost", mappedBy="user") */
|
||||
private $posts;
|
||||
}
|
||||
|
||||
So now when we persist a ``User`` and multiple ``BlogPost`` instances for that ``User``:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$user = new User();
|
||||
|
||||
$post1 = new BlogPost();
|
||||
$post1->setUser($user);
|
||||
|
||||
$post2 = new BlogPost();
|
||||
$post2->setUser($user);
|
||||
|
||||
$post3 = new BlogPost();
|
||||
$post3->setUser($user);
|
||||
|
||||
$dm->persist($post1);
|
||||
$dm->persist($post2);
|
||||
$dm->persist($post3);
|
||||
$dm->flush();
|
||||
|
||||
And we retrieve the ``User`` later to access the posts for that user:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$user = $dm->find('User', $user->id);
|
||||
|
||||
$posts = $user->getPosts();
|
||||
foreach ($posts as $post) {
|
||||
// ...
|
||||
}
|
||||
|
||||
The above will execute a query like the following to lazily load the collection of posts to
|
||||
iterate over:
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
db.BlogPost.find( { 'user.$id' : user.id } )
|
||||
|
||||
.. note::
|
||||
|
||||
Remember that the inverse side, the side which specified ``mappedBy`` is immutable and
|
||||
any changes to the state of the reference will not be persisted.
|
||||
|
||||
Other Examples
|
||||
--------------
|
||||
|
||||
Here are several examples which implement the ``inversedBy`` and ``mappedBy`` options:
|
||||
|
||||
One to One
|
||||
~~~~~~~~~~~
|
||||
|
||||
Here is an example where we have a one to one relationship between ``Cart`` and ``Customer``:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/** @Document */
|
||||
class Cart
|
||||
{
|
||||
// ...
|
||||
|
||||
/**
|
||||
* @ReferenceOne(targetDocument="Customer", inversedBy="cart")
|
||||
*/
|
||||
public $customer;
|
||||
}
|
||||
|
||||
/** @Document */
|
||||
class Customer
|
||||
{
|
||||
// ...
|
||||
|
||||
/**
|
||||
* @ReferenceOne(targetDocument="Cart", mappedBy="customer")
|
||||
*/
|
||||
public $cart;
|
||||
}
|
||||
|
||||
The owning side is on ``Cart.customer`` and the ``Customer.cart`` referenced is loaded with a query
|
||||
like this:
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
db.Cart.find( { 'customer.$id' : customer.id } )
|
||||
|
||||
If you want to nullify the relationship between a ``Cart`` instance and ``Customer`` instance
|
||||
you must null it out on the ``Cart.customer`` side:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$cart->setCustomer(null);
|
||||
$dm->flush();
|
||||
|
||||
.. note::
|
||||
|
||||
When specifying inverse one-to-one relationships the referenced document is
|
||||
loaded directly when the owning document is hydrated instead of using a
|
||||
proxy. In the example above, loading a ``Customer`` object from the database
|
||||
would also cause the corresponding ``Cart`` to be loaded. This can cause
|
||||
performance issues when loading many ``Customer`` objects at once.
|
||||
|
||||
Self-Referencing Many to Many
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
namespace Documents;
|
||||
|
||||
/** @Document */
|
||||
class User
|
||||
{
|
||||
// ...
|
||||
|
||||
/**
|
||||
* @ReferenceMany(targetDocument="User", mappedBy="myFriends")
|
||||
*/
|
||||
public $friendsWithMe;
|
||||
|
||||
/**
|
||||
* @ReferenceMany(targetDocument="User", inversedBy="friendsWithMe")
|
||||
*/
|
||||
public $myFriends;
|
||||
|
||||
public function __construct($name)
|
||||
{
|
||||
$this->name = $name;
|
||||
$this->friendsWithMe = new \Doctrine\Common\Collections\ArrayCollection();
|
||||
$this->myFriends = new \Doctrine\Common\Collections\ArrayCollection();
|
||||
}
|
||||
|
||||
public function addFriend(User $user)
|
||||
{
|
||||
$user->friendsWithMe[] = $this;
|
||||
$this->myFriends[] = $user;
|
||||
}
|
||||
}
|
||||
|
||||
.. _DBRef: https://docs.mongodb.com/manual/reference/database-references/#dbrefs
|
||||
@@ -0,0 +1,92 @@
|
||||
Capped Collections
|
||||
==================
|
||||
|
||||
Capped collections are fixed sized collections that have a very
|
||||
high performance auto-LRU age-out feature (age out is based on
|
||||
insertion order).
|
||||
|
||||
In addition, capped collections automatically, with high
|
||||
performance, maintain insertion order for the objects in the
|
||||
collection; this is very powerful for certain use cases such as
|
||||
logging.
|
||||
|
||||
Mapping
|
||||
-------
|
||||
|
||||
You can configure the collection in the ``collection`` attribute of
|
||||
the ``@Document`` annotation:
|
||||
|
||||
.. configuration-block::
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @Document(collection={
|
||||
* "name"="collname",
|
||||
* "capped"=true,
|
||||
* "size"=100000,
|
||||
* "max"=1000
|
||||
* })
|
||||
*/
|
||||
class Category
|
||||
{
|
||||
/** @Id */
|
||||
public $id;
|
||||
|
||||
/** @Field(type="string") */
|
||||
public $name;
|
||||
}
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<doctrine-mongo-mapping xmlns="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping
|
||||
http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping.xsd">
|
||||
<document name="Documents\Category" collection="collname" capped-collection="true" capped-collection-size="100000" capped-collection-max="1000">
|
||||
<field fieldName="id" id="true" />
|
||||
<field fieldName="name" type="string" />
|
||||
</document>
|
||||
</doctrine-mongo-mapping>
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
Documents\Category:
|
||||
type: document
|
||||
collection:
|
||||
name: collname
|
||||
capped: true
|
||||
size: 100000
|
||||
max: 1000
|
||||
fields:
|
||||
id:
|
||||
type: id
|
||||
id: true
|
||||
name:
|
||||
type: string
|
||||
|
||||
Creating
|
||||
--------
|
||||
|
||||
Remember that you must manually create the collections. If you let
|
||||
MongoDB create the collection lazily the first time it is selected,
|
||||
it will not be created with the capped configuration. You can
|
||||
create the collection for a document with the ``SchemaManager``
|
||||
that can be acquired from your ``DocumentManager`` instance:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$documentManager->getSchemaManager()->createDocumentCollection('Category');
|
||||
|
||||
You can drop the collection too if it already exists:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$documentManager->getSchemaManager()->dropDocumentCollection('Category');
|
||||
@@ -0,0 +1,150 @@
|
||||
.. _change_tracking_policies:
|
||||
|
||||
Change Tracking Policies
|
||||
========================
|
||||
|
||||
Change tracking is the process of determining what has changed in
|
||||
managed documents since the last time they were synchronized with
|
||||
the database.
|
||||
|
||||
Doctrine provides 3 different change tracking policies, each having
|
||||
its particular advantages and disadvantages. The change tracking
|
||||
policy can be defined on a per-class basis (or more precisely,
|
||||
per-hierarchy).
|
||||
|
||||
Deferred Implicit
|
||||
~~~~~~~~~~~~~~~~~
|
||||
|
||||
The deferred implicit policy is the default change tracking policy
|
||||
and the most convenient one. With this policy, Doctrine detects the
|
||||
changes by a property-by-property comparison at commit time and
|
||||
also detects changes to documents or new documents that are
|
||||
referenced by other managed documents. Although the most convenient policy,
|
||||
it can have negative effects on performance if you are dealing with large units
|
||||
of work. Since Doctrine can't know what has changed, it needs to check
|
||||
all managed documents for changes every time you invoke DocumentManager#flush(),
|
||||
making this operation rather costly.
|
||||
|
||||
Deferred Explicit
|
||||
~~~~~~~~~~~~~~~~~
|
||||
|
||||
The deferred explicit policy is similar to the deferred implicit
|
||||
policy in that it detects changes through a property-by-property
|
||||
comparison at commit time. The difference is that only documents are
|
||||
considered that have been explicitly marked for change detection
|
||||
through a call to DocumentManager#persist(document) or through a save
|
||||
cascade. All other documents are skipped. This policy therefore
|
||||
gives improved performance for larger units of work while
|
||||
sacrificing the behavior of "automatic dirty checking".
|
||||
|
||||
Therefore, flush() operations are potentially cheaper with this
|
||||
policy. The negative aspect this has is that if you have a rather
|
||||
large application and you pass your objects through several layers
|
||||
for processing purposes and business tasks you may need to track
|
||||
yourself which documents have changed on the way so you can pass
|
||||
them to DocumentManager#persist().
|
||||
|
||||
This policy can be configured as follows:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @Document
|
||||
* @ChangeTrackingPolicy("DEFERRED_EXPLICIT")
|
||||
*/
|
||||
class User
|
||||
{
|
||||
// ...
|
||||
}
|
||||
|
||||
Notify
|
||||
~~~~~~
|
||||
|
||||
This policy is based on the assumption that the documents notify
|
||||
interested listeners of changes to their properties. For that
|
||||
purpose, a class that wants to use this policy needs to implement
|
||||
the ``NotifyPropertyChanged`` interface from the Doctrine
|
||||
namespace. As a guideline, such an implementation can look as
|
||||
follows:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
use Doctrine\Common\NotifyPropertyChanged,
|
||||
Doctrine\Common\PropertyChangedListener;
|
||||
|
||||
/**
|
||||
* @Document
|
||||
* @ChangeTrackingPolicy("NOTIFY")
|
||||
*/
|
||||
class MyDocument implements NotifyPropertyChanged
|
||||
{
|
||||
// ...
|
||||
|
||||
private $_listeners = array();
|
||||
|
||||
public function addPropertyChangedListener(PropertyChangedListener $listener)
|
||||
{
|
||||
$this->_listeners[] = $listener;
|
||||
}
|
||||
}
|
||||
|
||||
Then, in each property setter of this class or derived classes, you
|
||||
need to notify all the ``PropertyChangedListener`` instances. As an
|
||||
example we add a convenience method on ``MyDocument`` that shows this
|
||||
behavior:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
// ...
|
||||
|
||||
class MyDocument implements NotifyPropertyChanged
|
||||
{
|
||||
// ...
|
||||
|
||||
protected function _onPropertyChanged($propName, $oldValue, $newValue)
|
||||
{
|
||||
if ($this->_listeners) {
|
||||
foreach ($this->_listeners as $listener) {
|
||||
$listener->propertyChanged($this, $propName, $oldValue, $newValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function setData($data)
|
||||
{
|
||||
if ($data != $this->data) {
|
||||
$this->_onPropertyChanged('data', $this->data, $data);
|
||||
$this->data = $data;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
You have to invoke ``_onPropertyChanged`` inside every method that
|
||||
changes the persistent state of ``MyDocument``.
|
||||
|
||||
The check whether the new value is different from the old one is
|
||||
not mandatory but recommended. That way you also have full control
|
||||
over when you consider a property changed.
|
||||
|
||||
The negative point of this policy is obvious: You need implement an
|
||||
interface and write some plumbing code. But also note that we tried
|
||||
hard to keep this notification functionality abstract. Strictly
|
||||
speaking, it has nothing to do with the persistence layer. You may
|
||||
find that property notification events come in handy in many other
|
||||
scenarios as well. As mentioned earlier, the ``Doctrine\Common``
|
||||
namespace is not that evil and consists solely of very small classes
|
||||
and interfaces that have almost no external dependencies and that you can easily take with you should
|
||||
you want to swap out the persistence layer. This change tracking policy
|
||||
does not introduce a dependency on the Doctrine persistence
|
||||
layer.
|
||||
|
||||
The positive point and main advantage of this policy is its
|
||||
effectiveness. It has the best performance characteristics of the 3
|
||||
policies with larger units of work and a flush() operation is very
|
||||
cheap when nothing has changed.
|
||||
@@ -0,0 +1,152 @@
|
||||
Complex References
|
||||
==================
|
||||
|
||||
Sometimes you may want to access related documents using custom criteria or from
|
||||
the inverse side of a relationship.
|
||||
|
||||
You can create an `immutable`_ reference to one or many documents and specify
|
||||
how that reference is to be loaded. The reference is immutable in that it is
|
||||
defined only in the mapping, unlike a typical reference where a `MongoDBRef`_ or
|
||||
identifier (see :ref:`storing_references`) is stored on the document itself.
|
||||
|
||||
The following options may be used for :ref:`one <reference_one>` and
|
||||
:ref:`many <reference_many>` reference mappings:
|
||||
|
||||
- ``criteria`` - Query criteria to apply to the cursor.
|
||||
- ``repositoryMethod`` - The repository method used to create the cursor.
|
||||
- ``sort`` - Sort criteria for the cursor.
|
||||
- ``skip`` - Skip offset to apply to the cursor.
|
||||
- ``limit`` - Limit to apply to the cursor.
|
||||
|
||||
Basic Example
|
||||
-------------
|
||||
|
||||
In the following example, ``$comments`` will refer to all Comments for the
|
||||
BlogPost and ``$last5Comments`` will refer to only the last five Comments. The
|
||||
``mappedBy`` field is used to determine which Comment field should be used for
|
||||
querying by the BlogPost's ID.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/** @Document */
|
||||
class BlogPost
|
||||
{
|
||||
// ...
|
||||
|
||||
/** @ReferenceMany(targetDocument="Comment", mappedBy="blogPost") */
|
||||
private $comments;
|
||||
|
||||
/**
|
||||
* @ReferenceMany(
|
||||
* targetDocument="Comment",
|
||||
* mappedBy="blogPost",
|
||||
* sort={"date"="desc"},
|
||||
* limit=5
|
||||
* )
|
||||
*/
|
||||
private $last5Comments;
|
||||
}
|
||||
|
||||
/** @Document */
|
||||
class Comment
|
||||
{
|
||||
// ...
|
||||
|
||||
/** @ReferenceOne(targetDocument="BlogPost", inversedBy="comments") */
|
||||
private $blogPost;
|
||||
}
|
||||
|
||||
You can also use ``mappedBy`` for referencing a single document, as in the
|
||||
following example:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @ReferenceOne(
|
||||
* targetDocument="Comment",
|
||||
* mappedBy="blogPost",
|
||||
* sort={"date"="desc"}
|
||||
* )
|
||||
*/
|
||||
private $lastComment;
|
||||
|
||||
|
||||
``criteria`` Example
|
||||
--------------------
|
||||
|
||||
Use ``criteria`` to further match referenced documents. In the following
|
||||
example, ``$commentsByAdmin`` will refer only comments created by
|
||||
administrators:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @ReferenceMany(
|
||||
* targetDocument="Comment",
|
||||
* mappedBy="blogPost",
|
||||
* criteria={"isByAdmin" : true}
|
||||
* )
|
||||
*/
|
||||
private $commentsByAdmin;
|
||||
|
||||
``repositoryMethod`` Example
|
||||
----------------------------
|
||||
|
||||
Alternatively, you can use ``repositoryMethod`` to specify a custom method to
|
||||
call on the Comment repository class to populate the reference.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @ReferenceMany(
|
||||
* targetDocument="Comment",
|
||||
* mappedBy="blogPost",
|
||||
* repositoryMethod="findSomeComments"
|
||||
* )
|
||||
*/
|
||||
private $someComments;
|
||||
|
||||
The ``Comment`` class will need to have a custom repository class configured:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/** @Document(repositoryClass="CommentRepository") */
|
||||
class Comment
|
||||
{
|
||||
// ...
|
||||
}
|
||||
|
||||
Lastly, the ``CommentRepository`` class will need a ``findSomeComments()``
|
||||
method which shall return ``Doctrine\MongoDB\CursorInterface``. When this method
|
||||
is called to populate the reference, Doctrine will provide the Blogpost instance
|
||||
(i.e. owning document) as the first argument:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
class CommentRepository extends \Doctrine\ODM\MongoDB\DocumentRepository
|
||||
{
|
||||
/**
|
||||
* @return \Doctrine\ODM\MongoDB\Cursor
|
||||
*/
|
||||
public function findSomeComments(BlogPost $blogPost)
|
||||
{
|
||||
return $this->createQueryBuilder()
|
||||
->field('blogPost')->references($blogPost);
|
||||
->getQuery()->execute();
|
||||
}
|
||||
}
|
||||
|
||||
.. _MongoDBRef: http://php.net/manual/en/class.mongodbref.php
|
||||
.. _immutable: http://en.wikipedia.org/wiki/Immutable
|
||||
@@ -0,0 +1,54 @@
|
||||
Console Commands
|
||||
================
|
||||
|
||||
Doctrine MongoDB ODM offers some console commands, which utilize Symfony2's
|
||||
Console component, to ease your development process:
|
||||
|
||||
- ``odm:clear-cache:metadata`` - Clear all metadata cache of the various cache drivers.
|
||||
- ``odm:query`` - Query mongodb and inspect the outputted results from your document classes.
|
||||
- ``odm:generate:documents`` - Generate document classes and method stubs from your mapping information.
|
||||
- ``odm:generate:hydrators`` - Generates hydrator classes for document classes.
|
||||
- ``odm:generate:proxies`` - Generates proxy classes for document classes.
|
||||
- ``odm:generate:repositories`` - Generate repository classes from your mapping information.
|
||||
- ``odm:schema:create`` - Allows you to create databases, collections and indexes for your documents
|
||||
- ``odm:schema:drop`` - Allows you to drop databases, collections and indexes for your documents
|
||||
- ``odm:schema:update`` - Allows you to update indexes for your documents
|
||||
- ``odm:schema:shard`` - Allows you to enable sharding for your documents
|
||||
|
||||
Provided you have an existing ``DocumentManager`` instance, you can setup a
|
||||
console command easily with the following code:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
// mongodb.php
|
||||
|
||||
// ... include Composer autoloader and configure DocumentManager instance
|
||||
|
||||
$helperSet = new \Symfony\Component\Console\Helper\HelperSet(array(
|
||||
'dm' => new \Doctrine\ODM\MongoDB\Tools\Console\Helper\DocumentManagerHelper($dm),
|
||||
));
|
||||
|
||||
$app = new Application('Doctrine MongoDB ODM');
|
||||
$app->setHelperSet($helperSet);
|
||||
$app->addCommands(array(
|
||||
new \Doctrine\ODM\MongoDB\Tools\Console\Command\GenerateDocumentsCommand(),
|
||||
new \Doctrine\ODM\MongoDB\Tools\Console\Command\GenerateHydratorsCommand(),
|
||||
new \Doctrine\ODM\MongoDB\Tools\Console\Command\GenerateProxiesCommand(),
|
||||
new \Doctrine\ODM\MongoDB\Tools\Console\Command\GenerateRepositoriesCommand(),
|
||||
new \Doctrine\ODM\MongoDB\Tools\Console\Command\QueryCommand(),
|
||||
new \Doctrine\ODM\MongoDB\Tools\Console\Command\ClearCache\MetadataCommand(),
|
||||
new \Doctrine\ODM\MongoDB\Tools\Console\Command\Schema\CreateCommand(),
|
||||
new \Doctrine\ODM\MongoDB\Tools\Console\Command\Schema\DropCommand(),
|
||||
new \Doctrine\ODM\MongoDB\Tools\Console\Command\Schema\UpdateCommand(),
|
||||
new \Doctrine\ODM\MongoDB\Tools\Console\Command\Schema\ShardCommand(),
|
||||
));
|
||||
|
||||
$app->run();
|
||||
|
||||
A reference implementation of the console command may be found in the
|
||||
``tools/sandbox`` directory of the project repository. That command is
|
||||
configured to store generated hydrators and proxies in the same directory, and
|
||||
relies on the main project's Composer dependencies. You will want to customize
|
||||
its configuration files if you intend to use it in your own project.
|
||||
@@ -0,0 +1,170 @@
|
||||
.. _custom_collection:
|
||||
|
||||
Custom Collections
|
||||
==================
|
||||
|
||||
.. note::
|
||||
This feature was introduced in version 1.1
|
||||
|
||||
By default, Doctrine uses ``ArrayCollection`` implementation of its ``Collection``
|
||||
interface to hold both embedded and referenced documents. That collection may then
|
||||
be wrapped by a ``PersistentCollection`` to allow for change tracking and other
|
||||
persistence-related features.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
use Doctrine\Common\Collections\ArrayCollection;
|
||||
|
||||
/** @Document */
|
||||
class Application
|
||||
{
|
||||
// ...
|
||||
|
||||
/**
|
||||
* @EmbedMany(targetDocument="Section")
|
||||
*/
|
||||
private $sections;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->sections = new ArrayCollection();
|
||||
}
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
For most cases this solution is sufficient but more sophisticated domains could use
|
||||
their own collections (e.g. a collection that ensures its contained objects are sorted)
|
||||
or to simply add common filtering methods that otherwise would otherwise be added to
|
||||
owning document's class.
|
||||
|
||||
Custom Collection Classes
|
||||
-------------------------
|
||||
|
||||
.. note::
|
||||
You may want to check `malarzm/collections <https://github.com/malarzm/collections>`_
|
||||
which provides alternative implementations of Doctrine's ``Collection`` interface and
|
||||
aims to kickstart development of your own collections.
|
||||
|
||||
Using your own ``Collection`` implementation is as simple as specifying the
|
||||
``collectionClass`` parameter in the ``@EmbedMany`` or ``@ReferenceMany`` mapping
|
||||
and ensuring that your custom class is initialized in the owning class' constructor:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
use Doctrine\Common\Collections\ArrayCollection;
|
||||
|
||||
/** @Document */
|
||||
class Application
|
||||
{
|
||||
// ...
|
||||
|
||||
/**
|
||||
* @EmbedMany(
|
||||
* collectionClass="SectionCollection"
|
||||
* targetDocument="Section"
|
||||
* )
|
||||
*/
|
||||
private $sections;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->sections = new SectionCollection();
|
||||
}
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
If you are satisfied with ``ArrayCollection`` and only want
|
||||
to sprinkle it with some filtering methods, you may just extend it:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
use Doctrine\Common\Collections\ArrayCollection;
|
||||
|
||||
class SectionCollection extends ArrayCollection
|
||||
{
|
||||
public function getEnabled()
|
||||
{
|
||||
return $this->filter(function(Section $s) {
|
||||
return $s->isEnabled();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Alternatively, you may want to implement the whole class from scratch:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
use Doctrine\Common\Collections\Collection;
|
||||
|
||||
class SectionCollection implements Collection
|
||||
{
|
||||
private $elements = array();
|
||||
|
||||
public function __construct(array $elements = array())
|
||||
{
|
||||
$this->elements = $elements;
|
||||
}
|
||||
|
||||
// your implementation of all methods interface requires
|
||||
}
|
||||
|
||||
Taking Control of the Collection's Constructor
|
||||
----------------------------------------------
|
||||
|
||||
By default, Doctrine assumes that it can instantiate your collections in same
|
||||
manner as an ``ArrayCollection`` (i.e. the only parameter is an optional PHP
|
||||
array); however, you may want to inject additional dependencies into your
|
||||
custom collection class(es). This will require you to create a
|
||||
`PersistentCollectionFactory implementation <https://github.com/doctrine/mongodb-odm/blob/master/lib/Doctrine/ODM/MongoDB/PersistentCollection/PersistentCollectionFactory.php>`_,
|
||||
which Doctrine will then use to construct its persistent collections.
|
||||
You may decide to implement this class from scratch or extend our
|
||||
``AbstractPersistentCollectionFactory``:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
use Doctrine\ODM\MongoDB\PersistentCollection\AbstractPersistentCollectionFactory;
|
||||
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
|
||||
|
||||
final class YourPersistentCollectionFactory extends AbstractPersistentCollectionFactory
|
||||
{
|
||||
private $eventDispatcher;
|
||||
|
||||
public function __construct(EventDispatcherInterface $eventDispatcher)
|
||||
{
|
||||
$this->eventDispatcher = $eventDispatcher;
|
||||
}
|
||||
|
||||
protected function createCollectionClass($collectionClass)
|
||||
{
|
||||
switch ($collectionClass) {
|
||||
case SectionCollection::class:
|
||||
return new $collectionClass(array(), $this->eventDispatcher);
|
||||
default:
|
||||
return new $collectionClass;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
The factory class must then be registered in the ``Configuration``:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$eventDispatcher = $container->get('event_dispatcher');
|
||||
$collFactory = new YourPersistentCollectionFactory($eventDispatcher);
|
||||
$configuration = new Configuration();
|
||||
// your other config here
|
||||
$configuration->setPersistentCollectionFactory($collFactory);
|
||||
@@ -0,0 +1,210 @@
|
||||
.. _document_repositories:
|
||||
|
||||
Document Repositories
|
||||
=====================
|
||||
|
||||
.. note::
|
||||
|
||||
A repository mediates between the domain and data mapping layers using a
|
||||
collection-like interface for accessing domain objects.
|
||||
|
||||
In Doctrine, a repository is a class that concentrates code responsible for
|
||||
querying and filtering your documents. ODM provides you with a default
|
||||
``DocumentRepository`` for all of your documents:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/* @var $repository \Doctrine\ODM\MongoDB\DocumentRepository */
|
||||
$repository = $documentManager->getRepository(User::class);
|
||||
$disabledUsers = $repository->findBy(['disabled' => true, 'activated' => true]);
|
||||
|
||||
The array passed to ``findBy`` specifies the criteria for which documents are matched.
|
||||
ODM will assist with converting PHP values to equivalent BSON types whenever possible:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
$group = $documentManager->find(Group::class, 123);
|
||||
/* @var $repository \Doctrine\ODM\MongoDB\DocumentRepository */
|
||||
$repository = $documentManager->getRepository(User::class);
|
||||
$usersInGroup = $repository->findBy(['group' => $group]);
|
||||
|
||||
The default repository implementation provides the following methods:
|
||||
|
||||
- ``find()`` - finds one document by its identifier. This may skip a database query
|
||||
if the document is already managed by ODM.
|
||||
- ``findAll()`` - finds all documents in the collection.
|
||||
- ``findBy()`` - finds all documents matching the given criteria. Additional query
|
||||
options may be specified (e.g. sort, limit, skip).
|
||||
- ``findOneBy()`` - finds one document matching the given criteria.
|
||||
- ``matching()`` - Finds all documents matching the given criteria, as expressed
|
||||
with Doctrine's Criteria API.
|
||||
|
||||
.. note::
|
||||
|
||||
All above methods will include additional criteria specified by :ref:`Filters <filters>`.
|
||||
|
||||
.. note::
|
||||
|
||||
Magic ``findBy`` and ``findOneBy`` calls described below are deprecated in 1.2 and
|
||||
will be removed in 2.0.
|
||||
|
||||
Additional methods that are not defined explicitly in the repository class may also be
|
||||
used if they follow a specific naming convention:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$group = $documentManager->find(Group::class, 123);
|
||||
/* @var $repository \Doctrine\ODM\MongoDB\DocumentRepository */
|
||||
$repository = $documentManager->getRepository(User::class);
|
||||
$usersInGroup = $repository->findByGroup($group);
|
||||
$randomUser = $repository->findOneByStatus('active');
|
||||
|
||||
In the above example, ``findByGroup()`` and ``findOneByStatus()`` will be handled by
|
||||
the ``__call`` method, which intercepts calls to undefined methods. If the invoked
|
||||
method's name starts with "findBy" or "findOneBy", ODM will attempt to infer mapped
|
||||
properties from the remainder of the method name ("Group" or "Status" as per example).
|
||||
The above calls are equivalent to:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$group = $documentManager->find(Group::class, 123);
|
||||
/* @var $repository \Doctrine\ODM\MongoDB\DocumentRepository */
|
||||
$repository = $documentManager->getRepository(User::class);
|
||||
$usersInGroup = $repository->findBy(['group' => $group]);
|
||||
$randomUser = $repository->findOneBy(['status' => 'active']);
|
||||
|
||||
Custom Repositories
|
||||
-------------------
|
||||
|
||||
A custom repository allows filtering logic to be consolidated into a single class instead
|
||||
of spreading it throughout a project. A custom repository class may be specified for a
|
||||
document class like so:
|
||||
|
||||
.. configuration-block::
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
namespace Documents;
|
||||
|
||||
/** @Document(repositoryClass="Repositories\UserRepository") */
|
||||
class User
|
||||
{
|
||||
/* ... */
|
||||
}
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<document name="Documents\User" repository-class="Repositories\UserRepository">
|
||||
<!-- ... -->
|
||||
</document>
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
Documents\User:
|
||||
repositoryClass: Repositories\\UserRepository
|
||||
collection: user
|
||||
# ...
|
||||
|
||||
The next step is implementing your repository class. In most cases, ODM's default
|
||||
``DocumentRepository`` class may be extended with additional methods that you need.
|
||||
More complex cases that require passing additional dependencies to a custom repository
|
||||
class will be discussed in the next section.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
namespace Repositories;
|
||||
|
||||
class UserRepository extends DocumentRepository
|
||||
{
|
||||
public function findDisabled()
|
||||
{
|
||||
return $this->findBy(['disabled' => true, 'activated' => true]);
|
||||
}
|
||||
}
|
||||
|
||||
It is also possible to change ODM's default ``DocumentRepository`` to your own
|
||||
implementation for all documents (unless overridden by the mapping):
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
$documentManager->getConfiguration()
|
||||
->setDefaultRepositoryClassName(MyDefaultRepository::class);
|
||||
|
||||
Repositories with Additional Dependencies
|
||||
-----------------------------------------
|
||||
|
||||
.. note::
|
||||
|
||||
Implementing your own RepositoryFactory is possible since version 1.0, but the
|
||||
``AbstractRepositoryFactory`` class used in this example is only available since 1.2.
|
||||
|
||||
By default, Doctrine assumes that it can instantiate your repositories in same manner
|
||||
as its default one:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
namespace Repositories;
|
||||
|
||||
class UserRepository extends DocumentRepository
|
||||
{
|
||||
public function __construct(DocumentManager $dm, UnitOfWork $uow, ClassMetadata $classMetadata)
|
||||
{
|
||||
/* constructor is inherited from DocumentRepository */
|
||||
/* ... */
|
||||
}
|
||||
}
|
||||
|
||||
In order to change the way Doctrine instantiates repositories, you will need to implement your own
|
||||
`RepositoryFactory <https://github.com/doctrine/mongodb-odm/blob/master/lib/Doctrine/ODM/MongoDB/Repository/RepositoryFactory.php>`_
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
use Doctrine\ODM\MongoDB\Repository\AbstractRepositoryFactory;
|
||||
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
|
||||
|
||||
final class YourRepositoryFactory extends AbstractRepositoryFactory
|
||||
{
|
||||
private $eventDispatcher;
|
||||
|
||||
public function __construct(EventDispatcherInterface $eventDispatcher)
|
||||
{
|
||||
$this->eventDispatcher = $eventDispatcher;
|
||||
}
|
||||
|
||||
protected function instantiateRepository($repositoryClassName, DocumentManager $documentManager, ClassMetadata $metadata)
|
||||
{
|
||||
switch ($repositoryClassName) {
|
||||
case UserRepository::class:
|
||||
return new UserRepository($this->eventDispatcher, $documentManager, $metadata);
|
||||
default:
|
||||
return new $repositoryClassName($documentManager, $documentManager->getUnitOfWork(), $metadata);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
The factory class must then be registered in the ``Configuration``:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$eventDispatcher = $container->get('event_dispatcher');
|
||||
$repoFactory = new YourRepositoryFactory($eventDispatcher);
|
||||
$configuration = new Configuration();
|
||||
// your other config here
|
||||
$configuration->setRepositoryFactory($repoFactory);
|
||||
@@ -0,0 +1,46 @@
|
||||
Eager Cursors
|
||||
-------------
|
||||
|
||||
With a typical MongoDB cursor, it stays open during iteration and fetches
|
||||
batches of documents as you iterate over the cursor. This isn't bad,
|
||||
but sometimes you want to fetch all of the data eagerly. For example
|
||||
when dealing with web applications, and you want to only show 50
|
||||
documents from a collection you should fetch all the data in your
|
||||
controller first before going on to the view.
|
||||
|
||||
Benefits:
|
||||
|
||||
- The cursor stays open for a much shorter period of time.
|
||||
|
||||
- Data retrieval and hydration are consolidated operations.
|
||||
|
||||
- Doctrine has the ability to retry the cursor when exceptions during interaction with mongodb are encountered.
|
||||
|
||||
Example:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$qb = $dm->createQueryBuilder('User')
|
||||
->eagerCursor(true);
|
||||
$query = $qb->getQuery();
|
||||
$users = $query->execute(); // returns instance of Doctrine\MongoDB\ODM\EagerCursor
|
||||
|
||||
At this point all data is loaded from the database and cursors to MongoDB
|
||||
have been closed but hydration of the data in to objects has not begun. Once
|
||||
insertion starts the data will be hydrated in to PHP objects.
|
||||
|
||||
Example:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
foreach ($users as $user) {
|
||||
echo $user->getUsername()."\n";
|
||||
}
|
||||
|
||||
Not all documents are converted to objects at once, the hydration is still done
|
||||
one document at a time during iteration. The only change is that all data is retrieved
|
||||
first.
|
||||
@@ -0,0 +1,283 @@
|
||||
Embedded Mapping
|
||||
================
|
||||
|
||||
This chapter explains how embedded documents are mapped in
|
||||
Doctrine.
|
||||
|
||||
.. _embed_one:
|
||||
|
||||
Embed One
|
||||
---------
|
||||
|
||||
Embed a single document:
|
||||
|
||||
.. configuration-block::
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/** @Document */
|
||||
class User
|
||||
{
|
||||
// ...
|
||||
|
||||
/** @EmbedOne(targetDocument="Address") */
|
||||
private $address;
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
/** @EmbeddedDocument */
|
||||
class Address
|
||||
{
|
||||
// ...
|
||||
}
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<doctrine-mongo-mapping xmlns="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping
|
||||
http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping.xsd">
|
||||
<document name="Documents\User">
|
||||
<embed-one field="address" target-document="Address" />
|
||||
</document>
|
||||
</doctrine-mongo-mapping>
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
User:
|
||||
type: document
|
||||
embedOne:
|
||||
address:
|
||||
targetDocument: Address
|
||||
|
||||
Address:
|
||||
type: embeddedDocument
|
||||
|
||||
.. _embed_many:
|
||||
|
||||
Embed Many
|
||||
----------
|
||||
|
||||
Embed many documents:
|
||||
|
||||
.. configuration-block::
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/** @Document */
|
||||
class User
|
||||
{
|
||||
// ...
|
||||
|
||||
/** @EmbedMany(targetDocument="Phonenumber") */
|
||||
private $phonenumbers = array();
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
/** @EmbeddedDocument */
|
||||
class Phonenumber
|
||||
{
|
||||
// ...
|
||||
}
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<doctrine-mongo-mapping xmlns="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping
|
||||
http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping.xsd">
|
||||
<document name="Documents\User">
|
||||
<embed-many field="phonenumbers" target-document="Phonenumber" />
|
||||
</document>
|
||||
</doctrine-mongo-mapping>
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
User:
|
||||
type: document
|
||||
embedMany:
|
||||
phonenumbers:
|
||||
targetDocument: Phonenumber
|
||||
|
||||
Phonenumber:
|
||||
type: embeddedDocument
|
||||
|
||||
.. _embed_mixing_document_types:
|
||||
|
||||
Mixing Document Types
|
||||
---------------------
|
||||
|
||||
If you want to store different types of embedded documents in the same field,
|
||||
you can simply omit the ``targetDocument`` option:
|
||||
|
||||
.. configuration-block::
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/** @Document */
|
||||
class User
|
||||
{
|
||||
// ..
|
||||
|
||||
/** @EmbedMany */
|
||||
private $tasks = array();
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<embed-many field="tasks" />
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
embedMany:
|
||||
tasks: ~
|
||||
|
||||
Now the ``$tasks`` property can store any type of document! The class name will
|
||||
be automatically stored in a field named ``_doctrine_class_name`` within
|
||||
the embedded document. The field name can be customized with the
|
||||
``discriminatorField`` option:
|
||||
|
||||
.. configuration-block::
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/** @Document */
|
||||
class User
|
||||
{
|
||||
// ..
|
||||
|
||||
/**
|
||||
* @EmbedMany(discriminatorField="type")
|
||||
*/
|
||||
private $tasks = array();
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<embed-many field="tasks">
|
||||
<discriminator-field name="type" />
|
||||
</embed-many>
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
embedMany:
|
||||
tasks:
|
||||
discriminatorField: type
|
||||
|
||||
You can also specify a discriminator map to avoid storing the |FQCN|
|
||||
in each embedded document:
|
||||
|
||||
.. configuration-block::
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/** @Document */
|
||||
class User
|
||||
{
|
||||
// ..
|
||||
|
||||
/**
|
||||
* @EmbedMany(
|
||||
* discriminatorMap={
|
||||
* "download"="DownloadTask",
|
||||
* "build"="BuildTask"
|
||||
* }
|
||||
* )
|
||||
*/
|
||||
private $tasks = array();
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<embed-many field="tasks">
|
||||
<discriminator-map>
|
||||
<discriminator-mapping value="download" class="DownloadTask" />
|
||||
<discriminator-mapping value="build" class="BuildTask" />
|
||||
</discriminator-map>
|
||||
</embed-many>
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
embedMany:
|
||||
tasks:
|
||||
discriminatorMap:
|
||||
download: DownloadTask
|
||||
build: BuildTask
|
||||
|
||||
If you have embedded documents without a discriminator value that need to be
|
||||
treated correctly you can optionally specify a default value for the
|
||||
discriminator:
|
||||
|
||||
.. configuration-block::
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/** @Document */
|
||||
class User
|
||||
{
|
||||
// ..
|
||||
|
||||
/**
|
||||
* @EmbedMany(
|
||||
* discriminatorMap={
|
||||
* "download"="DownloadTask",
|
||||
* "build"="BuildTask"
|
||||
* },
|
||||
* defaultDiscriminatorValue="download"
|
||||
* )
|
||||
*/
|
||||
private $tasks = array();
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<embed-many field="tasks">
|
||||
<discriminator-map>
|
||||
<discriminator-mapping value="download" class="DownloadTask" />
|
||||
<discriminator-mapping value="build" class="BuildTask" />
|
||||
</discriminator-map>
|
||||
<default-discriminator-value value="download" />
|
||||
</embed-many>
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
embedMany:
|
||||
tasks:
|
||||
discriminatorMap:
|
||||
download: DownloadTask
|
||||
build: BuildTask
|
||||
defaultDiscriminatorValue: download
|
||||
|
||||
Cascading Operations
|
||||
--------------------
|
||||
|
||||
All operations on embedded documents are automatically cascaded.
|
||||
This is because embedded documents are part of their parent
|
||||
document and cannot exist without those by nature.
|
||||
|
||||
.. |FQCN| raw:: html
|
||||
<abbr title="Fully-Qualified Class Name">FQCN</abbr>
|
||||
@@ -0,0 +1,717 @@
|
||||
Events
|
||||
======
|
||||
|
||||
Doctrine features a lightweight event system that is part of the
|
||||
Common package.
|
||||
|
||||
The Event System
|
||||
----------------
|
||||
|
||||
The event system is controlled by the ``EventManager``. It is the
|
||||
central point of Doctrine's event listener system. Listeners are
|
||||
registered on the manager and events are dispatched through the
|
||||
manager.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$evm = new EventManager();
|
||||
|
||||
Now we can add some event listeners to the ``$evm``. Let's create a
|
||||
``EventTest`` class to play around with.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
class EventTest
|
||||
{
|
||||
const preFoo = 'preFoo';
|
||||
const postFoo = 'postFoo';
|
||||
|
||||
private $_evm;
|
||||
|
||||
public $preFooInvoked = false;
|
||||
public $postFooInvoked = false;
|
||||
|
||||
public function __construct($evm)
|
||||
{
|
||||
$evm->addEventListener(array(self::preFoo, self::postFoo), $this);
|
||||
}
|
||||
|
||||
public function preFoo(EventArgs $e)
|
||||
{
|
||||
$this->preFooInvoked = true;
|
||||
}
|
||||
|
||||
public function postFoo(EventArgs $e)
|
||||
{
|
||||
$this->postFooInvoked = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Create a new instance
|
||||
$test = new EventTest($evm);
|
||||
|
||||
Events can be dispatched by using the ``dispatchEvent()`` method.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$evm->dispatchEvent(EventTest::preFoo);
|
||||
$evm->dispatchEvent(EventTest::postFoo);
|
||||
|
||||
You can easily remove a listener with the ``removeEventListener()``
|
||||
method.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$evm->removeEventListener(array(self::preFoo, self::postFoo), $this);
|
||||
|
||||
The Doctrine event system also has a simple concept of event
|
||||
subscribers. We can define a simple ``TestEventSubscriber`` class
|
||||
which implements the ``\Doctrine\Common\EventSubscriber`` interface
|
||||
and implements a ``getSubscribedEvents()`` method which returns an
|
||||
array of events it should be subscribed to.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
class TestEventSubscriber implements \Doctrine\Common\EventSubscriber
|
||||
{
|
||||
const preFoo = 'preFoo';
|
||||
|
||||
public $preFooInvoked = false;
|
||||
|
||||
public function preFoo()
|
||||
{
|
||||
$this->preFooInvoked = true;
|
||||
}
|
||||
|
||||
public function getSubscribedEvents()
|
||||
{
|
||||
return array(self::preFoo);
|
||||
}
|
||||
}
|
||||
|
||||
$eventSubscriber = new TestEventSubscriber();
|
||||
$evm->addEventSubscriber($eventSubscriber);
|
||||
|
||||
Now when you dispatch an event any event subscribers will be
|
||||
notified for that event.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$evm->dispatchEvent(TestEventSubscriber::preFoo);
|
||||
|
||||
Now test the ``$eventSubscriber`` instance to see if the
|
||||
``preFoo()`` method was invoked.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
if ($eventSubscriber->preFooInvoked) {
|
||||
echo 'pre foo invoked!';
|
||||
}
|
||||
|
||||
.. _lifecycle_events:
|
||||
|
||||
Lifecycle Events
|
||||
----------------
|
||||
|
||||
The DocumentManager and UnitOfWork trigger several events during
|
||||
the life-time of their registered documents.
|
||||
|
||||
-
|
||||
preRemove - The preRemove event occurs for a given document before
|
||||
the respective DocumentManager remove operation for that document
|
||||
is executed.
|
||||
-
|
||||
postRemove - The postRemove event occurs for a document after the
|
||||
document has been removed. It will be invoked after the database
|
||||
delete operations.
|
||||
-
|
||||
prePersist - The prePersist event occurs for a given document
|
||||
before the respective DocumentManager persist operation for that
|
||||
document is executed.
|
||||
-
|
||||
postPersist - The postPersist event occurs for a document after
|
||||
the document has been made persistent. It will be invoked after the
|
||||
database insert operations. Generated primary key values are
|
||||
available in the postPersist event.
|
||||
-
|
||||
preUpdate - The preUpdate event occurs before the database update
|
||||
operations to document data.
|
||||
-
|
||||
postUpdate - The postUpdate event occurs after the database update
|
||||
operations to document data.
|
||||
-
|
||||
preLoad - The preLoad event occurs for a document before the
|
||||
document has been loaded into the current DocumentManager from the
|
||||
database or after the refresh operation has been applied to it.
|
||||
-
|
||||
postLoad - The postLoad event occurs for a document after the
|
||||
document has been loaded into the current DocumentManager from the
|
||||
database or after the refresh operation has been applied to it.
|
||||
-
|
||||
loadClassMetadata - The loadClassMetadata event occurs after the
|
||||
mapping metadata for a class has been loaded from a mapping source
|
||||
(annotations/xml/yaml).
|
||||
-
|
||||
preFlush - The preFlush event occurs before the change-sets of all
|
||||
managed documents are computed. This both a lifecycle call back and
|
||||
and listener.
|
||||
-
|
||||
postFlush - The postFlush event occurs after the change-sets of all
|
||||
managed documents are computed.
|
||||
-
|
||||
onFlush - The onFlush event occurs after the change-sets of all
|
||||
managed documents are computed. This event is not a lifecycle
|
||||
callback.
|
||||
-
|
||||
onClear - The onClear event occurs after the UnitOfWork has had
|
||||
its state cleared.
|
||||
-
|
||||
documentNotFound - The documentNotFound event occurs when a proxy object
|
||||
could not be initialized. This event is not a lifecycle callback.
|
||||
-
|
||||
postCollectionLoad - The postCollectionLoad event occurs just after
|
||||
collection has been initialized (loaded) and before new elements
|
||||
are re-added to it.
|
||||
|
||||
You can access the Event constants from the ``Events`` class in the
|
||||
ODM package.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
use Doctrine\ODM\MongoDB\Events;
|
||||
|
||||
echo Events::preUpdate;
|
||||
|
||||
These can be hooked into by two different types of event
|
||||
listeners:
|
||||
|
||||
-
|
||||
Lifecycle Callbacks are methods on the document classes that are
|
||||
called when the event is triggered. They receive instances
|
||||
of ``Doctrine\ODM\MongoDB\Event\LifecycleEventArgs`` (see relevant
|
||||
examples below) as arguments and are specifically designed to allow
|
||||
changes inside the document classes state.
|
||||
-
|
||||
Lifecycle Event Listeners are classes with specific callback
|
||||
methods that receives some kind of ``EventArgs`` instance which
|
||||
give access to the document, DocumentManager or other relevant
|
||||
data.
|
||||
|
||||
.. note::
|
||||
|
||||
All Lifecycle events that happen during the ``flush()`` of
|
||||
a DocumentManager have very specific constraints on the allowed
|
||||
operations that can be executed. Please read the
|
||||
*Implementing Event Listeners* section very carefully to understand
|
||||
which operations are allowed in which lifecycle event.
|
||||
|
||||
Lifecycle Callbacks
|
||||
-------------------
|
||||
|
||||
A lifecycle event is a regular event with the additional feature of
|
||||
providing a mechanism to register direct callbacks inside the
|
||||
corresponding document classes that are executed when the lifecycle
|
||||
event occurs.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/** @Document @HasLifecycleCallbacks */
|
||||
class User
|
||||
{
|
||||
// ...
|
||||
|
||||
/**
|
||||
* @Field
|
||||
*/
|
||||
public $value;
|
||||
|
||||
/** @Field */
|
||||
private $createdAt;
|
||||
|
||||
/** @PrePersist */
|
||||
public function doStuffOnPrePersist(\Doctrine\ODM\MongoDB\Event\LifecycleEventArgs $eventArgs)
|
||||
{
|
||||
$this->createdAt = date('Y-m-d H:i:s');
|
||||
}
|
||||
|
||||
/** @PrePersist */
|
||||
public function doOtherStuffOnPrePersist(\Doctrine\ODM\MongoDB\Event\LifecycleEventArgs $eventArgs)
|
||||
{
|
||||
$this->value = 'changed from prePersist callback!';
|
||||
}
|
||||
|
||||
/** @PostPersist */
|
||||
public function doStuffOnPostPersist(\Doctrine\ODM\MongoDB\Event\LifecycleEventArgs $eventArgs)
|
||||
{
|
||||
$this->value = 'changed from postPersist callback!';
|
||||
}
|
||||
|
||||
/** @PreLoad */
|
||||
public function doStuffOnPreLoad(\Doctrine\ODM\MongoDB\Event\PreLoadEventArgs $eventArgs)
|
||||
{
|
||||
$data =& $eventArgs->getData();
|
||||
$data['value'] = 'changed from preLoad callback';
|
||||
}
|
||||
|
||||
/** @PostLoad */
|
||||
public function doStuffOnPostLoad(\Doctrine\ODM\MongoDB\Event\LifecycleEventArgs $eventArgs)
|
||||
{
|
||||
$this->value = 'changed from postLoad callback!';
|
||||
}
|
||||
|
||||
/** @PreUpdate */
|
||||
public function doStuffOnPreUpdate(\Doctrine\ODM\MongoDB\Event\PreUpdateEventArgs $eventArgs)
|
||||
{
|
||||
$this->value = 'changed from preUpdate callback!';
|
||||
}
|
||||
|
||||
/** @PreFlush */
|
||||
public function preFlush(\Doctrine\ODM\MongoDB\Event\PreFlushEventArgs $eventArgs)
|
||||
{
|
||||
$this->value = 'changed from preFlush callback!';
|
||||
}
|
||||
}
|
||||
|
||||
Note that when using annotations you have to apply the
|
||||
@HasLifecycleCallbacks marker annotation on the document class.
|
||||
|
||||
Listening to Lifecycle Events
|
||||
-----------------------------
|
||||
|
||||
Lifecycle event listeners are much more powerful than the simple
|
||||
lifecycle callbacks that are defined on the document classes. They
|
||||
allow to implement re-usable behaviours between different document
|
||||
classes, yet require much more detailed knowledge about the inner
|
||||
workings of the DocumentManager and UnitOfWork. Please read the
|
||||
*Implementing Event Listeners* section carefully if you are trying
|
||||
to write your own listener.
|
||||
|
||||
To register an event listener you have to hook it into the
|
||||
EventManager that is passed to the DocumentManager factory:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$eventManager = new EventManager();
|
||||
$eventManager->addEventListener(array(Events::preUpdate), new MyEventListener());
|
||||
$eventManager->addEventSubscriber(new MyEventSubscriber());
|
||||
|
||||
$documentManager = DocumentManager::create($mongo, $config, $eventManager);
|
||||
|
||||
You can also retrieve the event manager instance after the
|
||||
DocumentManager was created:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$documentManager->getEventManager()->addEventListener(array(Events::preUpdate), new MyEventListener());
|
||||
$documentManager->getEventManager()->addEventSubscriber(new MyEventSubscriber());
|
||||
|
||||
Implementing Event Listeners
|
||||
----------------------------
|
||||
|
||||
This section explains what is and what is not allowed during
|
||||
specific lifecycle events of the UnitOfWork. Although you get
|
||||
passed the DocumentManager in all of these events, you have to
|
||||
follow this restrictions very carefully since operations in the
|
||||
wrong event may produce lots of different errors, such as
|
||||
inconsistent data and lost updates/persists/removes.
|
||||
|
||||
prePersist
|
||||
~~~~~~~~~~
|
||||
|
||||
Listen to the ``prePersist`` event:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$test = new EventTest();
|
||||
$evm = $dm->getEventManager();
|
||||
$evm->addEventListener(Events::prePersist, $test);
|
||||
|
||||
Define the ``EventTest`` class:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
class EventTest
|
||||
{
|
||||
public function prePersist(\Doctrine\ODM\MongoDB\Event\LifecycleEventArgs $eventArgs)
|
||||
{
|
||||
$document = $eventArgs->getDocument();
|
||||
$document->setSomething();
|
||||
}
|
||||
}
|
||||
|
||||
preLoad
|
||||
~~~~~~~
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$test = new EventTest();
|
||||
$evm = $dm->getEventManager();
|
||||
$evm->addEventListener(Events::preLoad, $test);
|
||||
|
||||
Define the ``EventTest`` class with a ``preLoad()`` method:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
class EventTest
|
||||
{
|
||||
public function preLoad(\Doctrine\ODM\MongoDB\Event\PreLoadEventArgs $eventArgs)
|
||||
{
|
||||
$data =& $eventArgs->getData();
|
||||
// do something
|
||||
}
|
||||
}
|
||||
|
||||
postLoad
|
||||
~~~~~~~~
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$test = new EventTest();
|
||||
$evm = $dm->getEventManager();
|
||||
$evm->addEventListener(Events::postLoad, $test);
|
||||
|
||||
Define the ``EventTest`` class with a ``postLoad()`` method:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
class EventTest
|
||||
{
|
||||
public function postLoad(\Doctrine\ODM\MongoDB\Event\LifecycleEventArgs $eventArgs)
|
||||
{
|
||||
$document = $eventArgs->getDocument();
|
||||
// do something
|
||||
}
|
||||
}
|
||||
|
||||
preRemove
|
||||
~~~~~~~~~
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$test = new EventTest();
|
||||
$evm = $dm->getEventManager();
|
||||
$evm->addEventListener(Events::preRemove, $test);
|
||||
|
||||
Define the ``EventTest`` class with a ``preRemove()`` method:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
class EventTest
|
||||
{
|
||||
public function preRemove(\Doctrine\ODM\MongoDB\Event\LifecycleEventArgs $eventArgs)
|
||||
{
|
||||
$document = $eventArgs->getDocument();
|
||||
// do something
|
||||
}
|
||||
}
|
||||
|
||||
preFlush
|
||||
~~~~~~~~
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$test = new EventTest();
|
||||
$evm = $dm->getEventManager();
|
||||
$evm->addEventListener(Events::preFlush, $test);
|
||||
|
||||
Define the ``EventTest`` class with a ``preFlush()`` method:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
class EventTest
|
||||
{
|
||||
public function preFlush(\Doctrine\ODM\MongoDB\Event\PreFlushEventArgs $eventArgs)
|
||||
{
|
||||
$dm = $eventArgs->getDocumentManager();
|
||||
$uow = $dm->getUnitOfWork();
|
||||
// do something
|
||||
}
|
||||
}
|
||||
|
||||
onFlush
|
||||
~~~~~~~
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$test = new EventTest();
|
||||
$evm = $dm->getEventManager();
|
||||
$evm->addEventListener(Events::onFlush, $test);
|
||||
|
||||
Define the ``EventTest`` class with a ``onFlush()`` method:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
class EventTest
|
||||
{
|
||||
public function onFlush(\Doctrine\ODM\MongoDB\Event\OnFlushEventArgs $eventArgs)
|
||||
{
|
||||
$dm = $eventArgs->getDocumentManager();
|
||||
$uow = $dm->getUnitOfWork();
|
||||
// do something
|
||||
}
|
||||
}
|
||||
|
||||
postFlush
|
||||
~~~~~~~~~
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$test = new EventTest();
|
||||
$evm = $dm->getEventManager();
|
||||
$evm->addEventListener(Events::postFlush, $test);
|
||||
|
||||
Define the ``EventTest`` class with a ``postFlush()`` method:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
class EventTest
|
||||
{
|
||||
public function postFlush(\Doctrine\ODM\MongoDB\Event\PostFlushEventArgs $eventArgs)
|
||||
{
|
||||
$dm = $eventArgs->getDocumentManager();
|
||||
$uow = $dm->getUnitOfWork();
|
||||
// do something
|
||||
}
|
||||
}
|
||||
|
||||
preUpdate
|
||||
~~~~~~~~~
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$test = new EventTest();
|
||||
$evm = $dm->getEventManager();
|
||||
$evm->addEventListener(Events::preUpdate, $test);
|
||||
|
||||
Define the ``EventTest`` class with a ``preUpdate()`` method:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
class EventTest
|
||||
{
|
||||
public function preUpdate(\Doctrine\ODM\MongoDB\Event\LifecycleEventArgs $eventArgs)
|
||||
{
|
||||
$document = $eventArgs->getDocument();
|
||||
$document->setSomething();
|
||||
$dm = $eventArgs->getDocumentManager();
|
||||
$class = $dm->getClassMetadata(get_class($document));
|
||||
$dm->getUnitOfWork()->recomputeSingleDocumentChangeSet($class, $document);
|
||||
}
|
||||
}
|
||||
|
||||
.. note::
|
||||
|
||||
If you modify a document in the preUpdate event you must call ``recomputeSingleDocumentChangeSet``
|
||||
for the modified document in order for the changes to be persisted.
|
||||
|
||||
onClear
|
||||
~~~~~~~
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$test = new EventTest();
|
||||
$evm = $dm->getEventManager();
|
||||
$evm->addEventListener(Events::onClear, $test);
|
||||
|
||||
Define the ``EventTest`` class with a ``onClear()`` method:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
class EventTest
|
||||
{
|
||||
public function onClear(\Doctrine\ODM\MongoDB\Event\OnClearEventArgs $eventArgs)
|
||||
{
|
||||
$class = $eventArgs->getDocumentClass();
|
||||
$dm = $eventArgs->getDocumentManager();
|
||||
$uow = $dm->getUnitOfWork();
|
||||
|
||||
// Check if event clears all documents.
|
||||
if ($eventArgs->clearsAllDocuments()) {
|
||||
// do something
|
||||
}
|
||||
// do something
|
||||
}
|
||||
}
|
||||
|
||||
documentNotFound
|
||||
~~~~~~~~~~~~~~~~
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$test = new EventTest();
|
||||
$evm = $dm->getEventManager();
|
||||
$evm->addEventListener(Events::documentNotFound, $test);
|
||||
|
||||
Define the ``EventTest`` class with a ``documentNotFound()`` method:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
class EventTest
|
||||
{
|
||||
public function documentNotFound(\Doctrine\ODM\MongoDB\Event\DocumentNotFoundEventArgs $eventArgs)
|
||||
{
|
||||
$proxy = $eventArgs->getObject();
|
||||
$identifier = $eventArgs->getIdentifier();
|
||||
// do something
|
||||
// To prevent the documentNotFound exception from being thrown, call the disableException() method:
|
||||
$eventArgs->disableException();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
postUpdate, postRemove, postPersist
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$test = new EventTest();
|
||||
$evm = $dm->getEventManager();
|
||||
$evm->addEventListener(Events::postUpdate, $test);
|
||||
$evm->addEventListener(Events::postRemove, $test);
|
||||
$evm->addEventListener(Events::postPersist, $test);
|
||||
|
||||
Define the ``EventTest`` class with a ``postUpdate()``, ``postRemove()`` and ``postPersist()`` method:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
class EventTest
|
||||
{
|
||||
public function postUpdate(\Doctrine\ODM\MongoDB\Event\LifecycleEventArgs $eventArgs)
|
||||
{
|
||||
}
|
||||
|
||||
public function postRemove(\Doctrine\ODM\MongoDB\Event\LifecycleEventArgs $eventArgs)
|
||||
{
|
||||
}
|
||||
|
||||
public function postPersist(\Doctrine\ODM\MongoDB\Event\LifecycleEventArgs $eventArgs)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
postCollectionLoad
|
||||
~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. note::
|
||||
This event was introduced in version 1.1
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$test = new EventTest();
|
||||
$evm = $dm->getEventManager();
|
||||
$evm->addEventListener(Events::postCollectionLoad, $test);
|
||||
|
||||
Define the ``EventTest`` class with a ``postCollectionLoad()`` method:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
class EventTest
|
||||
{
|
||||
public function postCollectionLoad(\Doctrine\ODM\MongoDB\Event\PostCollectionLoadEventArgs $eventArgs)
|
||||
{
|
||||
$collection = $eventArgs->getCollection();
|
||||
if ($collection instanceof \Malarzm\Collections\DiffableCollection) {
|
||||
$collection->snapshot();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Load ClassMetadata Event
|
||||
------------------------
|
||||
|
||||
When the mapping information for a document is read, it is
|
||||
populated in to a ``ClassMetadata`` instance. You can hook in to
|
||||
this process and manipulate the instance with the ``loadClassMetadata`` event:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$test = new EventTest();
|
||||
$metadataFactory = $dm->getMetadataFactory();
|
||||
$evm = $dm->getEventManager();
|
||||
$evm->addEventListener(Events::loadClassMetadata, $test);
|
||||
|
||||
class EventTest
|
||||
{
|
||||
public function loadClassMetadata(\Doctrine\ODM\MongoDB\Event\LoadClassMetadataEventArgs $eventArgs)
|
||||
{
|
||||
$classMetadata = $eventArgs->getClassMetadata();
|
||||
$fieldMapping = array(
|
||||
'fieldName' => 'about',
|
||||
'type' => 'string'
|
||||
);
|
||||
$classMetadata->mapField($fieldMapping);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
.. _filters:
|
||||
|
||||
Filters
|
||||
=======
|
||||
|
||||
Doctrine features a filter system that allows the developer to add additional
|
||||
criteria to queries, regardless of where the query is generated within the
|
||||
application (e.g. from a query builder, loading referenced documents). This is
|
||||
useful for excluding documents at a low level, to ensure that they are neither
|
||||
returned from MongoDB nor hydrated by ODM.
|
||||
|
||||
Example filter class
|
||||
--------------------
|
||||
|
||||
Throughout this document, the example ``MyLocaleFilter`` class will be used to
|
||||
illustrate how the filter feature works. A filter class must extend the base
|
||||
``Doctrine\ODM\MongoDB\Query\Filter\BsonFilter`` class and implement the
|
||||
``addFilterCriteria()`` method. This method receives ``ClassMetadata`` and is
|
||||
invoked whenever a query is prepared for any class. Since filters are typically
|
||||
designed with a specific class or interface in mind, ``addFilterCriteria()``
|
||||
will frequently start by checking ``ClassMetadata`` and returning immediately if
|
||||
it is not supported.
|
||||
|
||||
Parameters for the query should be set on the filter object by calling the
|
||||
``BsonFilter::setParameter()`` method. Within the filter class, parameters
|
||||
should be accessed via ``BsonFilter::getParameter()``.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
namespace Vendor\Filter;
|
||||
|
||||
use Doctrine\ODM\MongoDB\Mapping\ClassMetadata;
|
||||
use Doctrine\ODM\MongoDB\Query\Filter\BsonFilter;
|
||||
|
||||
class MyLocaleFilter extends BsonFilter
|
||||
{
|
||||
public function addFilterCriteria(ClassMetadata $targetDocument)
|
||||
{
|
||||
// Check if the entity implements the LocalAware interface
|
||||
if ( ! $targetDocument->reflClass->implementsInterface('LocaleAware')) {
|
||||
return array();
|
||||
}
|
||||
|
||||
return array('locale' => $this->getParameter('locale'));
|
||||
}
|
||||
}
|
||||
|
||||
Configuration
|
||||
-------------
|
||||
Filter classes are added to the configuration as following:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$config->addFilter('locale', '\Vendor\Filter\MyLocaleFilter');
|
||||
|
||||
The ``Configuration#addFilter()`` method takes a name for the filter and the
|
||||
name of the filter class, which will be constructed as necessary.
|
||||
|
||||
An optional third parameter may be used to set parameters at configuration time:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$config->addFilter('locale', '\Vendor\Filter\MyLocaleFilter', array('locale' => 'en'));
|
||||
|
||||
Disabling/Enabling Filters and Setting Parameters
|
||||
-------------------------------------------------
|
||||
|
||||
Filters can be disabled and enabled via the ``FilterCollection``, which is
|
||||
stored in the ``DocumentManager``. The ``FilterCollection#enable($name)`` method
|
||||
may be used to enabled and return a filter, after which you may set parameters.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$filter = $dm->getFilterCollection()->enable("locale");
|
||||
$filter->setParameter('locale', array('$in' => array('en', 'fr'));
|
||||
|
||||
// Disable the filter (perhaps temporarily to run an unfiltered query)
|
||||
$filter = $dm->getFilterCollection()->disable("locale");
|
||||
|
||||
.. warning::
|
||||
|
||||
Disabling and enabling filters has no effect on managed documents. If you
|
||||
want to refresh or reload an object after having modified a filter or the
|
||||
FilterCollection, then you should clear the DocumentManager and re-fetch
|
||||
your documents so the new filtering rules may be applied.
|
||||
@@ -0,0 +1,84 @@
|
||||
Find and Modify
|
||||
===============
|
||||
|
||||
.. note::
|
||||
|
||||
From MongoDB.org:
|
||||
|
||||
MongoDB supports a "find, modify, and return" command. This command
|
||||
can be used to atomically modify a document (at most one) and
|
||||
return it. Note that, by default, the document returned will not
|
||||
include the modifications made on the update.
|
||||
|
||||
Doctrine fully integrates the find and modify functionality to the
|
||||
query builder object so you can easily run these types of queries!
|
||||
|
||||
Update
|
||||
------
|
||||
|
||||
For example you can update a job and return it:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$job = $dm->createQueryBuilder('Job')
|
||||
// Find the job
|
||||
->findAndUpdate()
|
||||
->field('in_progress')->equals(false)
|
||||
->sort('priority', 'desc')
|
||||
|
||||
// Update found job
|
||||
->field('started')->set(new \MongoDate())
|
||||
->field('in_progress')->set(true)
|
||||
->getQuery()
|
||||
->execute();
|
||||
|
||||
If you want to update a job and return the new document you can
|
||||
call the ``returnNew()`` method.
|
||||
|
||||
Here is an example where we return the new updated job document:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
$job = $dm->createQueryBuilder('Job')
|
||||
// Find the job
|
||||
->findAndUpdate()
|
||||
->returnNew()
|
||||
->field('in_progress')->equals(false)
|
||||
->sort('priority', 'desc')
|
||||
|
||||
// Update found job
|
||||
->field('started')->set(new \MongoDate())
|
||||
->field('in_progress')->set(true)
|
||||
->getQuery()
|
||||
->execute();
|
||||
|
||||
The returned ``$job`` will be a managed ``Job`` instance with the
|
||||
``started`` and ``in_progress`` fields updated.
|
||||
|
||||
Remove
|
||||
------
|
||||
|
||||
You can also remove a document and return it:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$job = $dm->createQueryBuilder('Job')
|
||||
->findAndRemove()
|
||||
->sort('priority', 'desc')
|
||||
->getQuery()
|
||||
->execute();
|
||||
|
||||
You can read more about the find and modify functionality on the
|
||||
`MongoDB website <https://docs.mongodb.com/manual/reference/method/db.collection.findAndModify/>`_.
|
||||
|
||||
.. note::
|
||||
|
||||
If you don't need to return the document, you can use just run a normal update which can
|
||||
affect multiple documents, as well. For multiple update to happen you need to use
|
||||
``->updateMany()`` method of the builder (or ``update()->multiple()`` combination that
|
||||
was deprecated in version 1.2).
|
||||
@@ -0,0 +1,141 @@
|
||||
Geospatial Queries
|
||||
==================
|
||||
|
||||
You can execute some special queries when using geospatial indexes
|
||||
like checking for documents within a rectangle or circle.
|
||||
|
||||
Mapping
|
||||
-------
|
||||
|
||||
First, setup some documents like the following:
|
||||
|
||||
.. configuration-block::
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @Document
|
||||
* @Index(keys={"coordinates"="2d"})
|
||||
*/
|
||||
class City
|
||||
{
|
||||
/** @Id */
|
||||
public $id;
|
||||
|
||||
/** @Field(type="string") */
|
||||
public $name;
|
||||
|
||||
/** @EmbedOne(targetDocument="Coordinates") */
|
||||
public $coordinates;
|
||||
|
||||
/** @Distance */
|
||||
public $distance;
|
||||
}
|
||||
|
||||
/** @EmbeddedDocument */
|
||||
class Coordinates
|
||||
{
|
||||
/** @Field(type="float") */
|
||||
public $x;
|
||||
|
||||
/** @Field(type="float") */
|
||||
public $y;
|
||||
}
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<indexes>
|
||||
<index>
|
||||
<key name="coordinates" order="2d" />
|
||||
</index>
|
||||
</indexes>
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
indexes:
|
||||
coordinates:
|
||||
keys:
|
||||
coordinates: 2d
|
||||
|
||||
Near Query
|
||||
----------
|
||||
|
||||
Now you can execute queries against these documents like the
|
||||
following. Check for the 10 nearest cities to a given longitude
|
||||
and latitude with the ``near($longitude, $latitude)`` method:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$cities = $this->dm->createQuery('City')
|
||||
->field('coordinates')->near(-120, 40)
|
||||
->execute();
|
||||
|
||||
.. _geonear:
|
||||
|
||||
GeoNear Command
|
||||
---------------
|
||||
|
||||
You can also execute the `geoNear command`_ using the query builder's
|
||||
``geoNear()`` method. Additional builder methods can be used to set options for
|
||||
this command (e.g. ``distanceMultipler()``, ``maxDistance()``, ``spherical()``).
|
||||
Unlike ``near()``, which uses a query operator, ``geoNear()`` does not require
|
||||
the location field to be specified in the builder, as MongoDB will use the
|
||||
single geospatial index for the collection. Documents will be returned in order
|
||||
of nearest to farthest.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$cities = $this->dm->createQuery('City')
|
||||
->geoNear(-120, 40)
|
||||
->spherical(true)
|
||||
// Convert radians to kilometers (use 3963.192 for miles)
|
||||
->distanceMultiplier(6378.137)
|
||||
->execute();
|
||||
|
||||
If the model has a property mapped with :ref:`@Distance <annotation_distance>`,
|
||||
that field will be set with the calculated distance between the document and the
|
||||
query coordinates.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
foreach ($cities as $city) {
|
||||
printf("%s is %f kilometers away.\n", $city->name, $city->distance);
|
||||
}
|
||||
|
||||
.. _`geoNear command`: https://docs.mongodb.com/manual/reference/command/geoNear/
|
||||
|
||||
Within Box
|
||||
----------
|
||||
|
||||
You can also query for cities within a given rectangle using the
|
||||
``withinBox($x1, $y1, $x2, $y2)`` method:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$cities = $this->dm->createQuery('City')
|
||||
->field('coordinates')->withinBox(41, 41, 72, 72)
|
||||
->execute();
|
||||
|
||||
Within Center
|
||||
-------------
|
||||
|
||||
In addition to boxes you can check for cities within a circle using
|
||||
the ``withinCenter($x, $y, $radius)`` method:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$cities = $this->dm->createQuery('City')
|
||||
->field('coordinates')->withinCenter(50, 50, 20)
|
||||
->execute();
|
||||
@@ -0,0 +1,549 @@
|
||||
Indexes
|
||||
=======
|
||||
|
||||
Working with indexes in the MongoDB ODM is pretty straight forward.
|
||||
You can have multiple indexes, they can consist of multiple fields,
|
||||
they can be unique and you can give them an order. In this chapter
|
||||
we'll show you examples of indexes using annotations.
|
||||
|
||||
First here is an example where we put an index on a single
|
||||
property:
|
||||
|
||||
.. configuration-block::
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
namespace Documents;
|
||||
|
||||
/** @Document */
|
||||
class User
|
||||
{
|
||||
/** @Id */
|
||||
public $id;
|
||||
|
||||
/** @Field(type="string") @Index */
|
||||
public $username;
|
||||
}
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<field name="username" index="true" />
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
fields:
|
||||
username:
|
||||
index: true
|
||||
|
||||
|
||||
Index Options
|
||||
-------------
|
||||
|
||||
You can customize the index with some additional options:
|
||||
|
||||
-
|
||||
**name** - The name of the index. This can be useful if you are
|
||||
indexing many keys and Mongo complains about the index name being
|
||||
too long.
|
||||
-
|
||||
**dropDups** - If a unique index is being created and duplicate
|
||||
values exist, drop all but one duplicate value.
|
||||
-
|
||||
**background** - Create indexes in the background while other
|
||||
operations are taking place. By default, index creation happens
|
||||
synchronously. If you specify TRUE with this option, index creation
|
||||
will be asynchronous.
|
||||
-
|
||||
**safe** - You can specify a boolean value for checking if the
|
||||
index creation succeeded. The driver will throw a
|
||||
MongoCursorException if index creation failed.
|
||||
-
|
||||
**expireAfterSeconds** - If you specify this option then the associated
|
||||
document will be automatically removed when the provided time (in seconds)
|
||||
has passed. This option is bound to a number of limitations, which
|
||||
are documented at https://docs.mongodb.com/manual/tutorial/expire-data/.
|
||||
-
|
||||
**order** - The order of the index (asc or desc).
|
||||
-
|
||||
**unique** - Create a unique index.
|
||||
-
|
||||
**sparse** - Create a sparse index. If a unique index is being created
|
||||
the sparse option will allow duplicate null entries, but the field must be
|
||||
unique otherwise.
|
||||
-
|
||||
**partialFilterExpression** - Create a partial index. Partial indexes only
|
||||
index the documents in a collection that meet a specified filter expression.
|
||||
By indexing a subset of the documents in a collection, partial indexes have
|
||||
lower storage requirements and reduced performance costs for index creation
|
||||
and maintenance. This feature was introduced with MongoDB 3.2 and is not
|
||||
available on older versions.
|
||||
|
||||
Unique Index
|
||||
------------
|
||||
|
||||
.. configuration-block::
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
namespace Documents;
|
||||
|
||||
/** @Document */
|
||||
class User
|
||||
{
|
||||
/** @Id */
|
||||
public $id;
|
||||
|
||||
/** @Field(type="string") @Index(unique=true, order="asc") */
|
||||
public $username;
|
||||
}
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<field fieldName="username" index="true" unique="true" order="asc" />
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
fields:
|
||||
username:
|
||||
index: true
|
||||
unique: true
|
||||
order: true
|
||||
|
||||
For your convenience you can quickly specify a unique index with
|
||||
``@UniqueIndex``:
|
||||
|
||||
.. configuration-block::
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
namespace Documents;
|
||||
|
||||
/** @Document */
|
||||
class User
|
||||
{
|
||||
/** @Id */
|
||||
public $id;
|
||||
|
||||
/** @Field(type="string") @UniqueIndex(order="asc") */
|
||||
public $username;
|
||||
}
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<field fieldName="username" unique="true" order="asc" />
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
fields:
|
||||
username:
|
||||
unique: true
|
||||
order: true
|
||||
|
||||
If you want to specify an index that consists of multiple fields
|
||||
you can specify them on the class doc block:
|
||||
|
||||
.. configuration-block::
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
namespace Documents;
|
||||
|
||||
/**
|
||||
* @Document
|
||||
* @UniqueIndex(keys={"accountId"="asc", "username"="asc"})
|
||||
*/
|
||||
class User
|
||||
{
|
||||
/** @Id */
|
||||
public $id;
|
||||
|
||||
/** @Field(type="int") */
|
||||
public $accountId;
|
||||
|
||||
/** @Field(type="string") */
|
||||
public $username;
|
||||
}
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<doctrine-mongo-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mongo-mapping"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mongo-mapping
|
||||
http://doctrine-project.org/schemas/orm/doctrine-mongo-mapping.xsd">
|
||||
|
||||
<document name="Documents\User">
|
||||
<indexes>
|
||||
<index>
|
||||
<option name="unique" value="true" />
|
||||
<key name="accountId" order="asc" />
|
||||
<key name="username" order="asc" />
|
||||
</index>
|
||||
</indexes>
|
||||
</document>
|
||||
</doctrine-mongo-mapping>
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
Documents\User:
|
||||
indexes:
|
||||
usernameacctid:
|
||||
options:
|
||||
unique: true
|
||||
keys:
|
||||
accountId:
|
||||
order: asc
|
||||
username:
|
||||
order: asc
|
||||
|
||||
To specify multiple indexes you must use the ``@Indexes``
|
||||
annotation:
|
||||
|
||||
.. configuration-block::
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @Document
|
||||
* @Indexes({
|
||||
* @Index(keys={"accountId"="asc"}),
|
||||
* @Index(keys={"username"="asc"})
|
||||
* })
|
||||
*/
|
||||
class User
|
||||
{
|
||||
/** @Id */
|
||||
public $id;
|
||||
|
||||
/** @Field(type="int") */
|
||||
public $accountId;
|
||||
|
||||
/** @Field(type="string") */
|
||||
public $username;
|
||||
}
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<doctrine-mongo-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mongo-mapping"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mongo-mapping
|
||||
http://doctrine-project.org/schemas/orm/doctrine-mongo-mapping.xsd">
|
||||
|
||||
<document name="Documents\User">
|
||||
<indexes>
|
||||
<index>
|
||||
<key name="accountId" order="asc" />
|
||||
</index>
|
||||
<index>
|
||||
<key name="username" order="asc" />
|
||||
</index>
|
||||
</indexes>
|
||||
</document>
|
||||
</doctrine-mongo-mapping>
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
Documents\User:
|
||||
indexes:
|
||||
accountId:
|
||||
keys:
|
||||
accountId:
|
||||
order: asc
|
||||
username:
|
||||
keys:
|
||||
username:
|
||||
order: asc
|
||||
|
||||
Embedded Indexes
|
||||
----------------
|
||||
|
||||
You can specify indexes on embedded documents just like you do on normal documents. When Doctrine
|
||||
creates the indexes for a document it will also create all the indexes from its mapped embedded
|
||||
documents.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
namespace Documents;
|
||||
|
||||
/** @EmbeddedDocument */
|
||||
class Comment
|
||||
{
|
||||
/** @Field(type="date") @Index */
|
||||
private $date;
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
Now if we had a ``BlogPost`` document with the ``Comment`` document embedded many times:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
namespace Documents;
|
||||
|
||||
/** @Document */
|
||||
class BlogPost
|
||||
{
|
||||
// ...
|
||||
|
||||
/** @Field(type="string") @Index */
|
||||
private $slug;
|
||||
|
||||
/** @EmbedMany(targetDocument="Comment") */
|
||||
private $comments;
|
||||
}
|
||||
|
||||
If we were to create the indexes with the ``SchemaManager``:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$sm->ensureIndexes();
|
||||
|
||||
It will create the indexes from the ``BlogPost`` document but will also create the indexes that are
|
||||
defined on the ``Comment`` embedded document. The following would be executed on the underlying MongoDB
|
||||
database:
|
||||
|
||||
..
|
||||
|
||||
db.BlogPost.ensureIndexes({ 'slug' : 1, 'comments.date': 1 })
|
||||
|
||||
Also, for your convenience you can create the indexes for your mapped documents from the
|
||||
:doc:`console <console-commands>`:
|
||||
|
||||
..
|
||||
|
||||
$ php mongodb.php mongodb:schema:create --index
|
||||
|
||||
.. note::
|
||||
|
||||
If you are :ref:`mixing document types <embed_mixing_document_types>` for your
|
||||
embedded documents, ODM will not be able to create indexes for their fields
|
||||
unless you specify a discriminator map for the :ref:`embed-one <embed_one>`
|
||||
or :ref:`embed-many <embed_many>` relationship.
|
||||
|
||||
Geospatial Indexing
|
||||
-------------------
|
||||
|
||||
You can specify a geospatial index by just specifying the keys and
|
||||
options structures manually:
|
||||
|
||||
.. configuration-block::
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @Document
|
||||
* @Index(keys={"coordinates"="2d"})
|
||||
*/
|
||||
class Place
|
||||
{
|
||||
/** @Id */
|
||||
public $id;
|
||||
|
||||
/** @EmbedOne(targetDocument="Coordinates") */
|
||||
public $coordinates;
|
||||
}
|
||||
|
||||
/** @EmbeddedDocument */
|
||||
class Coordinates
|
||||
{
|
||||
/** @Field(type="float") */
|
||||
public $latitude;
|
||||
|
||||
/** @Field(type="float") */
|
||||
public $longitude;
|
||||
}
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<indexes>
|
||||
<index>
|
||||
<key name="coordinates" order="2d" />
|
||||
</index>
|
||||
</indexes>
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
indexes:
|
||||
coordinates:
|
||||
keys:
|
||||
coordinates: 2d
|
||||
|
||||
Partial indexes
|
||||
---------------
|
||||
|
||||
You can create a partial index by adding a ``partialFilterExpression`` to any
|
||||
index.
|
||||
|
||||
.. configuration-block::
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @Document
|
||||
* @Index(keys={"city"="asc"}, partialFilterExpression={"version"={"$gt"=1}})
|
||||
*/
|
||||
class Place
|
||||
{
|
||||
/** @Id */
|
||||
public $id;
|
||||
|
||||
/** @Field(type="string") */
|
||||
public $city;
|
||||
|
||||
/** @Field(type="int") */
|
||||
public $version;
|
||||
}
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<indexes>
|
||||
<index>
|
||||
<key name="city" order="asc" />
|
||||
<partial-filter-expression>
|
||||
<field name="version" value="1" operator="gt" />
|
||||
</partial-filter-expression>
|
||||
</index>
|
||||
</indexes>
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
indexes:
|
||||
partialIndexExample:
|
||||
keys:
|
||||
coordinates: asc
|
||||
options:
|
||||
partialFilterExpression:
|
||||
version: { $gt: 1 }
|
||||
|
||||
.. note::
|
||||
|
||||
Partial indexes are only available with MongoDB 3.2 or newer. For more
|
||||
information on partial filter expressions, read the
|
||||
`official MongoDB documentation <https://docs.mongodb.com/manual/core/index-partial/>`_.
|
||||
|
||||
Requiring Indexes
|
||||
-----------------
|
||||
|
||||
.. note::
|
||||
Requiring Indexes was deprecated in 1.2 and will be removed in 2.0.
|
||||
|
||||
Sometimes you may want to require indexes for all your queries to ensure you don't let stray unindexed queries
|
||||
make it to the database and cause performance problems.
|
||||
|
||||
|
||||
.. configuration-block::
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @Document(requireIndexes=true)
|
||||
*/
|
||||
class Place
|
||||
{
|
||||
/** @Id */
|
||||
public $id;
|
||||
|
||||
/** @Field(type="string") @Index */
|
||||
public $city;
|
||||
}
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
// Documents.Place.dcm.xml
|
||||
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
|
||||
<doctrine-mongo-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mongo-mapping"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mongo-mapping
|
||||
http://doctrine-project.org/schemas/orm/doctrine-mongo-mapping.xsd">
|
||||
|
||||
<document name="Documents\Place" require-indexes="true">
|
||||
<field fieldName="id" id="true" />
|
||||
<field fieldName="city" type="string" />
|
||||
<indexes>
|
||||
<index>
|
||||
<key name="city">
|
||||
</index>
|
||||
</indexes>
|
||||
</document>
|
||||
</doctrine-mongo-mapping>
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
# Documents.Place.dcm.yml
|
||||
|
||||
Documents\Place:
|
||||
fields:
|
||||
id:
|
||||
id: true
|
||||
city:
|
||||
type: string
|
||||
indexes:
|
||||
index1:
|
||||
keys:
|
||||
city: asc
|
||||
|
||||
When you run queries it will check that it is indexed and throw an exception if it is not indexed:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$qb = $dm->createQueryBuilder('Documents\Place')
|
||||
->field('city')->equals('Nashville');
|
||||
$query = $qb->getQuery();
|
||||
$places = $query->execute();
|
||||
|
||||
When you execute the query it will throw an exception if `city` was not indexed in the database. You can control
|
||||
whether or not an exception will be thrown by using the `requireIndexes()` method:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$qb->requireIndexes(false);
|
||||
|
||||
You can also check if the query is indexed and with the `isIndexed()` method and use it to display your
|
||||
own notification when a query is unindexed:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$query = $qb->getQuery();
|
||||
if (!$query->isIndexed()) {
|
||||
$notifier->addError('Cannot execute queries that are not indexed.');
|
||||
}
|
||||
|
||||
If you don't want to require indexes for all queries you can set leave `requireIndexes` as false and control
|
||||
it on a per query basis:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$qb->requireIndexes(true);
|
||||
$query = $qb->getQuery();
|
||||
$results = $query->execute();
|
||||
@@ -0,0 +1,280 @@
|
||||
.. _inheritance_mapping:
|
||||
|
||||
Inheritance Mapping
|
||||
===================
|
||||
|
||||
Doctrine currently offers two supported methods of inheritance:
|
||||
:ref:`single collection <single_collection_inheritance>` and
|
||||
:ref:`collection per class <collection_per_class_inheritance>` inheritance.
|
||||
|
||||
Mapped Superclasses
|
||||
-------------------
|
||||
|
||||
A mapped superclass is an abstract or concrete class that provides mapping
|
||||
information for its subclasses, but is not itself a document. Typically, the
|
||||
purpose of such a mapped superclass is to define state and mapping information
|
||||
that is common to multiple document classes.
|
||||
|
||||
Just like non-mapped classes, mapped superclasses may appear in the middle of
|
||||
an otherwise mapped inheritance hierarchy (through
|
||||
:ref:`single collection <single_collection_inheritance>` or
|
||||
:ref:`collection per class <collection_per_class_inheritance>`) inheritance.
|
||||
|
||||
.. note::
|
||||
|
||||
A mapped superclass cannot be a document and is not queryable.
|
||||
|
||||
Example:
|
||||
|
||||
.. configuration-block::
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
namespace Documents;
|
||||
|
||||
/** @MappedSuperclass */
|
||||
abstract class BaseDocument
|
||||
{
|
||||
}
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<doctrine-mongo-mapping xmlns="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping
|
||||
http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping.xsd">
|
||||
<mapped-superclass name="Documents\BaseDocument">
|
||||
</mapped-superclass>
|
||||
</doctrine-mongo-mapping>
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
Documents\BaseDocument:
|
||||
type: mappedSuperclass
|
||||
|
||||
.. _single_collection_inheritance:
|
||||
|
||||
Single Collection Inheritance
|
||||
-----------------------------
|
||||
|
||||
In single collection inheritance, each document is stored in a single collection
|
||||
and a discriminator field is used to distinguish one document type from another.
|
||||
|
||||
Simple example:
|
||||
|
||||
.. configuration-block::
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
namespace Documents;
|
||||
|
||||
/**
|
||||
* @Document
|
||||
* @InheritanceType("SINGLE_COLLECTION")
|
||||
* @DiscriminatorField("type")
|
||||
* @DiscriminatorMap({"person"="Person", "employee"="Employee"})
|
||||
*/
|
||||
class Person
|
||||
{
|
||||
// ...
|
||||
}
|
||||
|
||||
/**
|
||||
* @Document
|
||||
*/
|
||||
class Employee extends Person
|
||||
{
|
||||
// ...
|
||||
}
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<doctrine-mongo-mapping xmlns="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping
|
||||
http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping.xsd">
|
||||
<document name="Documents\Person" inheritance-type="SINGLE_COLLECTION">
|
||||
<discriminator-field name="type" />
|
||||
<discriminator-map>
|
||||
<discriminator-mapping value="person" class="Person" />
|
||||
<discriminator-mapping value="employee" class="Employee" />
|
||||
</discriminator-map>
|
||||
</document>
|
||||
</doctrine-mongo-mapping>
|
||||
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<doctrine-mongo-mapping xmlns="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping
|
||||
http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping.xsd">
|
||||
<document name="Documents\Employee">
|
||||
</document>
|
||||
</doctrine-mongo-mapping>
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
Documents\Person:
|
||||
type: document
|
||||
inheritanceType: SINGLE_COLLECTION
|
||||
discriminatorField: type
|
||||
discriminatorMap:
|
||||
person: Person
|
||||
employee: Employee
|
||||
|
||||
The discriminator value allows Doctrine to infer the class name to instantiate
|
||||
when hydrating a document. If a discriminator map is used, the discriminator
|
||||
value will be used to look up the class name in the map.
|
||||
|
||||
Now, if we query for a Person and its discriminator value is ``employee``, we
|
||||
would get an Employee instance back:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$employee = new Employee();
|
||||
// ...
|
||||
$dm->persist($employee);
|
||||
$dm->flush();
|
||||
|
||||
$employee = $dm->find('Person', $employee->getId()); // instanceof Employee
|
||||
|
||||
Even though we queried for a Person, Doctrine will know to return an Employee
|
||||
instance because of the discriminator map!
|
||||
|
||||
If your document structure has changed and you've added discriminators after
|
||||
already having a bunch of documents, you can specify a default value for the
|
||||
discriminator field:
|
||||
|
||||
.. configuration-block::
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
namespace Documents;
|
||||
|
||||
/**
|
||||
* @Document
|
||||
* @InheritanceType("SINGLE_COLLECTION")
|
||||
* @DiscriminatorField("type")
|
||||
* @DiscriminatorMap({"person"="Person", "employee"="Employee"})
|
||||
* @DefaultDiscriminatorValue("person")
|
||||
*/
|
||||
class Person
|
||||
{
|
||||
// ...
|
||||
}
|
||||
|
||||
/**
|
||||
* @Document
|
||||
*/
|
||||
class Employee extends Person
|
||||
{
|
||||
// ...
|
||||
}
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<doctrine-mongo-mapping xmlns="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping
|
||||
http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping.xsd">
|
||||
<document name="Documents\Person" inheritance-type="SINGLE_COLLECTION">
|
||||
<discriminator-field name="type" />
|
||||
<discriminator-map>
|
||||
<discriminator-mapping value="person" class="Person" />
|
||||
<discriminator-mapping value="employee" class="Employee" />
|
||||
</discriminator-map>
|
||||
<default-discriminator-value value="person" />
|
||||
</document>
|
||||
</doctrine-mongo-mapping>
|
||||
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<doctrine-mongo-mapping xmlns="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping
|
||||
http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping.xsd">
|
||||
<document name="Documents\Employee">
|
||||
</document>
|
||||
</doctrine-mongo-mapping>
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
Documents\Person:
|
||||
type: document
|
||||
inheritanceType: SINGLE_COLLECTION
|
||||
discriminatorField: type
|
||||
defaultDiscriminatorValue: person
|
||||
discriminatorMap:
|
||||
person: Person
|
||||
employee: Employee
|
||||
|
||||
.. _collection_per_class_inheritance:
|
||||
|
||||
Collection Per Class Inheritance
|
||||
--------------------------------
|
||||
|
||||
With collection per class inheritance, each document is stored in its own
|
||||
collection and contains all inherited fields:
|
||||
|
||||
.. configuration-block::
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
namespace Documents;
|
||||
|
||||
/**
|
||||
* @Document
|
||||
* @InheritanceType("COLLECTION_PER_CLASS")
|
||||
*/
|
||||
class Person
|
||||
{
|
||||
// ...
|
||||
}
|
||||
|
||||
/**
|
||||
* @Document
|
||||
*/
|
||||
class Employee extends Person
|
||||
{
|
||||
// ...
|
||||
}
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<doctrine-mongo-mapping xmlns="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping
|
||||
http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping.xsd">
|
||||
<document name="Documents\Person" inheritance-type="COLLECTION_PER_CLASS">
|
||||
</document>
|
||||
</doctrine-mongo-mapping>
|
||||
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<doctrine-mongo-mapping xmlns="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping
|
||||
http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping.xsd">
|
||||
<document name="Documents\Employee">
|
||||
</document>
|
||||
</doctrine-mongo-mapping>
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
Documents\Person:
|
||||
type: document
|
||||
inheritanceType: COLLECTION_PER_CLASS
|
||||
|
||||
A discriminator is not needed with this type of inheritance since the data is
|
||||
separated in different collections.
|
||||
@@ -0,0 +1,494 @@
|
||||
Introduction
|
||||
============
|
||||
|
||||
Doctrine MongoDB Object Document Mapper is built for PHP 5.3.0+ and
|
||||
provides transparent persistence for PHP objects to the popular `MongoDB`_ database by `10gen`_.
|
||||
|
||||
Features Overview
|
||||
-----------------
|
||||
|
||||
- Transparent persistence.
|
||||
- Map one or many embedded documents.
|
||||
- Map one or many referenced documents.
|
||||
- Create references between documents in different databases.
|
||||
- Map documents with Annotations, XML, YAML or plain old PHP code.
|
||||
- Documents can be stored on the `MongoGridFS <http://www.php.net/MongoGridFS>`_.
|
||||
- Collection per class(concrete) and single collection inheritance supported.
|
||||
- Map your Doctrine 2 ORM Entities to the ODM and use mixed data stores.
|
||||
- Inserts are performed using `MongoCollection::batchInsert() <http://us.php.net/manual/en/mongocollection.batchinsert.php>`_
|
||||
- Updates are performed using atomic operators.
|
||||
|
||||
Here is a quick example of some PHP object documents that demonstrates a few of the features:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
use Doctrine\Common\Collections\ArrayCollection;
|
||||
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
|
||||
use DateTime;
|
||||
|
||||
/** @ODM\MappedSuperclass */
|
||||
abstract class BaseEmployee
|
||||
{
|
||||
/** @ODM\Id */
|
||||
private $id;
|
||||
|
||||
/** @ODM\Field(type="int", strategy="increment") */
|
||||
private $changes = 0;
|
||||
|
||||
/** @ODM\Field(type="collection") */
|
||||
private $notes = array();
|
||||
|
||||
/** @ODM\Field(type="string") */
|
||||
private $name;
|
||||
|
||||
/** @ODM\Field(type="int") */
|
||||
private $salary;
|
||||
|
||||
/** @ODM\Field(type="date") */
|
||||
private $started;
|
||||
|
||||
/** @ODM\Field(type="date") */
|
||||
private $left;
|
||||
|
||||
/** @ODM\EmbedOne(targetDocument="Address") */
|
||||
private $address;
|
||||
|
||||
public function getId() { return $this->id; }
|
||||
|
||||
public function getChanges() { return $this->changes; }
|
||||
public function incrementChanges() { $this->changes++; }
|
||||
|
||||
public function getNotes() { return $this->notes; }
|
||||
public function addNote($note) { $this->notes[] = $note; }
|
||||
|
||||
public function getName() { return $this->name; }
|
||||
public function setName($name) { $this->name = $name; }
|
||||
|
||||
public function getSalary() { return $this->salary; }
|
||||
public function setSalary($salary) { $this->salary = (int) $salary; }
|
||||
|
||||
public function getStarted() { return $this->started; }
|
||||
public function setStarted(DateTime $started) { $this->started = $started; }
|
||||
|
||||
public function getLeft() { return $this->left; }
|
||||
public function setLeft(DateTime $left) { $this->left = $left; }
|
||||
|
||||
public function getAddress() { return $this->address; }
|
||||
public function setAddress(Address $address) { $this->address = $address; }
|
||||
}
|
||||
|
||||
/** @ODM\Document */
|
||||
class Employee extends BaseEmployee
|
||||
{
|
||||
/** @ODM\ReferenceOne(targetDocument="Documents\Manager") */
|
||||
private $manager;
|
||||
|
||||
public function getManager() { return $this->manager; }
|
||||
public function setManager(Manager $manager) { $this->manager = $manager; }
|
||||
}
|
||||
|
||||
/** @ODM\Document */
|
||||
class Manager extends BaseEmployee
|
||||
{
|
||||
/** @ODM\ReferenceMany(targetDocument="Documents\Project") */
|
||||
private $projects;
|
||||
|
||||
public __construct() { $this->projects = new ArrayCollection(); }
|
||||
|
||||
public function getProjects() { return $this->projects; }
|
||||
public function addProject(Project $project) { $this->projects[] = $project; }
|
||||
}
|
||||
|
||||
/** @ODM\EmbeddedDocument */
|
||||
class Address
|
||||
{
|
||||
/** @ODM\Field(type="string") */
|
||||
private $address;
|
||||
|
||||
/** @ODM\Field(type="string") */
|
||||
private $city;
|
||||
|
||||
/** @ODM\Field(type="string") */
|
||||
private $state;
|
||||
|
||||
/** @ODM\Field(type="string") */
|
||||
private $zipcode;
|
||||
|
||||
public function getAddress() { return $this->address; }
|
||||
public function setAddress($address) { $this->address = $address; }
|
||||
|
||||
public function getCity() { return $this->city; }
|
||||
public function setCity($city) { $this->city = $city; }
|
||||
|
||||
public function getState() { return $this->state; }
|
||||
public function setState($state) { $this->state = $state; }
|
||||
|
||||
public function getZipcode() { return $this->zipcode; }
|
||||
public function setZipcode($zipcode) { $this->zipcode = $zipcode; }
|
||||
}
|
||||
|
||||
/** @ODM\Document */
|
||||
class Project
|
||||
{
|
||||
/** @ODM\Id */
|
||||
private $id;
|
||||
|
||||
/** @ODM\Field(type="string") */
|
||||
private $name;
|
||||
|
||||
public function __construct($name) { $this->name = $name; }
|
||||
|
||||
public function getId() { return $this->id; }
|
||||
|
||||
public function getName() { return $this->name; }
|
||||
public function setName($name) { $this->name = $name; }
|
||||
}
|
||||
|
||||
Now those objects can be used just like you weren't using any
|
||||
persistence layer at all and can be persisted transparently by
|
||||
Doctrine:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
use Documents\Employee;
|
||||
use Documents\Address;
|
||||
use Documents\Project;
|
||||
use Documents\Manager;
|
||||
use DateTime;
|
||||
|
||||
$employee = new Employee();
|
||||
$employee->setName('Employee');
|
||||
$employee->setSalary(50000);
|
||||
$employee->setStarted(new DateTime());
|
||||
|
||||
$address = new Address();
|
||||
$address->setAddress('555 Doctrine Rd.');
|
||||
$address->setCity('Nashville');
|
||||
$address->setState('TN');
|
||||
$address->setZipcode('37209');
|
||||
$employee->setAddress($address);
|
||||
|
||||
$project = new Project('New Project');
|
||||
$manager = new Manager();
|
||||
$manager->setName('Manager');
|
||||
$manager->setSalary(100000);
|
||||
$manager->setStarted(new DateTime());
|
||||
$manager->addProject($project);
|
||||
|
||||
$dm->persist($employee);
|
||||
$dm->persist($address);
|
||||
$dm->persist($project);
|
||||
$dm->persist($manager);
|
||||
$dm->flush();
|
||||
|
||||
The above would insert the following:
|
||||
|
||||
::
|
||||
|
||||
Array
|
||||
(
|
||||
[000000004b0a33690000000001c304c6] => Array
|
||||
(
|
||||
[name] => New Project
|
||||
)
|
||||
|
||||
)
|
||||
Array
|
||||
(
|
||||
[000000004b0a33660000000001c304c6] => Array
|
||||
(
|
||||
[changes] => 0
|
||||
[notes] => Array
|
||||
(
|
||||
)
|
||||
|
||||
[name] => Manager
|
||||
[salary] => 100000
|
||||
[started] => MongoDate Object
|
||||
(
|
||||
[sec] => 1275265048
|
||||
[usec] => 0
|
||||
)
|
||||
|
||||
[projects] => Array
|
||||
(
|
||||
[0] => Array
|
||||
(
|
||||
[$ref] => projects
|
||||
[$id] => 4c0300188ead0e947a000000
|
||||
[$db] => my_db
|
||||
)
|
||||
|
||||
)
|
||||
|
||||
)
|
||||
|
||||
)
|
||||
Array
|
||||
(
|
||||
[000000004b0a336a0000000001c304c6] => Array
|
||||
(
|
||||
[changes] => 0
|
||||
[notes] => Array
|
||||
(
|
||||
)
|
||||
|
||||
[name] => Employee
|
||||
[salary] => 50000
|
||||
[started] => MongoDate Object
|
||||
(
|
||||
[sec] => 1275265048
|
||||
[usec] => 0
|
||||
)
|
||||
|
||||
[address] => Array
|
||||
(
|
||||
[address] => 555 Doctrine Rd.
|
||||
[city] => Nashville
|
||||
[state] => TN
|
||||
[zipcode] => 37209
|
||||
)
|
||||
|
||||
)
|
||||
|
||||
)
|
||||
|
||||
If we update a property and call ``->flush()`` again we'll get an
|
||||
efficient update query using the atomic operators:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
$newProject = new Project('Another Project');
|
||||
$manager->setSalary(200000);
|
||||
$manager->addNote('Gave user 100k a year raise');
|
||||
$manager->incrementChanges(2);
|
||||
$manager->addProject($newProject);
|
||||
|
||||
$dm->persist($newProject);
|
||||
$dm->flush();
|
||||
|
||||
The above could would produce an update that looks something like
|
||||
this:
|
||||
|
||||
::
|
||||
|
||||
Array
|
||||
(
|
||||
[$inc] => Array
|
||||
(
|
||||
[changes] => 2
|
||||
)
|
||||
|
||||
[$pushAll] => Array
|
||||
(
|
||||
[notes] => Array
|
||||
(
|
||||
[0] => Gave user 100k a year raise
|
||||
)
|
||||
|
||||
[projects] => Array
|
||||
(
|
||||
[0] => Array
|
||||
(
|
||||
[$ref] => projects
|
||||
[$id] => 4c0310718ead0e767e030000
|
||||
[$db] => my_db
|
||||
)
|
||||
|
||||
)
|
||||
|
||||
)
|
||||
|
||||
[$set] => Array
|
||||
(
|
||||
[salary] => 200000
|
||||
)
|
||||
|
||||
)
|
||||
|
||||
This is a simple example, but it demonstrates well that you can
|
||||
transparently persist PHP objects while still utilizing the
|
||||
atomic operators for updating documents! Continue reading to learn
|
||||
how to get the Doctrine MongoDB Object Document Mapper setup and
|
||||
running!
|
||||
|
||||
Setup
|
||||
-----
|
||||
|
||||
Before we can begin, we'll need to install the Doctrine MongoDB ODM library and
|
||||
its dependencies. The easiest way to do this is with `Composer`_:
|
||||
|
||||
::
|
||||
|
||||
$ composer require "doctrine/mongodb-odm"
|
||||
|
||||
Once ODM and its dependencies have been downloaded, we can begin by creating a
|
||||
``bootstrap.php`` file in our project's root directory, where Composer's
|
||||
``vendor/`` directory also resides. Let's start by importing some of the classes
|
||||
we'll use:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
use Doctrine\MongoDB\Connection;
|
||||
use Doctrine\ODM\MongoDB\Configuration;
|
||||
use Doctrine\ODM\MongoDB\DocumentManager;
|
||||
use Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver;
|
||||
|
||||
The first bit of code will be to import Composer's autoloader, so these classes
|
||||
can actually be loaded:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
// ...
|
||||
|
||||
if ( ! file_exists($file = __DIR__.'/vendor/autoload.php')) {
|
||||
throw new RuntimeException('Install dependencies to run this script.');
|
||||
}
|
||||
|
||||
$loader = require_once $file;
|
||||
|
||||
Note that instead of simply requiring the file, we assign its return value to
|
||||
the ``$loader`` variable. Assuming document classes will be stored in the
|
||||
``Documents/`` directory (with a namespace to match), we can register them with
|
||||
the autoloader like so:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
// ...
|
||||
|
||||
$loader->add('Documents', __DIR__);
|
||||
|
||||
Ultimately, our application will utilize ODM through its ``DocumentManager``
|
||||
class. Before we can instantiate a ``DocumentManager``, we need to construct the
|
||||
``Connection`` and ``Configuration`` objects required by its factory method:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
// ...
|
||||
|
||||
$connection = new Connection();
|
||||
$config = new Configuration();
|
||||
|
||||
Next, we'll specify some essential configuration options. The following assumes
|
||||
that we will store generated proxy and hydrator classes in the ``Proxies/`` and
|
||||
``Hydrators/`` directories, respectively. Additionally, we'll define a default
|
||||
database name to use for document classes that do not specify a database in
|
||||
their mapping.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
// ...
|
||||
|
||||
$config->setProxyDir(__DIR__ . '/Proxies');
|
||||
$config->setProxyNamespace('Proxies');
|
||||
$config->setHydratorDir(__DIR__ . '/Hydrators');
|
||||
$config->setHydratorNamespace('Hydrators');
|
||||
$config->setDefaultDB('doctrine_odm');
|
||||
|
||||
The easiest way to define mappings for our document classes is with annotations.
|
||||
We'll need to specify an annotation driver in our configuration (with one or
|
||||
more paths) and register the annotations for the driver:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
// ...
|
||||
|
||||
$config->setMetadataDriverImpl(AnnotationDriver::create(__DIR__ . '/Documents'));
|
||||
|
||||
AnnotationDriver::registerAnnotationClasses();
|
||||
|
||||
At this point, we have everything necessary to construct a ``DocumentManager``:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
// ...
|
||||
|
||||
$dm = DocumentManager::create($connection, $config);
|
||||
|
||||
The final ``bootstrap.php`` file should look like this:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
use Doctrine\MongoDB\Connection;
|
||||
use Doctrine\ODM\MongoDB\Configuration;
|
||||
use Doctrine\ODM\MongoDB\DocumentManager;
|
||||
use Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver;
|
||||
|
||||
if ( ! file_exists($file = __DIR__.'/vendor/autoload.php')) {
|
||||
throw new RuntimeException('Install dependencies to run this script.');
|
||||
}
|
||||
|
||||
$loader = require_once $file;
|
||||
$loader->add('Documents', __DIR__);
|
||||
|
||||
$connection = new Connection();
|
||||
|
||||
$config = new Configuration();
|
||||
$config->setProxyDir(__DIR__ . '/Proxies');
|
||||
$config->setProxyNamespace('Proxies');
|
||||
$config->setHydratorDir(__DIR__ . '/Hydrators');
|
||||
$config->setHydratorNamespace('Hydrators');
|
||||
$config->setDefaultDB('doctrine_odm');
|
||||
$config->setMetadataDriverImpl(AnnotationDriver::create(__DIR__ . '/Documents'));
|
||||
|
||||
AnnotationDriver::registerAnnotationClasses();
|
||||
|
||||
$dm = DocumentManager::create($connection, $config);
|
||||
|
||||
That is it! Your ``DocumentManager`` instance is ready to be used!
|
||||
|
||||
Using PHP 7
|
||||
-----------
|
||||
|
||||
You can use Doctrine MongoDB ODM with PHP 7, but there are a few extra steps during
|
||||
the installation. Since the legacy driver (referred to as ``ext-mongo``) is not
|
||||
available on PHP 7, you will need the new driver (``ext-mongodb``) installed and
|
||||
use a polyfill to provide the API of the legacy driver.
|
||||
|
||||
To do this, you have to require ``alcaeus/mongo-php-adapter`` before adding a composer
|
||||
dependency to ODM. To do this, run the following command:
|
||||
|
||||
::
|
||||
|
||||
$ composer require "alcaeus/mongo-php-adapter"
|
||||
|
||||
Next, manually add a ``provide`` section to your ``composer.json``:
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
"provide": {
|
||||
"ext-mongo": "1.6.14"
|
||||
}
|
||||
|
||||
This section needs to be added to work around a composer issue with libraries
|
||||
providing platform packages (such as ``ext-mongo``). Now, you may install ODM as
|
||||
described above:
|
||||
|
||||
::
|
||||
|
||||
$ composer require "doctrine/mongodb-odm"
|
||||
|
||||
.. _MongoDB: https://www.mongodb.com/
|
||||
.. _10gen: http://www.10gen.com
|
||||
.. _Composer: http://getcomposer.org/
|
||||
@@ -0,0 +1,31 @@
|
||||
Logging
|
||||
=======
|
||||
|
||||
If you want to turn on logging and receive information about
|
||||
queries made to the database you can do so on your
|
||||
``Doctrine\ODM\MongoDB\Configuration`` instance:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
// ...
|
||||
|
||||
$config->setLoggerCallable(function(array $log) {
|
||||
print_r($log);
|
||||
});
|
||||
|
||||
You can register any PHP callable and it will be notified with a
|
||||
single argument that is an array of information about the query
|
||||
being sent to the database.
|
||||
|
||||
Just like the anonymous function above, you could pass an array
|
||||
with a object instance and a method to call:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
// ...
|
||||
|
||||
$config->setLoggerCallable(array($obj, 'method'));
|
||||
@@ -0,0 +1,117 @@
|
||||
Map Reduce
|
||||
==========
|
||||
|
||||
The Doctrine MongoDB ODM fully supports the `map reduce`_ functionality via its
|
||||
:doc:`Query Builder API <query-builder-api>`.
|
||||
|
||||
.. note::
|
||||
|
||||
From the MongoDB manual:
|
||||
|
||||
Map-reduce is a data processing paradigm for condensing large volumes of
|
||||
data into useful aggregated results. In MongoDB, map-reduce operations use
|
||||
custom JavaScript functions to map, or associate, values to a key. If a key
|
||||
has multiple values mapped to it, the operation reduces the values for the
|
||||
key to a single object.
|
||||
|
||||
Imagine a situation where you had an application with a document
|
||||
named ``Event`` and it was related to a ``User`` document:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
namespace Documents;
|
||||
|
||||
/** @Document */
|
||||
class Event
|
||||
{
|
||||
/** @Id */
|
||||
private $id;
|
||||
|
||||
/** @ReferenceOne(targetDocument="Documents\User") */
|
||||
private $user;
|
||||
|
||||
/** @Field(type="string") */
|
||||
private $type;
|
||||
|
||||
/** @Field(type="date") */
|
||||
private $date;
|
||||
|
||||
/** @Field(type="string") */
|
||||
private $description;
|
||||
|
||||
// getters and setters
|
||||
}
|
||||
|
||||
/** @Document */
|
||||
class User
|
||||
{
|
||||
// ...
|
||||
}
|
||||
|
||||
We may have a situation where we want to run a query that tells us how many
|
||||
sales events each user has had. We can easily use the map reduce functionality
|
||||
of MongoDB via the ODM's query builder. Here is a simple map reduce example:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$qb = $dm->createQueryBuilder('Documents\User')
|
||||
->field('type')
|
||||
->equals('sale')
|
||||
->map('function() { emit(this.user.$id, 1); }')
|
||||
->reduce('function(k, vals) {
|
||||
var sum = 0;
|
||||
for (var i in vals) {
|
||||
sum += vals[i];
|
||||
}
|
||||
return sum;
|
||||
}');
|
||||
$query = $qb->getQuery();
|
||||
$results = $query->execute();
|
||||
|
||||
foreach ($results as $user) {
|
||||
printf("User %s had %d sale(s).\n", $user['_id'], $user['value']);
|
||||
}
|
||||
|
||||
.. note::
|
||||
|
||||
The query builder also has a ``finalize()`` method, which may be used to
|
||||
specify a `finalize function`_ to be executed after the reduce step.
|
||||
|
||||
When using map reduce with Doctrine, the results are not hydrated into objects.
|
||||
Instead, the raw results are returned directly from MongoDB.
|
||||
|
||||
The preceding example is equivalent to executing the following command via the
|
||||
PHP driver directly:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$db = $mongoClient->selectDB('my_db');
|
||||
|
||||
$map = new MongoCode('function() { emit(this.user.$id, 1); }');
|
||||
$reduce = new MongoCode('function(k, vals) {
|
||||
var sum = 0;
|
||||
for (var i in vals) {
|
||||
sum += vals[i];
|
||||
}
|
||||
return sum;
|
||||
}');
|
||||
|
||||
$result = $db->command(array(
|
||||
'mapreduce' => 'events',
|
||||
'map' => $map,
|
||||
'reduce' => $reduce,
|
||||
'query' => array('type' => 'sale'),
|
||||
));
|
||||
|
||||
foreach ($result['results'] as $user) {
|
||||
printf("User %s had %d sale(s).\n", $user['_id'], $user['value']);
|
||||
}
|
||||
|
||||
.. _`map reduce`: https://docs.mongodb.com/manual/core/map-reduce/
|
||||
.. _`finalize function`: https://docs.mongodb.com/master/reference/command/mapReduce/#mapreduce-finalize-cmd
|
||||
@@ -0,0 +1,196 @@
|
||||
Metadata Drivers
|
||||
================
|
||||
|
||||
The heart of an object mapper is the mapping information
|
||||
that glues everything together. It instructs the DocumentManager how
|
||||
it should behave when dealing with the different documents.
|
||||
|
||||
Core Metadata Drivers
|
||||
---------------------
|
||||
|
||||
Doctrine provides a few different ways for you to specify your
|
||||
metadata:
|
||||
|
||||
- **XML files** (XmlDriver)
|
||||
- **Class DocBlock Annotations** (AnnotationDriver)
|
||||
- **YAML files** (YamlDriver)
|
||||
- **PHP Code in files or static functions** (PhpDriver)
|
||||
|
||||
Something important to note about the above drivers is they are all
|
||||
an intermediate step to the same end result. The mapping
|
||||
information is populated to ``Doctrine\ODM\MongoDB\Mapping\ClassMetadata``
|
||||
instances. So in the end, Doctrine only ever has to work with the
|
||||
API of the ``ClassMetadata`` class to get mapping information for
|
||||
a document.
|
||||
|
||||
.. note::
|
||||
|
||||
The populated ``ClassMetadata`` instances are also cached
|
||||
so in a production environment the parsing and populating only ever
|
||||
happens once. You can configure the metadata cache implementation
|
||||
using the ``setMetadataCacheImpl()`` method on the
|
||||
``Doctrine\ODM\MongoDB\Configuration`` class:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$em->getConfiguration()->setMetadataCacheImpl(new ApcCache());
|
||||
|
||||
If you want to use one of the included core metadata drivers you
|
||||
just need to configure it. All the drivers are in the
|
||||
``Doctrine\ODM\MongoDB\Mapping\Driver`` namespace:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$driver = new \Doctrine\ODM\MongoDB\Mapping\Driver\XmlDriver('/path/to/mapping/files');
|
||||
$em->getConfiguration()->setMetadataDriverImpl($driver);
|
||||
|
||||
Implementing Metadata Drivers
|
||||
-----------------------------
|
||||
|
||||
In addition to the included metadata drivers you can very easily
|
||||
implement your own. All you need to do is define a class which
|
||||
implements the ``Driver`` interface:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
namespace Doctrine\ODM\MongoDB\Mapping\Driver;
|
||||
|
||||
use Doctrine\ODM\MongoDB\Mapping\ClassMetadataInfo;
|
||||
|
||||
interface Driver
|
||||
{
|
||||
/**
|
||||
* Loads the metadata for the specified class into the provided container.
|
||||
*
|
||||
* @param string $className
|
||||
* @param ClassMetadataInfo $metadata
|
||||
*/
|
||||
function loadMetadataForClass($className, ClassMetadataInfo $metadata);
|
||||
|
||||
/**
|
||||
* Gets the names of all mapped classes known to this driver.
|
||||
*
|
||||
* @return array The names of all mapped classes known to this driver.
|
||||
*/
|
||||
function getAllClassNames();
|
||||
|
||||
/**
|
||||
* Whether the class with the specified name should have its metadata loaded.
|
||||
* This is only the case if it is either mapped as a Document or a
|
||||
* MappedSuperclass.
|
||||
*
|
||||
* @param string $className
|
||||
* @return boolean
|
||||
*/
|
||||
function isTransient($className);
|
||||
}
|
||||
|
||||
If you want to write a metadata driver to parse information from
|
||||
some file format we've made your life a little easier by providing
|
||||
the ``AbstractFileDriver`` implementation for you to extend from:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
class MyMetadataDriver extends AbstractFileDriver
|
||||
{
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected $_fileExtension = '.dcm.ext';
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function loadMetadataForClass($className, ClassMetadataInfo $metadata)
|
||||
{
|
||||
$data = $this->_loadMappingFile($file);
|
||||
|
||||
// populate ClassMetadataInfo instance from $data
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function _loadMappingFile($file)
|
||||
{
|
||||
// parse contents of $file and return php data structure
|
||||
}
|
||||
}
|
||||
|
||||
.. note::
|
||||
|
||||
When using the ``AbstractFileDriver`` it requires that you
|
||||
only have one document defined per file and the file named after the
|
||||
class described inside where namespace separators are replaced by
|
||||
periods. So if you have a document named ``Documents\User`` and you
|
||||
wanted to write a mapping file for your driver above you would need
|
||||
to name the file ``Documents.User.dcm.ext`` for it to be
|
||||
recognized.
|
||||
|
||||
Now you can use your ``MyMetadataDriver`` implementation by setting
|
||||
it with the ``setMetadataDriverImpl()`` method:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$driver = new MyMetadataDriver('/path/to/mapping/files');
|
||||
$em->getConfiguration()->setMetadataDriverImpl($driver);
|
||||
|
||||
ClassMetadata
|
||||
-------------
|
||||
|
||||
The last piece you need to know and understand about metadata in
|
||||
Doctrine is the API of the ``ClassMetadata`` classes. You need to
|
||||
be familiar with them in order to implement your own drivers but
|
||||
more importantly to retrieve mapping information for a certain
|
||||
document when needed.
|
||||
|
||||
You have all the methods you need to manually specify the mapping
|
||||
information instead of using some mapping file to populate it from.
|
||||
The base ``ClassMetadataInfo`` class is responsible for only data
|
||||
storage and is not meant for runtime use. It does not require that
|
||||
the class actually exists yet so it is useful for describing some
|
||||
document before it exists and using that information to generate for
|
||||
example the documents themselves. The class ``ClassMetadata``
|
||||
extends ``ClassMetadataInfo`` and adds some functionality required
|
||||
for runtime usage and requires that the PHP class is present and
|
||||
can be autoloaded.
|
||||
|
||||
You can read more about the API of the ``ClassMetadata`` classes in
|
||||
the PHP Mapping chapter.
|
||||
|
||||
Getting ClassMetadata Instances
|
||||
-------------------------------
|
||||
|
||||
If you want to get the ``ClassMetadata`` instance for a document in
|
||||
your project to programmatically use some mapping information to
|
||||
generate some HTML or something similar you can retrieve it through
|
||||
the ``ClassMetadataFactory``:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$cmf = $em->getMetadataFactory();
|
||||
$class = $cmf->getMetadataFor('MyDocumentName');
|
||||
|
||||
Now you can learn about the document and use the data stored in the
|
||||
``ClassMetadata`` instance to get all mapped fields for example and
|
||||
iterate over them:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
foreach ($class->fieldMappings as $fieldMapping) {
|
||||
echo $fieldMapping['fieldName'] . "\n";
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
Migrating Schemas
|
||||
=================
|
||||
|
||||
Even though MongoDB is schemaless, introducing some kind of object mapper means
|
||||
that your object definitions become your schema. You may have a situation where
|
||||
you rename a property in your object model but need to load values from older
|
||||
documents where the field is still using the former name. While you could use
|
||||
MongoDB's `$rename`_ operator to migrate everything, sometimes a lazy migration
|
||||
is preferable. Doctrine offers a few different methods for dealing with this
|
||||
problem!
|
||||
|
||||
.. note::
|
||||
|
||||
The features in this chapter were inspired by `Objectify`_, an object mapper
|
||||
for the Google App Engine datastore. Additional information may be found in
|
||||
the `Objectify schema migration`_ documentation.
|
||||
|
||||
Renaming a Field
|
||||
----------------
|
||||
|
||||
Let's say you have a simple document that starts off with the following fields:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/** @Document */
|
||||
class Person
|
||||
{
|
||||
/** @Id */
|
||||
public $id;
|
||||
|
||||
/** @Field(type="string") */
|
||||
public $name;
|
||||
}
|
||||
|
||||
Later on, you need rename ``name`` to ``fullName``; however, you'd like to
|
||||
hydrate ``fullName`` from ``name`` if the new field doesn't exist.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/** @Document */
|
||||
class Person
|
||||
{
|
||||
/** @Id */
|
||||
public $id;
|
||||
|
||||
/** @Field(type="string") @AlsoLoad("name") */
|
||||
public $fullName;
|
||||
}
|
||||
|
||||
When a Person is loaded, the ``fullName`` field will be populated with the value
|
||||
of ``name`` if ``fullName`` is not found. When the Person is persisted, this
|
||||
value will then be stored in the ``fullName`` field.
|
||||
|
||||
.. caution::
|
||||
|
||||
A caveat of this feature is that it only affects hydration. Queries will not
|
||||
know about the rename, so a query on ``fullName`` will only match documents
|
||||
with the new field name. You can still query using the ``name`` field to
|
||||
find older documents. The `$or`_ query operator could be used to match both.
|
||||
|
||||
Transforming Data
|
||||
-----------------
|
||||
|
||||
You may have a situation where you want to migrate a Person's name to separate
|
||||
``firstName`` and ``lastName`` fields. This is also possible by specifying the
|
||||
``@AlsoLoad`` annotation on a method, which will then be invoked immediately
|
||||
before normal hydration.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/** @Document @HasLifecycleCallbacks */
|
||||
class Person
|
||||
{
|
||||
/** @Id */
|
||||
public $id;
|
||||
|
||||
/** @Field(type="string") */
|
||||
public $firstName;
|
||||
|
||||
/** @Field(type="string") */
|
||||
public $lastName;
|
||||
|
||||
/** @AlsoLoad({"name", "fullName"}) */
|
||||
public function populateFirstAndLastName($fullName)
|
||||
{
|
||||
list($this->firstName, $this->lastName) = explode(' ', $fullName);
|
||||
}
|
||||
}
|
||||
|
||||
The annotation is defined with one or a list of field names. During hydration,
|
||||
these fields will be checked in order and, for each field present, the annotated
|
||||
method will be invoked with its value as a single argument. Since the
|
||||
``firstName`` and ``lastName`` fields are mapped, they would then be updated
|
||||
when the Person was persisted back to MongoDB.
|
||||
|
||||
Unlike lifecycle callbacks, the ``@AlsoLoad`` method annotation does not require
|
||||
the :ref:`haslifecyclecallbacks` class annotation to be present.
|
||||
|
||||
Moving Fields
|
||||
-------------
|
||||
|
||||
Migrating your schema can be a difficult task, but Doctrine provides a few
|
||||
different methods for dealing with it:
|
||||
|
||||
- **@AlsoLoad** - load values from old fields or transform data through methods
|
||||
- **@NotSaved** - load values into fields without saving them again
|
||||
- **@PostLoad** - execute code after all fields have been loaded
|
||||
- **@PrePersist** - execute code before your document gets saved
|
||||
|
||||
Imagine you have some address-related fields on a Person document:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/** @Document */
|
||||
class Person
|
||||
{
|
||||
/** @Id */
|
||||
public $id;
|
||||
|
||||
/** @Field(type="string") */
|
||||
public $name;
|
||||
|
||||
/** @Field(type="string") */
|
||||
public $street;
|
||||
|
||||
/** @Field(type="string") */
|
||||
public $city;
|
||||
}
|
||||
|
||||
Later on, you may want to migrate this data into an embedded Address document:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/** @EmbeddedDocument */
|
||||
class Address
|
||||
{
|
||||
/** @Field(type="string") */
|
||||
public $street;
|
||||
|
||||
/** @Field(type="string") */
|
||||
public $city;
|
||||
|
||||
public function __construct($street, $city)
|
||||
{
|
||||
$this->street = $street;
|
||||
$this->city = $city;
|
||||
}
|
||||
}
|
||||
|
||||
/** @Document @HasLifecycleCallbacks */
|
||||
class Person
|
||||
{
|
||||
/** @Id */
|
||||
public $id;
|
||||
|
||||
/** @Field(type="string") */
|
||||
public $name;
|
||||
|
||||
/** @NotSaved */
|
||||
public $street;
|
||||
|
||||
/** @NotSaved */
|
||||
public $city;
|
||||
|
||||
/** @EmbedOne(targetDocument="Address") */
|
||||
public $address;
|
||||
|
||||
/** @PostLoad */
|
||||
public function postLoad()
|
||||
{
|
||||
if ($this->street !== null || $this->city !== null)
|
||||
{
|
||||
$this->address = new Address($this->street, $this->city);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Person's ``street`` and ``city`` fields will be hydrated, but not saved. Once
|
||||
the Person has loaded, the ``postLoad()`` method will be invoked and construct
|
||||
a new Address object, which is mapped and will be persisted.
|
||||
|
||||
Alternatively, you could defer this migration until the Person is saved:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/** @Document @HasLifecycleCallbacks */
|
||||
class Person
|
||||
{
|
||||
// ...
|
||||
|
||||
/** @PrePersist */
|
||||
public function prePersist()
|
||||
{
|
||||
if ($this->street !== null || $this->city !== null)
|
||||
{
|
||||
$this->address = new Address($this->street, $this->city);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
The :ref:`haslifecyclecallbacks` annotation must be present on the class in
|
||||
which the method is declared for the lifecycle callback to be registered.
|
||||
|
||||
.. _`$rename`: https://docs.mongodb.com/manual/reference/operator/update/rename/
|
||||
.. _`Objectify`: https://github.com/objectify/objectify
|
||||
.. _`Objectify schema migration`: https://github.com/objectify/objectify/wiki/SchemaMigration
|
||||
.. _`$or`: https://docs.mongodb.com/manual/reference/operator/query/or/
|
||||
@@ -0,0 +1,168 @@
|
||||
Priming References
|
||||
==================
|
||||
|
||||
Priming references allows you to consolidate database queries when working with
|
||||
:ref:`one <reference_one>` and :ref:`many <reference_many>` reference mappings.
|
||||
This is useful for avoiding the
|
||||
`n+1 problem <http://stackoverflow.com/q/97197/162228>`_ in your application.
|
||||
|
||||
Query Builder
|
||||
-------------
|
||||
|
||||
Consider the following abbreviated model:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/** @Document */
|
||||
class User
|
||||
{
|
||||
/** @ReferenceMany(targetDocument="Account") */
|
||||
private $accounts;
|
||||
}
|
||||
|
||||
We would like to query for 100 users and then iterate over their referenced
|
||||
accounts.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$qb = $dm->createQueryBuilder('User')
|
||||
->limit(100);
|
||||
$query = $qb->getQuery();
|
||||
$users = $query->execute();
|
||||
|
||||
foreach ($users as $user) {
|
||||
/* PersistentCollection::initialize() will be invoked when we begin
|
||||
* iterating through the user's accounts. Any accounts not already
|
||||
* managed by the unit of work will need to be queried.
|
||||
*/
|
||||
foreach ($user->getAccounts() as $account) {
|
||||
// ...
|
||||
}
|
||||
}
|
||||
|
||||
In this example, ODM would query the database once for the result set of users
|
||||
and then, for each user, issue a separate query to load any accounts that are
|
||||
not already being managed by the unit of work. This could result in as many as
|
||||
100 additional database queries!
|
||||
|
||||
If we expect to iterate through all users and their accounts, we could optimize
|
||||
this process by loading all of the referenced accounts with one query. The query
|
||||
builder's ``prime()`` method allows us to do just that.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$qb = $dm->createQueryBuilder('User')
|
||||
->field('accounts')->prime(true)
|
||||
->limit(100);
|
||||
$query = $qb->getQuery();
|
||||
|
||||
/* After querying for the users, ODM will collect the IDs of all referenced
|
||||
* accounts and load them with a single additional query.
|
||||
*/
|
||||
$users = $query->execute();
|
||||
|
||||
foreach ($users as $user) {
|
||||
/* Accounts have already been loaded, so iterating through accounts will
|
||||
* not query an additional query.
|
||||
*/
|
||||
foreach ($user->getAccounts() as $account) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
In this case, priming will allow us to load all users and referenced accounts in
|
||||
two database queries. If the accounts had used an
|
||||
:ref:`inheritance mapping <inheritance_mapping>`, priming might require several
|
||||
queries (one per discriminated class name).
|
||||
|
||||
.. note::
|
||||
|
||||
Priming is also compatible with :ref:`simple references <storing_references>`
|
||||
and discriminated references. When priming discriminated references, ODM
|
||||
will issue one query per distinct class among the referenced document(s).
|
||||
|
||||
.. note::
|
||||
|
||||
Hydration must be enabled in the query builder for priming to work properly.
|
||||
Disabling hydration will cause the DBRef to be returned for a referenced
|
||||
document instead of the hydrated document object.
|
||||
|
||||
Inverse references
|
||||
------------------
|
||||
|
||||
.. note::
|
||||
|
||||
This feature was added in version 1.2.
|
||||
|
||||
When using inverse references (references mapped using ``mappedBy`` or
|
||||
``repositoryMethod``) you can also enable primers on one-to-many references by
|
||||
specifying them in the mapping:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/** @Document */
|
||||
class User
|
||||
{
|
||||
/** @ReferenceMany(targetDocument="Account", prime={"user"}) */
|
||||
private $accounts;
|
||||
}
|
||||
|
||||
When the collection is initialized, the configured primers are automatically
|
||||
added to the query.
|
||||
|
||||
.. note::
|
||||
|
||||
When using inverse references with ``repositoryMethod``, be sure to return
|
||||
an eager cursor from the repository method if you want to rely on primers
|
||||
defined in the mapping. If the result is not an eager cursor, an exception
|
||||
will be thrown and the collection won't be loaded. Also, any primers you
|
||||
might have added in the ``repositoryMethod`` are overwritten with those
|
||||
specified in the mapping.
|
||||
|
||||
Primer Callback
|
||||
---------------
|
||||
|
||||
Passing ``true`` to ``prime()`` instructs ODM to load the referenced document(s)
|
||||
on its own; however, we can also pass a custom callable (e.g. Closure instance)
|
||||
to ``prime()``, which allows more control over the priming query.
|
||||
|
||||
As an example, we can look at the default callable, which is found in the
|
||||
``ReferencePrimer`` class.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
function(DocumentManager $dm, ClassMetadata $class, array $ids, array $hints) {
|
||||
$qb = $dm->createQueryBuilder($class->name)
|
||||
->field($class->identifier)->in($ids);
|
||||
|
||||
if ( ! empty($hints[Query::HINT_SLAVE_OKAY])) {
|
||||
$qb->slaveOkay(true);
|
||||
}
|
||||
|
||||
if ( ! empty($hints[Query::HINT_READ_PREFERENCE])) {
|
||||
$qb->setReadPreference(
|
||||
$hints[Query::HINT_READ_PREFERENCE],
|
||||
$hints[Query::HINT_READ_PREFERENCE_TAGS]
|
||||
);
|
||||
}
|
||||
|
||||
$qb->getQuery()->toArray();
|
||||
};
|
||||
|
||||
Firstly, the callable is passed the ``DocumentManager`` of the main query. This
|
||||
is necessary to create the query used for priming, and ensures that the results
|
||||
will become managed in the same scope. The ``ClassMetadata`` argument provides
|
||||
mapping information for the referenced class as well as its name, which is used
|
||||
to create the query builder. An array of identifiers follows, which is used to
|
||||
query for the documents to be primed. Lastly, the ``UnitOfWork`` hints from the
|
||||
original query are provided so that the priming query can apply them as well.
|
||||
@@ -0,0 +1,998 @@
|
||||
Query Builder API
|
||||
=================
|
||||
|
||||
.. role:: math(raw)
|
||||
:format: html latex
|
||||
|
||||
Querying for documents with Doctrine is just as simple as if you
|
||||
weren't using Doctrine at all. Of course you always have your
|
||||
traditional ``find()`` and ``findOne()`` methods but you also have
|
||||
a ``Query`` object with a fluent API for defining the query that
|
||||
should be executed.
|
||||
|
||||
The ``Query`` object supports several types of queries
|
||||
|
||||
- FIND
|
||||
- FIND_AND_UPDATE
|
||||
- FIND_AND_REMOVE
|
||||
- INSERT
|
||||
- UPDATE
|
||||
- REMOVE
|
||||
- GROUP
|
||||
- MAP_REDUCE
|
||||
- DISTINCT_FIELD
|
||||
- GEO_LOCATION
|
||||
|
||||
This section will show examples for the different types of queries.
|
||||
|
||||
Finding Documents
|
||||
-----------------
|
||||
|
||||
You have a few different ways to find documents. You can use the ``find()`` method
|
||||
to find a document by its identifier:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$users = $dm->find('User', $id);
|
||||
|
||||
The ``find()`` method is just a convenience shortcut method to:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$user = $dm->getRepository('User')->find($id);
|
||||
|
||||
.. note::
|
||||
|
||||
The ``find()`` method checks the local in memory identity map for the document
|
||||
before querying the database for the document.
|
||||
|
||||
On the ``DocumentRepository`` you have a few other methods for finding documents:
|
||||
|
||||
- ``findBy`` - find documents by an array of criteria
|
||||
- ``findOneBy`` - find one document by an array of criteria
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$users = $dm->getRepository('User')->findBy(array('type' => 'employee'));
|
||||
$user = $dm->getRepository('User')->findOneBy(array('username' => 'jwage'));
|
||||
|
||||
Creating a Query Builder
|
||||
------------------------
|
||||
|
||||
You can easily create a new ``Query\Builder`` object with the
|
||||
``DocumentManager::createQueryBuilder()`` method:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$qb = $dm->createQueryBuilder('User');
|
||||
|
||||
The first and only argument is optional, you can specify it later
|
||||
with the ``find()``, ``update()`` (deprecated), ``updateOne()``,
|
||||
``updateMany()`` or ``remove()`` method:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$qb = $dm->createQueryBuilder();
|
||||
|
||||
// ...
|
||||
|
||||
$qb->find('User');
|
||||
|
||||
Executing Queries
|
||||
~~~~~~~~~~~~~~~~~
|
||||
|
||||
You can execute a query by getting a ``Query`` through the ``getQuery()`` method:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$qb = $dm->createQueryBuilder('User');
|
||||
$query = $qb->getQuery();
|
||||
|
||||
Now you can ``execute()`` that query and it will return a cursor for you to iterate over the results:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$users = $query->execute();
|
||||
|
||||
Debugging Queries
|
||||
~~~~~~~~~~~~~~~~~
|
||||
|
||||
While building not complicated queries is really simple sometimes it might be hard to wrap your head
|
||||
around more sophisticated queries that involves building separate expressions to work properly. If
|
||||
you are not sure if your the query constructed with Builder is in fact correct you may want to ``debug()`` it
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$qb = $dm->createQueryBuilder('User');
|
||||
$query = $qb->getQuery();
|
||||
$debug = $query->debug();
|
||||
|
||||
At this point your query is *prepared* - that means ODM done all its job in renaming fields to match their
|
||||
database name, added discriminator fields, applied filters, created correct references and all other things
|
||||
you employ ODM to. The array returned by ``->debug()`` is what is passed to the underlying driver for the
|
||||
query to be performed.
|
||||
|
||||
Eager Cursors
|
||||
~~~~~~~~~~~~~
|
||||
|
||||
You can configure queries to return an eager cursor instead of a normal mongodb cursor using the ``Builder#eagerCursor()`` method:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$qb = $dm->createQueryBuilder('User')
|
||||
->eagerCursor(true);
|
||||
$query = $qb->getQuery();
|
||||
$cursor = $query->execute(); // instanceof Doctrine\ODM\MongoDB\EagerCursor
|
||||
|
||||
Iterating over the ``$cursor`` will fetch all the data in a short and small cursor all at once and will hydrate
|
||||
one document at a time in to an object as you iterate:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
foreach ($cursor as $user) { // queries for all users and data is held internally
|
||||
// each User object is hydrated from the data one at a time.
|
||||
}
|
||||
|
||||
Getting Single Result
|
||||
~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
If you want to just get a single result you can use the ``Query#getSingleResult()`` method:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$user = $dm->createQueryBuilder('User')
|
||||
->field('username')->equals('jwage')
|
||||
->getQuery()
|
||||
->getSingleResult();
|
||||
|
||||
Selecting Fields
|
||||
~~~~~~~~~~~~~~~~
|
||||
|
||||
You can limit the fields that are returned in the results by using
|
||||
the ``select()`` method:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$qb = $dm->createQueryBuilder('User')
|
||||
->select('username', 'password');
|
||||
$query = $qb->getQuery();
|
||||
$users = $query->execute();
|
||||
|
||||
In the results only the data from the username and password will be
|
||||
returned.
|
||||
|
||||
Index hints
|
||||
~~~~~~~~~~~
|
||||
|
||||
You can force MongoDB to use a specific index for a query with the ``hint()`` method (see `hint <https://docs.mongodb.com/manual/reference/operator/meta/hint/>`_)
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$qb = $dm->createQueryBuilder('User')
|
||||
->hint('user_pass_idx');
|
||||
$query = $qb->getQuery();
|
||||
$users = $query->execute();
|
||||
|
||||
.. note::
|
||||
|
||||
Combining ``select()`` and ``hint()`` on appropriate indexes can result in very fast
|
||||
`covered queries <https://docs.mongodb.com/manual/core/query-optimization/#covered-query>`_
|
||||
|
||||
Selecting Distinct Values
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Sometimes you may want to get an array of distinct values in a
|
||||
collection. You can accomplish this using the ``distinct()``
|
||||
method:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$ages = $dm->createQueryBuilder('User')
|
||||
->distinct('age')
|
||||
->getQuery()
|
||||
->execute();
|
||||
|
||||
The above would give you an ``ArrayCollection`` of all the distinct user ages!
|
||||
|
||||
.. note::
|
||||
|
||||
MongoDB's `distinct command <https://docs.mongodb.com/manual/reference/command/distinct/>`_
|
||||
does not support sorting, so you cannot combine ``distinct()`` with
|
||||
``sort()``. If you would like to sort the results of a distinct query, you
|
||||
will need to do so in PHP after executing the query.
|
||||
|
||||
Refreshing Documents
|
||||
~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
When a query (e.g. geoNear, find) returns one or more hydrated documents whose
|
||||
identifiers are already in the identity map, ODM returns the managed document
|
||||
instances for those results. In this case, a managed document's data may differ
|
||||
from whatever was just returned by the database query.
|
||||
|
||||
The query builder's ``refresh()`` method may be used to instruct ODM to override
|
||||
the managed document with data from the query result. This is comparable to
|
||||
calling ``DocumentManager::refresh()`` for a managed document. The document's
|
||||
changeset will be reset in the process.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$user = $dm->createQueryBuilder('User')
|
||||
->field('username')->equals('jwage')
|
||||
->refresh()
|
||||
->getQuery()
|
||||
->getSingleResult();
|
||||
|
||||
// Jon's user will have the latest data, even if it was already managed
|
||||
|
||||
Refreshing is not applicable if hydration is disabled.
|
||||
|
||||
Fetching Documents as Read-Only
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Similar to ``refresh()``, ``readOnly()`` instructs ODM to not only hydrate the
|
||||
latest data but also to create new document's instance (i.e. if found document
|
||||
would be already managed by Doctrine, new instance will be returned) and not
|
||||
register it in ``UnitOfWork``.
|
||||
|
||||
This technique can prove especially useful when using ``select()`` with no intent
|
||||
to update fetched documents.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$user = $dm->createQueryBuilder('User')
|
||||
->field('username')->equals('malarzm')
|
||||
->readOnly()
|
||||
->getQuery()
|
||||
->getSingleResult();
|
||||
|
||||
// Maciej's user will have the latest data, and will not be the same object
|
||||
// as the one that was already managed (if it was)
|
||||
|
||||
Read-Only is not applicable if hydration is disabled.
|
||||
|
||||
.. note::
|
||||
|
||||
Read-only mode is not deep, i.e. any references (be it owning or inverse) of
|
||||
fetched WILL be managed by Doctrine. This is a shortcoming of current
|
||||
implementation, may change in future and will not be considered a BC break
|
||||
(will be treated as a feature instead).
|
||||
|
||||
.. note::
|
||||
|
||||
To manage a document previously fetched in read-only mode, always use the
|
||||
`merge` method of the DocumentManager. Using `persist` in these cases can
|
||||
have unwanted side effects.
|
||||
|
||||
Disabling Hydration
|
||||
~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
For find queries the results by default are hydrated and you get
|
||||
document objects back instead of arrays. You can disable this and
|
||||
get the raw results directly back from mongo by using the
|
||||
``hydrate(false)`` method:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$users = $dm->createQueryBuilder('User')
|
||||
->hydrate(false)
|
||||
->getQuery()
|
||||
->execute();
|
||||
|
||||
print_r($users);
|
||||
|
||||
Limiting Results
|
||||
~~~~~~~~~~~~~~~~
|
||||
|
||||
You can limit results similar to how you would in a relational
|
||||
database with a limit and offset by using the ``limit()`` and
|
||||
``skip()`` method.
|
||||
|
||||
Here is an example where we get the third page of blog posts when
|
||||
we show twenty at a time:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$blogPosts = $dm->createQueryBuilder('BlogPost')
|
||||
->limit(20)
|
||||
->skip(40)
|
||||
->getQuery()
|
||||
->execute();
|
||||
|
||||
Sorting Results
|
||||
~~~~~~~~~~~~~~~
|
||||
|
||||
You can sort the results by using the ``sort()`` method:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$qb = $dm->createQueryBuilder('Article')
|
||||
->sort('createdAt', 'desc');
|
||||
|
||||
If you want to an additional sort you can call ``sort()`` again. The calls are stacked and ordered
|
||||
in the order you call the method:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$query->sort('featured', 'desc');
|
||||
|
||||
Map Reduce
|
||||
~~~~~~~~~~
|
||||
|
||||
You can also run map reduced find queries using the ``Query``
|
||||
object:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$qb = $this->dm->createQueryBuilder('Event')
|
||||
->field('type')->equals('sale')
|
||||
->map('function() { emit(this.userId, 1); }')
|
||||
->reduce("function(k, vals) {
|
||||
var sum = 0;
|
||||
for (var i in vals) {
|
||||
sum += vals[i];
|
||||
}
|
||||
return sum;
|
||||
}");
|
||||
$query = $qb->getQuery();
|
||||
$results = $query->execute();
|
||||
|
||||
.. note::
|
||||
|
||||
When you specify a ``map()`` and ``reduce()`` operation
|
||||
the results will not be hydrated and the raw results from the map
|
||||
reduce operation will be returned.
|
||||
|
||||
If you just want to reduce the results using a javascript function
|
||||
you can just call the ``where()`` method:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$qb = $dm->createQueryBuilder('User')
|
||||
->where("function() { return this.type == 'admin'; }");
|
||||
|
||||
You can read more about the `$where operator <https://docs.mongodb.com/manual/reference/operator/query/where/>`_ in the Mongo docs.
|
||||
|
||||
Conditional Operators
|
||||
~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
The conditional operators in Mongo are available to limit the returned results through a easy to use API. Doctrine abstracts this to a fluent object oriented interface with a fluent API. Here is a list of all the conditional operation methods you can use on the `Query\Builder` object.
|
||||
|
||||
* ``where($javascript)``
|
||||
* ``in($values)``
|
||||
* ``notIn($values)``
|
||||
* ``equals($value)``
|
||||
* ``notEqual($value)``
|
||||
* ``gt($value)``
|
||||
* ``gte($value)``
|
||||
* ``lt($value)``
|
||||
* ``lte($value)``
|
||||
* ``range($start, $end)``
|
||||
* ``size($size)``
|
||||
* ``exists($bool)``
|
||||
* ``type($type)``
|
||||
* ``all($values)``
|
||||
* ``mod($mod)``
|
||||
* ``addOr($expr)``
|
||||
* ``references($document)``
|
||||
* ``includesReferenceTo($document)``
|
||||
|
||||
Query for active administrator users:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$qb = $dm->createQueryBuilder('User')
|
||||
->field('type')->equals('admin')
|
||||
->field('active')->equals(true);
|
||||
|
||||
Query for articles that have some tags:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$qb = $dm->createQueryBuilder('Article')
|
||||
->field('tags.name')->in(array('tag1', 'tag2'));
|
||||
|
||||
Read more about the
|
||||
`$in operator <https://docs.mongodb.com/manual/reference/operator/query/in/>`_
|
||||
in the Mongo docs
|
||||
|
||||
Query for articles that do not have some tags:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$qb = $dm->createQueryBuilder('Article')
|
||||
->field('tags.name')->notIn(array('tag3'));
|
||||
|
||||
Read more about the
|
||||
`$nin operator <https://docs.mongodb.com/manual/reference/operator/query/nin/>`_
|
||||
in the Mongo docs.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$qb = $dm->createQueryBuilder('User')
|
||||
->field('type')->notEqual('admin');
|
||||
|
||||
Read more about the
|
||||
`$ne operator <https://docs.mongodb.com/manual/reference/operator/query/ne/>`_
|
||||
in the Mongo docs.
|
||||
|
||||
Query for accounts with an amount due greater than 30:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$qb = $dm->createQueryBuilder('Account')
|
||||
->field('amount_due')->gt(30);
|
||||
|
||||
Query for accounts with an amount due greater than or equal to 30:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$qb = $dm->createQueryBuilder('Account')
|
||||
->field('amount_due')->gte(30);
|
||||
|
||||
Query for accounts with an amount due less than 30:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$qb = $dm->createQueryBuilder('Account')
|
||||
->field('amount_due')->lt(30);
|
||||
|
||||
Query for accounts with an amount due less than or equal to 30:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$qb = $dm->createQueryBuilder('Account')
|
||||
->field('amount_due')->lte(30);
|
||||
|
||||
Query for accounts with an amount due between 10 and 20:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$qb = $dm->createQueryBuilder('Account')
|
||||
->field('amount_due')->range(10, 20);
|
||||
|
||||
Read more about
|
||||
`conditional operators <http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-ConditionalOperators%3A%3C%2C%3C%3D%2C%3E%2C%3E%3D>`_
|
||||
in the Mongo docs.
|
||||
|
||||
Query for articles with no comments:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$qb = $dm->createQueryBuilder('Article')
|
||||
->field('comments')->size(0);
|
||||
|
||||
Read more about the
|
||||
`$size operator <https://docs.mongodb.com/manual/reference/operator/query/size/>`_
|
||||
in the Mongo docs.
|
||||
|
||||
Query for users that have a login field before it was renamed to
|
||||
username:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$qb = $dm->createQueryBuilder('User')
|
||||
->field('login')->exists(true);
|
||||
|
||||
Read more about the
|
||||
`$exists operator <https://docs.mongodb.com/manual/reference/operator/query/exists/>`_
|
||||
in the Mongo docs.
|
||||
|
||||
Query for users that have a type field that is of integer bson
|
||||
type:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$qb = $dm->createQueryBuilder('User')
|
||||
->field('type')->type('integer');
|
||||
|
||||
Read more about the
|
||||
`$type operator <https://docs.mongodb.com/manual/reference/operator/query/type/>`_
|
||||
in the Mongo docs.
|
||||
|
||||
Query for users that are in all the specified Groups:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$qb = $dm->createQueryBuilder('User')
|
||||
->field('groups')->all(array('Group 1', 'Group 2'));
|
||||
|
||||
Read more about the
|
||||
`$all operator <https://docs.mongodb.com/manual/reference/operator/query/all/>`_
|
||||
in the Mongo docs.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$qb = $dm->createQueryBuilder('Transaction')
|
||||
->field('field')->mod('field', array(10, 1));
|
||||
|
||||
Read more about the
|
||||
`$mod operator <https://docs.mongodb.com/manual/reference/operator/query/mod/>`_ in the Mongo docs.
|
||||
|
||||
Query for users who have subscribed or are in a trial.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$qb = $dm->createQueryBuilder('User');
|
||||
$qb->addOr($qb->expr()->field('subscriber')->equals(true));
|
||||
$qb->addOr($qb->expr()->field('inTrial')->equals(true));
|
||||
|
||||
Read more about the
|
||||
`$or operator <https://docs.mongodb.com/manual/reference/operator/query/or/>`_ in the Mongo docs.
|
||||
|
||||
The ``references()`` method may be used to query the owning side of a
|
||||
:ref:`@ReferenceOne <annotations_reference_reference_one>` relationship. In the
|
||||
following example, we query for all articles written by a particular user.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
// Suppose $user has already been fetched from the database
|
||||
$qb = $dm->createQueryBuilder('Article')
|
||||
->field('user')->references($user);
|
||||
|
||||
The ``includesReferenceTo()`` method may be used to query the owning side of a
|
||||
:ref:`@ReferenceMany <annotations_reference_reference_many>` relationship. In
|
||||
the following example, we query for the user(s) that have access to a particular
|
||||
account.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
// Suppose $account has already been fetched from the database
|
||||
$qb = $dm->createQueryBuilder('User')
|
||||
->field('accounts')->includesReferenceTo($account);
|
||||
|
||||
Text Search
|
||||
~~~~~~~~~~~
|
||||
|
||||
You can use the
|
||||
`$text operator <https://docs.mongodb.com/manual/reference/operator/query/text/>`_
|
||||
to run a text search against a field with a text index. To do so, create a
|
||||
document with a text index:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @Document
|
||||
* @Index(keys={"description"="text"})
|
||||
*/
|
||||
class Document
|
||||
{
|
||||
/** @Id */
|
||||
public $id;
|
||||
|
||||
/** @Field(type="string") */
|
||||
public $description;
|
||||
|
||||
/** @Field(type="float") @NotSaved */
|
||||
public $score;
|
||||
}
|
||||
|
||||
You can then run queries using the text operator:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
// Run a text search against the index
|
||||
$qb = $dm->createQueryBuilder('Document')
|
||||
->text('words you are looking for');
|
||||
|
||||
To fetch the calculated score for the text search, use the ``selectMeta()``
|
||||
method:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
// Run a text search against the index
|
||||
$qb = $dm->createQueryBuilder('Document')
|
||||
->selectMeta('score', 'textScore')
|
||||
->text('words you are looking for');
|
||||
|
||||
You can also change the language used for stemming using the ``language()``
|
||||
method:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
// Run a text search against the index
|
||||
$qb = $dm->createQueryBuilder('Document')
|
||||
->language('it')
|
||||
->text('parole che stai cercando');
|
||||
|
||||
|
||||
Update Queries
|
||||
~~~~~~~~~~~~~~
|
||||
|
||||
Doctrine also supports executing atomic update queries using the `Query\Builder`
|
||||
object. You can use the conditional operations in combination with the ability to
|
||||
change document field values atomically. Additionally if you are modifying a field
|
||||
that is a reference you can pass managed document to the Builder and let ODM build
|
||||
``DBRef`` object for you.
|
||||
|
||||
You have several modifier operations
|
||||
available to you that make it easy to update documents in Mongo:
|
||||
|
||||
* ``set($name, $value, $atomic = true)``
|
||||
* ``setNewObj($newObj)``
|
||||
* ``inc($name, $value)``
|
||||
* ``unsetField($field)``
|
||||
* ``push($field, $value)``
|
||||
* ``pushAll($field, array $valueArray)``
|
||||
* ``addToSet($field, $value)``
|
||||
* ``addManyToSet($field, array $values)``
|
||||
* ``popFirst($field)``
|
||||
* ``popLast($field)``
|
||||
* ``pull($field, $value)``
|
||||
* ``pullAll($field, array $valueArray)``
|
||||
|
||||
Updating multiple documents
|
||||
---------------------------
|
||||
|
||||
By default Mongo updates only one document unless ``multi`` option is provided and true.
|
||||
In ODM the distinction is done by explicitly calling ``updateMany()`` method of the builder:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$dm->createQueryBuilder('User')
|
||||
->updateMany()
|
||||
->field('someField')->set('newValue')
|
||||
->field('username')->equals('sgoettschkes')
|
||||
->getQuery()
|
||||
->execute();
|
||||
|
||||
.. note::
|
||||
``updateMany()`` and ``updateOne()`` methods were introduced in version 1.2. If you're
|
||||
using one of previous version you need to use ``update()`` combined with ``multiple(true)``.
|
||||
|
||||
Modifier Operations
|
||||
-------------------
|
||||
|
||||
Change a users password:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$dm->createQueryBuilder('User')
|
||||
->updateOne()
|
||||
->field('password')->set('newpassword')
|
||||
->field('username')->equals('jwage')
|
||||
->getQuery()
|
||||
->execute();
|
||||
|
||||
If you want to just set the values of an entirely new object you
|
||||
can do so by passing false as the third argument of ``set()`` to
|
||||
tell it the update is not an atomic one:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$dm->createQueryBuilder('User')
|
||||
->updateOne()
|
||||
->field('username')->set('jwage', false)
|
||||
->field('password')->set('password', false)
|
||||
// ... set other remaining fields
|
||||
->field('username')->equals('jwage')
|
||||
->getQuery()
|
||||
->execute();
|
||||
|
||||
Read more about the
|
||||
`$set modifier <https://docs.mongodb.com/manual/reference/operator/update/set/>`_
|
||||
in the Mongo docs.
|
||||
|
||||
You can set an entirely new object to update as well:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$dm->createQueryBuilder('User')
|
||||
->setNewObj(array(
|
||||
'username' => 'jwage',
|
||||
'password' => 'password',
|
||||
// ... other fields
|
||||
))
|
||||
->field('username')->equals('jwage')
|
||||
->getQuery()
|
||||
->execute();
|
||||
|
||||
Increment the value of a document:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$dm->createQueryBuilder('Package')
|
||||
->field('id')->equals('theid')
|
||||
->field('downloads')->inc(1)
|
||||
->getQuery()
|
||||
->execute();
|
||||
|
||||
Read more about the
|
||||
`$inc modifier <https://docs.mongodb.com/manual/reference/operator/update/inc/>`_
|
||||
in the Mongo docs.
|
||||
|
||||
Unset the login field from users where the login field still
|
||||
exists:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$dm->createQueryBuilder('User')
|
||||
->updateMany()
|
||||
->field('login')->unsetField()->exists(true)
|
||||
->getQuery()
|
||||
->execute();
|
||||
|
||||
Read more about the
|
||||
`$unset modifier <https://docs.mongodb.com/manual/reference/operator/update/unset/>`_
|
||||
in the Mongo docs.
|
||||
|
||||
Append new tag to the tags array:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$dm->createQueryBuilder('Article')
|
||||
->updateOne()
|
||||
->field('tags')->push('tag5')
|
||||
->field('id')->equals('theid')
|
||||
->getQuery()
|
||||
->execute();
|
||||
|
||||
Read more about the
|
||||
`$push modifier <https://docs.mongodb.com/manual/reference/operator/update/push/>`_
|
||||
in the Mongo docs.
|
||||
|
||||
Append new tags to the tags array:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$dm->createQueryBuilder('Article')
|
||||
->updateOne()
|
||||
->field('tags')->pushAll(array('tag6', 'tag7'))
|
||||
->field('id')->equals('theid')
|
||||
->getQuery()
|
||||
->execute();
|
||||
|
||||
Read more about the
|
||||
`$pushAll modifier <https://docs.mongodb.com/manual/reference/operator/update/pushAll/>`_
|
||||
in the Mongo docs.
|
||||
|
||||
Add value to array only if its not in the array already:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$dm->createQueryBuilder('Article')
|
||||
->updateOne()
|
||||
->field('tags')->addToSet('tag1')
|
||||
->field('id')->equals('theid')
|
||||
->getQuery()
|
||||
->execute();
|
||||
|
||||
Read more about the
|
||||
`$addToSet modifier <https://docs.mongodb.com/manual/reference/operator/update/addToSet/>`_
|
||||
in the Mongo docs.
|
||||
|
||||
Add many values to the array only if they do not exist in the array
|
||||
already:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$dm->createQueryBuilder('Article')
|
||||
->updateOne()
|
||||
->field('tags')->addManyToSet(array('tag6', 'tag7'))
|
||||
->field('id')->equals('theid')
|
||||
->getQuery()
|
||||
->execute();
|
||||
|
||||
Read more about the
|
||||
`$addManyToSet modifier <http://www.mongodb.org/display/DOCS/Updating#Updating-%24addManyToSet>`_
|
||||
in the Mongo docs.
|
||||
|
||||
Remove first element in an array:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$dm->createQueryBuilder('Article')
|
||||
->updateOne()
|
||||
->field('tags')->popFirst()
|
||||
->field('id')->equals('theid')
|
||||
->getQuery()
|
||||
->execute();
|
||||
|
||||
Remove last element in an array:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$dm->createQueryBuilder('Article')
|
||||
->updateOne()
|
||||
->field('tags')->popLast()
|
||||
->field('id')->equals('theid')
|
||||
->getQuery()
|
||||
->execute();
|
||||
|
||||
Read more about the
|
||||
`$pop modifier <https://docs.mongodb.com/manual/reference/operator/update/pop/>`_
|
||||
in the Mongo docs.
|
||||
|
||||
Remove all occurrences of value from array:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$dm->createQueryBuilder('Article')
|
||||
->updateMany()
|
||||
->field('tags')->pull('tag1')
|
||||
->getQuery()
|
||||
->execute();
|
||||
|
||||
Read more about the
|
||||
`$pull modifier <https://docs.mongodb.com/manual/reference/operator/update/pull/>`_
|
||||
in the Mongo docs.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$dm->createQueryBuilder('Article')
|
||||
->updateMany()
|
||||
->field('tags')->pullAll(array('tag1', 'tag2'))
|
||||
->getQuery()
|
||||
->execute();
|
||||
|
||||
Read more about the
|
||||
`$pullAll modifier <https://docs.mongodb.com/manual/reference/operator/update/pullAll/>`_
|
||||
in the Mongo docs.
|
||||
|
||||
Remove Queries
|
||||
--------------
|
||||
|
||||
In addition to updating you can also issue queries to remove
|
||||
documents from a collection. It works pretty much the same way as
|
||||
everything else and you can use the conditional operations to
|
||||
specify which documents you want to remove.
|
||||
|
||||
Here is an example where we remove users who have never logged in:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$dm->createQueryBuilder('User')
|
||||
->remove()
|
||||
->field('num_logins')->equals(0)
|
||||
->getQuery()
|
||||
->execute();
|
||||
|
||||
Group Queries
|
||||
-------------
|
||||
|
||||
.. note::
|
||||
|
||||
Due to deprecation of ``group`` command in MongoDB 3.4 the ODM
|
||||
also deprecates its usage through Query Builder in 1.2. Please
|
||||
use :ref:`$group stage <aggregation_builder_group>` of the
|
||||
Aggregation Builder instead.
|
||||
|
||||
The last type of supported query is a group query. It performs an
|
||||
operation similar to SQL's GROUP BY command.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$result = $this->dm->createQueryBuilder('Documents\User')
|
||||
->group(array(), array('count' => 0))
|
||||
->reduce('function (obj, prev) { prev.count++; }')
|
||||
->field('a')->gt(1)
|
||||
->getQuery()
|
||||
->execute();
|
||||
|
||||
This is the same as if we were to do the group with the raw PHP
|
||||
code:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$reduce = 'function (obj, prev) { prev.count++; }';
|
||||
$condition = array('a' => array( '$gt' => 1));
|
||||
$result = $collection->group(array(), array('count' => 0), $reduce, $condition);
|
||||
@@ -0,0 +1,495 @@
|
||||
Reference Mapping
|
||||
=================
|
||||
|
||||
This chapter explains how references between documents are mapped with Doctrine.
|
||||
|
||||
Collections
|
||||
-----------
|
||||
|
||||
Examples of many-valued references in this manual make use of a ``Collection``
|
||||
interface and a corresponding ``ArrayCollection`` implementation, which are
|
||||
defined in the ``Doctrine\Common\Collections`` namespace. These classes have no
|
||||
dependencies on ODM, and can therefore be used within your domain model and
|
||||
elsewhere without introducing coupling to the persistence layer.
|
||||
|
||||
ODM also provides a ``PersistentCollection`` implementation of ``Collection``,
|
||||
which incorporates change-tracking functionality; however, this class is
|
||||
constructed internally during hydration. As a developer, you should develop with
|
||||
the ``Collection`` interface in mind so that your code can operate with any
|
||||
implementation.
|
||||
|
||||
.. note::
|
||||
|
||||
New in 1.1: you are no longer limited to using ``ArrayCollection`` and can
|
||||
freely use your own ``Collection`` implementation. For more details please
|
||||
see :doc:`Custom Collections <custom-collections>` chapter.
|
||||
|
||||
Why are these classes used over PHP arrays? Native arrays cannot be
|
||||
transparently extended in PHP, which is necessary for many advanced features
|
||||
provided by the ODM. Although PHP does provide various interfaces that allow
|
||||
objects to operate like arrays (e.g. ``Traversable``, ``Countable``,
|
||||
``ArrayAccess``), and even a concrete implementation in ``ArrayObject``, these
|
||||
objects cannot always be used everywhere that a native array is accepted.
|
||||
Doctrine's ``Collection`` interface and ``ArrayCollection`` implementation are
|
||||
conceptually very similar to ``ArrayObject``, with some slight differences and
|
||||
improvements.
|
||||
|
||||
.. _reference_one:
|
||||
|
||||
Reference One
|
||||
-------------
|
||||
|
||||
Reference one document:
|
||||
|
||||
.. configuration-block::
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/** @Document */
|
||||
class Product
|
||||
{
|
||||
// ...
|
||||
|
||||
/**
|
||||
* @ReferenceOne(targetDocument="Shipping")
|
||||
*/
|
||||
private $shipping;
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
/** @Document */
|
||||
class Shipping
|
||||
{
|
||||
// ...
|
||||
}
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<doctrine-mongo-mapping xmlns="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping
|
||||
http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping.xsd">
|
||||
<document name="Documents\Product">
|
||||
<reference-one field="shipping" target-document="Documents\Shipping" />
|
||||
</document>
|
||||
</doctrine-mongo-mapping>
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
Product:
|
||||
type: document
|
||||
referenceOne:
|
||||
shipping:
|
||||
targetDocument: Documents\Shipping
|
||||
|
||||
.. _reference_many:
|
||||
|
||||
Reference Many
|
||||
--------------
|
||||
|
||||
Reference many documents:
|
||||
|
||||
.. configuration-block::
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/** @Document */
|
||||
class User
|
||||
{
|
||||
// ...
|
||||
|
||||
/**
|
||||
* @ReferenceMany(targetDocument="Account")
|
||||
*/
|
||||
private $accounts = array();
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
/** @Document */
|
||||
class Account
|
||||
{
|
||||
// ...
|
||||
}
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<doctrine-mongo-mapping xmlns="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping
|
||||
http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping.xsd">
|
||||
<document name="Documents\Product">
|
||||
<reference-many field="accounts" target-document="Documents\Account" />
|
||||
</document>
|
||||
</doctrine-mongo-mapping>
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
User:
|
||||
type: document
|
||||
referenceMany:
|
||||
accounts:
|
||||
targetDocument: Documents\Account
|
||||
|
||||
.. _reference_mixing_document_types:
|
||||
|
||||
Mixing Document Types
|
||||
---------------------
|
||||
|
||||
If you want to store different types of documents in references, you can simply
|
||||
omit the ``targetDocument`` option:
|
||||
|
||||
.. configuration-block::
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/** @Document */
|
||||
class User
|
||||
{
|
||||
// ..
|
||||
|
||||
/** @ReferenceMany */
|
||||
private $favorites = array();
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<field fieldName="favorites" />
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
referenceMany:
|
||||
favorites: ~
|
||||
|
||||
Now the ``$favorites`` property can store a reference to any type of document!
|
||||
The class name will be automatically stored in a field named
|
||||
``_doctrine_class_name`` within the `DBRef`_ object.
|
||||
|
||||
.. note::
|
||||
|
||||
The MongoDB shell tends to ignore fields other than ``$id`` and ``$ref``
|
||||
when displaying `DBRef`_ objects. You can verify the presence of any ``$db``
|
||||
and discriminator fields by querying and examining the document with a
|
||||
driver. See `SERVER-10777 <https://jira.mongodb.org/browse/SERVER-10777>`_
|
||||
for additional discussion on this issue.
|
||||
|
||||
The name of the field within the DBRef object can be customized via the
|
||||
``discriminatorField`` option:
|
||||
|
||||
.. configuration-block::
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/** @Document */
|
||||
class User
|
||||
{
|
||||
// ..
|
||||
|
||||
/**
|
||||
* @ReferenceMany(discriminatorField="type")
|
||||
*/
|
||||
private $favorites = array();
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<reference-many fieldName="favorites">
|
||||
<discriminator-field name="type" />
|
||||
</reference-many>
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
referenceMany:
|
||||
favorites:
|
||||
discriminatorField: type
|
||||
|
||||
You can also specify a discriminator map to avoid storing the |FQCN|
|
||||
in each `DBRef`_ object:
|
||||
|
||||
.. configuration-block::
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/** @Document */
|
||||
class User
|
||||
{
|
||||
// ..
|
||||
|
||||
/**
|
||||
* @ReferenceMany(
|
||||
* discriminatorMap={
|
||||
* "album"="Album",
|
||||
* "song"="Song"
|
||||
* }
|
||||
* )
|
||||
*/
|
||||
private $favorites = array();
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<reference-many fieldName="favorites">
|
||||
<discriminator-map>
|
||||
<discriminator-mapping value="album" class="Documents\Album" />
|
||||
<discriminator-mapping value="song" class="Documents\Song" />
|
||||
</discriminator-map>
|
||||
</reference-many>
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
referenceMany:
|
||||
favorites:
|
||||
discriminatorMap:
|
||||
album: Documents\Album
|
||||
song: Documents\Song
|
||||
|
||||
If you have references without a discriminator value that should be considered
|
||||
a certain class, you can optionally specify a default discriminator value:
|
||||
|
||||
.. configuration-block::
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/** @Document */
|
||||
class User
|
||||
{
|
||||
// ..
|
||||
|
||||
/**
|
||||
* @ReferenceMany(
|
||||
* discriminatorMap={
|
||||
* "album"="Album",
|
||||
* "song"="Song"
|
||||
* },
|
||||
* defaultDiscriminatorValue="album"
|
||||
* )
|
||||
*/
|
||||
private $favorites = array();
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<reference-many fieldName="favorites">
|
||||
<discriminator-map>
|
||||
<discriminator-mapping value="album" class="Documents\Album" />
|
||||
<discriminator-mapping value="song" class="Documents\Song" />
|
||||
</discriminator-map>
|
||||
<default-discriminator-value value="album" />
|
||||
</reference-many>
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
referenceMany:
|
||||
favorites:
|
||||
discriminatorMap:
|
||||
album: Documents\Album
|
||||
song: Documents\Song
|
||||
defaultDiscriminatorValue: album
|
||||
|
||||
.. _storing_references:
|
||||
|
||||
Storing References
|
||||
------------------
|
||||
|
||||
By default all references are stored as a `DBRef`_ object with the traditional
|
||||
``$ref``, ``$id``, and (optionally) ``$db`` fields (in that order). For references to
|
||||
documents of a single collection, storing the collection (and database) names for
|
||||
each reference may be redundant. You can use simple references to store the
|
||||
referenced document's identifier (e.g. ``MongoId``) instead of a `DBRef`_.
|
||||
|
||||
Example:
|
||||
|
||||
.. configuration-block::
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @ReferenceOne(targetDocument="Profile", storeAs="id")
|
||||
*/
|
||||
private $profile;
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<reference-one target-document="Documents\Profile", store-as="id" />
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
referenceOne:
|
||||
profile:
|
||||
storeAs: id
|
||||
|
||||
Now, the ``profile`` field will only store the ``MongoId`` of the referenced
|
||||
Profile document.
|
||||
|
||||
Simple references reduce the amount of storage used, both for the document
|
||||
itself and any indexes on the reference field; however, simple references cannot
|
||||
be used with discriminators, since there is no `DBRef`_ object in which to store
|
||||
a discriminator value.
|
||||
|
||||
In addition to saving references as `DBRef`_ with ``$ref``, ``$id``, and ``$db``
|
||||
fields and as ``MongoId``, it is possible to save references as `DBRef`_ without
|
||||
the ``$db`` field. This solves problems when the database name changes (and also
|
||||
reduces the amount of storage used).
|
||||
|
||||
The ``storeAs`` option has the following possible values:
|
||||
|
||||
- **dbRefWithDb**: Uses a `DBRef`_ with ``$ref``, ``$id``, and ``$db`` fields (this is the default)
|
||||
- **dbRef**: Uses a `DBRef`_ with ``$ref`` and ``$id``
|
||||
- **ref**: Uses a custom embedded object with an ``id`` field
|
||||
- **id**: Uses the identifier of the referenced object
|
||||
|
||||
.. note::
|
||||
|
||||
The ``storeAs=id`` option used to be called a "simple reference". The old syntax is
|
||||
still recognized (so using ``simple=true`` will imply ``storeAs=id``).
|
||||
|
||||
.. note::
|
||||
|
||||
For backwards compatibility ``storeAs=dbRefWithDb`` is the default, but
|
||||
``storeAs=ref`` is the recommended setting.
|
||||
|
||||
|
||||
Cascading Operations
|
||||
--------------------
|
||||
|
||||
By default, Doctrine will not cascade any ``UnitOfWork`` operations to
|
||||
referenced documents. You must explicitly enable this functionality:
|
||||
|
||||
.. configuration-block::
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @ReferenceOne(targetDocument="Profile", cascade={"persist"})
|
||||
*/
|
||||
private $profile;
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<reference-one target-document="Documents\Profile">
|
||||
<cascade>
|
||||
<persist/>
|
||||
</cascade>
|
||||
</reference-one>
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
referenceOne:
|
||||
profile:
|
||||
cascade: [persist]
|
||||
|
||||
The valid values are:
|
||||
|
||||
- **all** - cascade all operations by default.
|
||||
- **detach** - cascade detach operation to referenced documents.
|
||||
- **merge** - cascade merge operation to referenced documents.
|
||||
- **refresh** - cascade refresh operation to referenced documents.
|
||||
- **remove** - cascade remove operation to referenced documents.
|
||||
- **persist** - cascade persist operation to referenced documents.
|
||||
|
||||
Orphan Removal
|
||||
--------------
|
||||
|
||||
There is another concept of cascading that is relevant only when removing documents
|
||||
from collections. If a Document of type ``A`` contains references to privately
|
||||
owned Documents ``B`` then if the reference from ``A`` to ``B`` is removed the
|
||||
document ``B`` should also be removed, because it is not used anymore.
|
||||
|
||||
OrphanRemoval works with both reference one and many mapped fields.
|
||||
|
||||
.. note::
|
||||
|
||||
When using the ``orphanRemoval=true`` option Doctrine makes the assumption
|
||||
that the documents are privately owned and will **NOT** be reused by other documents.
|
||||
If you neglect this assumption your documents will get deleted by Doctrine even if
|
||||
you assigned the orphaned documents to another one.
|
||||
|
||||
As a better example consider an Addressbook application where you have Contacts, Addresses
|
||||
and StandingData:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
namespace Addressbook;
|
||||
|
||||
use Doctrine\Common\Collections\ArrayCollection;
|
||||
|
||||
/**
|
||||
* @Document
|
||||
*/
|
||||
class Contact
|
||||
{
|
||||
/** @Id */
|
||||
private $id;
|
||||
|
||||
/** @ReferenceOne(targetDocument="StandingData", orphanRemoval=true) */
|
||||
private $standingData;
|
||||
|
||||
/** @ReferenceMany(targetDocument="Address", mappedBy="contact", orphanRemoval=true) */
|
||||
private $addresses;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->addresses = new ArrayCollection();
|
||||
}
|
||||
|
||||
public function newStandingData(StandingData $sd)
|
||||
{
|
||||
$this->standingData = $sd;
|
||||
}
|
||||
|
||||
public function removeAddress($pos)
|
||||
{
|
||||
unset($this->addresses[$pos]);
|
||||
}
|
||||
}
|
||||
|
||||
Now two examples of what happens when you remove the references:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$contact = $dm->find("Addressbook\Contact", $contactId);
|
||||
$contact->newStandingData(new StandingData("Firstname", "Lastname", "Street"));
|
||||
$contact->removeAddress(1);
|
||||
|
||||
$dm->flush();
|
||||
|
||||
In this case you have not only changed the ``Contact`` document itself but
|
||||
you have also removed the references for standing data and as well as one
|
||||
address reference. When flush is called not only are the references removed
|
||||
but both the old standing data and the one address documents are also deleted
|
||||
from the database.
|
||||
|
||||
.. _`DBRef`: https://docs.mongodb.com/manual/reference/database-references/#dbrefs
|
||||
.. |FQCN| raw:: html
|
||||
<abbr title="Fully-Qualified Class Name">FQCN</abbr>
|
||||
@@ -0,0 +1,69 @@
|
||||
.. _sharding:
|
||||
|
||||
Sharding
|
||||
========
|
||||
|
||||
MongoDB allows you to horizontally scale your database. In order to enable this,
|
||||
Doctrine MongoDB ODM needs to know about your sharding setup. For basic information
|
||||
about sharding, please refer to the `MongoDB docs <https://docs.mongodb.com/manual/sharding/>`_.
|
||||
|
||||
Once you have a `sharded cluster <https://docs.mongodb.com/manual/core/sharded-cluster-architectures-production/>`_,
|
||||
you can enable sharding for a document. You can do this by defining a shard key in
|
||||
the document:
|
||||
|
||||
.. configuration-block::
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @Document
|
||||
* @ShardKey(keys={"username"="asc"})
|
||||
*/
|
||||
class User
|
||||
{
|
||||
/** @Id */
|
||||
public $id;
|
||||
|
||||
/** @Field(type="int") */
|
||||
public $accountId;
|
||||
|
||||
/** @Field(type="string") */
|
||||
public $username;
|
||||
}
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<doctrine-mongo-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mongo-mapping"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mongo-mapping
|
||||
http://doctrine-project.org/schemas/orm/doctrine-mongo-mapping.xsd">
|
||||
|
||||
<document name="Documents\User">
|
||||
<shard-key>
|
||||
<key name="username" order="asc"/>
|
||||
</shard-key>
|
||||
</document>
|
||||
</doctrine-mongo-mapping>
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
Documents\User:
|
||||
shardKey:
|
||||
keys:
|
||||
username: asc
|
||||
|
||||
.. note::
|
||||
When a shard key is defined for a document, Doctrine MongoDB ODM will no
|
||||
longer persist changes to the shard key as these fields become immutable in
|
||||
a sharded setup.
|
||||
|
||||
Once you've defined a shard key you need to enable sharding for the collection
|
||||
where the document will be stored. To do this, use the ``odm:schema:shard``
|
||||
command.
|
||||
|
||||
.. note::
|
||||
|
||||
For performance reasons, sharding is not enabled during the
|
||||
``odm:schema:create`` and ``odm:schema:update`` commmands.
|
||||
@@ -0,0 +1,71 @@
|
||||
Slave Okay Queries
|
||||
==================
|
||||
|
||||
.. note::
|
||||
|
||||
``slaveOkay`` was deprecated in 1.2 - please use `Read Preference <http://php.net/manual/en/mongo.readpreferences.php>`_
|
||||
instead.
|
||||
|
||||
Documents
|
||||
~~~~~~~~~
|
||||
|
||||
You can configure an entire document to send all reads to the slaves by using the ``slaveOkay`` flag:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/** @Document(slaveOkay=true) */
|
||||
class User
|
||||
{
|
||||
/** @Id */
|
||||
private $id;
|
||||
}
|
||||
|
||||
Now all reads involving the ``User`` document will be sent to a slave.
|
||||
|
||||
Queries
|
||||
~~~~~~~~~
|
||||
|
||||
If you want to instruct individual queries to read from a slave you can use the ``slaveOkay()`` method
|
||||
on the query builder.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$qb = $dm->createQueryBuilder('User')
|
||||
->slaveOkay(true);
|
||||
$query = $qb->getQuery();
|
||||
$users = $query->execute();
|
||||
|
||||
The data in the query above will be read from a slave. Even if you have a ``@ReferenceOne`` or
|
||||
``@ReferenceMany`` resulting from the query above it will be initialized and loaded from a slave.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/** @Document */
|
||||
class User
|
||||
{
|
||||
/** @ReferenceMany(targetDocument="Account") */
|
||||
private $accounts;
|
||||
}
|
||||
|
||||
Now when you query and iterate over the accounts, they will be loaded from a slave:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$qb = $dm->createQueryBuilder('User')
|
||||
->slaveOkay(true);
|
||||
$query = $qb->getQuery();
|
||||
$users = $query->execute();
|
||||
|
||||
foreach ($users as $user) {
|
||||
foreach ($user->getAccounts() as $account) {
|
||||
echo $account->getName();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
.. _storage_strategies:
|
||||
|
||||
Storage Strategies
|
||||
==================
|
||||
|
||||
Doctrine MongoDB ODM implements several different strategies for persisting changes
|
||||
to mapped fields. These strategies apply to the following mapping types:
|
||||
|
||||
- :ref:`int`
|
||||
- :ref:`float`
|
||||
- :ref:`embed_many`
|
||||
- :ref:`reference_many`
|
||||
|
||||
For collections, Doctrine tracks changes via the PersistentCollection class. The
|
||||
strategies described on this page are implemented by the CollectionPersister
|
||||
class. The ``increment`` strategy cannot be used for collections.
|
||||
|
||||
increment
|
||||
---------
|
||||
|
||||
The ``increment`` strategy does not apply to collections but can be used for
|
||||
``int`` and ``float`` fields. When using the ``increment`` strategy, the field
|
||||
value will be updated using the `$inc`_ operator.
|
||||
|
||||
addToSet
|
||||
--------
|
||||
|
||||
The ``addToSet`` strategy uses MongoDB's `$addToSet`_ operator to insert
|
||||
elements into the array. This strategy is useful for ensuring that duplicate
|
||||
values will not be inserted into the collection. Like the `pushAll`_ strategy,
|
||||
elements are inserted in a separate query after removing deleted elements.
|
||||
|
||||
set
|
||||
---
|
||||
|
||||
The ``set`` strategy uses MongoDB's `$set`_ operator to update the entire
|
||||
collection with a single update query.
|
||||
|
||||
.. note::
|
||||
|
||||
Doctrine's Collection interface is modeled after PHP's associative arrays,
|
||||
so they cannot always be represented as a BSON array. If the collection's
|
||||
keys are not sequential integers starting with zero, the ``set`` strategy
|
||||
will store the collection as a BSON object instead of an array. Use the
|
||||
`setArray`_ strategy if you want to ensure that the collection is always
|
||||
stored as a BSON array.
|
||||
|
||||
setArray
|
||||
--------
|
||||
|
||||
The ``setArray`` strategy uses MongoDB's `$set`_ operator, just like the ``set``
|
||||
strategy, but will first numerically reindex the collection to ensure that it is
|
||||
stored as a BSON array.
|
||||
|
||||
pushAll
|
||||
-------
|
||||
|
||||
The ``pushAll`` strategy uses MongoDB's `$pushAll`_ operator to insert
|
||||
elements into the array. MongoDB does not allow elements to be added and removed
|
||||
from an array in a single operation, so this strategy relies on multiple update
|
||||
queries to remove and insert elements (in that order).
|
||||
|
||||
.. _atomic_set:
|
||||
|
||||
atomicSet
|
||||
---------
|
||||
|
||||
The ``atomicSet`` strategy uses MongoDB's `$set`_ operator to update the entire
|
||||
collection with a single update query. Unlike with ``set`` strategy there will
|
||||
be only one query for updating both parent document and collection itself. This
|
||||
strategy can be especially useful when dealing with high concurrency and
|
||||
:ref:`versioned documents <annotations_reference_version>`.
|
||||
|
||||
.. note::
|
||||
|
||||
The ``atomicSet`` and ``atomicSetArray`` strategies may only be used for
|
||||
collections mapped directly in a top-level document.
|
||||
|
||||
.. _atomic_set_array:
|
||||
|
||||
atomicSetArray
|
||||
--------------
|
||||
|
||||
The ``atomicSetArray`` strategy works exactly like ``atomicSet`` strategy, but
|
||||
will first numerically reindex the collection to ensure that it is stored as a
|
||||
BSON array.
|
||||
|
||||
.. note::
|
||||
|
||||
The ``atomicSet`` and ``atomicSetArray`` strategies may only be used for
|
||||
collections mapped directly in a top-level document.
|
||||
|
||||
.. _`$addToSet`: https://docs.mongodb.com/manual/reference/operator/update/addToSet/
|
||||
.. _`$inc`: https://docs.mongodb.com/manual/reference/operator/update/inc/
|
||||
.. _`$pushAll`: https://docs.mongodb.com/manual/reference/operator/update/pushAll/
|
||||
.. _`$set`: https://docs.mongodb.com/manual/reference/operator/update/set/
|
||||
.. _`$unset`: https://docs.mongodb.com/manual/reference/operator/update/unset/
|
||||
@@ -0,0 +1,190 @@
|
||||
Storing Files with MongoGridFS
|
||||
==============================
|
||||
|
||||
The PHP Mongo extension provides a nice and convenient way to store
|
||||
files in chunks of data with the
|
||||
`MongoGridFS <http://us.php.net/manual/en/class.mongogridfs.php>`_.
|
||||
|
||||
It uses two database collections, one to store the metadata for the
|
||||
file, and another to store the contents of the file. The contents
|
||||
are stored in chunks to avoid going over the maximum allowed size
|
||||
of a MongoDB document.
|
||||
|
||||
You can easily setup a Document that is stored using the
|
||||
MongoGridFS:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
namespace Documents;
|
||||
|
||||
/** @Document */
|
||||
class Image
|
||||
{
|
||||
/** @Id */
|
||||
private $id;
|
||||
|
||||
/** @Field */
|
||||
private $name;
|
||||
|
||||
/** @File */
|
||||
private $file;
|
||||
|
||||
/** @Field */
|
||||
private $uploadDate;
|
||||
|
||||
/** @Field */
|
||||
private $length;
|
||||
|
||||
/** @Field */
|
||||
private $chunkSize;
|
||||
|
||||
/** @Field */
|
||||
private $md5;
|
||||
|
||||
public function getId()
|
||||
{
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
public function setName($name)
|
||||
{
|
||||
$this->name = $name;
|
||||
}
|
||||
|
||||
public function getName()
|
||||
{
|
||||
return $this->name;
|
||||
}
|
||||
|
||||
public function getFile()
|
||||
{
|
||||
return $this->file;
|
||||
}
|
||||
|
||||
public function setFile($file)
|
||||
{
|
||||
$this->file = $file;
|
||||
}
|
||||
}
|
||||
|
||||
Notice how we annotated the $file property with @File. This is what
|
||||
tells the Document that it is to be stored using the MongoGridFS
|
||||
and the MongoGridFSFile instance is placed in the $file property
|
||||
for you to access the actual file itself.
|
||||
|
||||
The $uploadDate, $chunkSize and $md5 properties are automatically filled in
|
||||
for each file stored in GridFS (whether you like that or not).
|
||||
Feel free to create getters in your document to actually make use of them,
|
||||
but keep in mind that their values will be initially unset for new objects
|
||||
until the next time the document is hydrated (fetched from the database).
|
||||
|
||||
First you need to create a new Image:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$image = new Image();
|
||||
$image->setName('Test image');
|
||||
$image->setFile('/path/to/image.png');
|
||||
|
||||
$dm->persist($image);
|
||||
$dm->flush();
|
||||
|
||||
Now you can later query for the Image and render it:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$image = $dm->createQueryBuilder('Documents\Image')
|
||||
->field('name')->equals('Test image')
|
||||
->getQuery()
|
||||
->getSingleResult();
|
||||
|
||||
header('Content-type: image/png;');
|
||||
echo $image->getFile()->getBytes();
|
||||
|
||||
You can of course make references to this Image document from
|
||||
another document. Imagine you had a Profile document and you wanted
|
||||
every Profile to have a profile image:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
namespace Documents;
|
||||
|
||||
/** @Document */
|
||||
class Profile
|
||||
{
|
||||
/** @Id */
|
||||
private $id;
|
||||
|
||||
/** @Field */
|
||||
private $name;
|
||||
|
||||
/** @ReferenceOne(targetDocument="Documents\Image") */
|
||||
private $image;
|
||||
|
||||
public function getId()
|
||||
{
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
public function getName()
|
||||
{
|
||||
return $this->name;
|
||||
}
|
||||
|
||||
public function setName($name)
|
||||
{
|
||||
$this->name = $name;
|
||||
}
|
||||
|
||||
public function getImage()
|
||||
{
|
||||
return $this->image;
|
||||
}
|
||||
|
||||
public function setImage(Image $image)
|
||||
{
|
||||
$this->image = $image;
|
||||
}
|
||||
}
|
||||
|
||||
Now you can create a new Profile and give it an Image:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$image = new Image();
|
||||
$image->setName('Test image');
|
||||
$image->setFile('/path/to/image.png');
|
||||
|
||||
$profile = new Profile();
|
||||
$profile->setName('Jonathan H. Wage');
|
||||
$profile->setImage($image);
|
||||
|
||||
$dm->persist($profile);
|
||||
$dm->flush();
|
||||
|
||||
If you want to query for the Profile and load the Image reference
|
||||
in a query you can use:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$profile = $dm->createQueryBuilder('Profile')
|
||||
->field('name')->equals('Jonathan H. Wage')
|
||||
->getQuery()
|
||||
->getSingleResult();
|
||||
|
||||
$image = $profile->getImage();
|
||||
|
||||
header('Content-type: image/png;');
|
||||
echo $image->getFile()->getBytes();
|
||||
@@ -0,0 +1,306 @@
|
||||
.. Heavily inspired by Doctrine 2 ORM documentation
|
||||
|
||||
Transactions and Concurrency
|
||||
============================
|
||||
|
||||
Transactions
|
||||
------------
|
||||
|
||||
As per the `documentation <https://docs.mongodb.com/manual/core/write-operations-atomicity/#atomicity-and-transactions>`_, MongoDB
|
||||
write operations are "atomic on the level of a single document".
|
||||
|
||||
Even when updating multiple documents within a single write operation,
|
||||
though the modification of each document is atomic,
|
||||
the operation as a whole is not and other operations may interleave.
|
||||
|
||||
As stated in the `FAQ <https://docs.mongodb.com/manual/faq/fundamentals/#does-mongodb-support-transactions>`_,
|
||||
"MongoDB does not support multi-document transactions" and neither does Doctrine MongoDB ODM.
|
||||
|
||||
Limitation
|
||||
~~~~~~~~~~
|
||||
At the moment, Doctrine MongoDB ODM does not provide any native strategy to emulate multi-document transactions.
|
||||
|
||||
Workaround
|
||||
~~~~~~~~~~
|
||||
To work around this limitation, one can utilize `two phase commits <https://docs.mongodb.com/manual/tutorial/perform-two-phase-commits/>`_.
|
||||
|
||||
Concurrency
|
||||
-----------
|
||||
|
||||
Doctrine MongoDB ODM offers native support for pessimistic and optimistic locking strategies.
|
||||
This allows for very fine-grained control over what kind of locking is required for documents in your application.
|
||||
|
||||
.. _transactions_and_concurrency_optimistic_locking:
|
||||
|
||||
Optimistic Locking
|
||||
~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Approach
|
||||
^^^^^^^^
|
||||
|
||||
Doctrine has integrated support for automatic optimistic locking
|
||||
via a ``version`` field. Any document that should be
|
||||
protected against concurrent modifications during long-running
|
||||
business transactions gets a ``version`` field that is either a simple
|
||||
number (mapping type: ``int``) or a date (mapping type: ``date``).
|
||||
When changes to the document are persisted,
|
||||
the expected version and version increment are incorporated into the update criteria and modifiers, respectively.
|
||||
If this results in no document being modified by the update (i.e. expected version did not match),
|
||||
a ``LockException`` is thrown, which indicates that the document was already modified by another query.
|
||||
|
||||
.. note::
|
||||
|
||||
| Versioning can only be used on *root* (top-level) documents.
|
||||
|
||||
Document Configuration
|
||||
^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
The following example designates a version field using the ``int`` type:
|
||||
|
||||
.. configuration-block::
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
/** @Version @Field(type="int") */
|
||||
private $version;
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<field fieldName="version" version="true" type="int" />
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
version:
|
||||
type: int
|
||||
version: true
|
||||
|
||||
|
||||
Alternatively, the ``date`` type may be used:
|
||||
|
||||
.. configuration-block::
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
/** @Version @Field(type="date") */
|
||||
private $version;
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<field fieldName="version" version="true" type="date" />
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
version:
|
||||
type: date
|
||||
version: true
|
||||
|
||||
Choosing the Field Type
|
||||
"""""""""""""""""""""""
|
||||
|
||||
When using the ``date`` type in a high-concurrency environment, it is still possible to create multiple documents
|
||||
with the same version and cause a conflict. This can be avoided by using the ``int`` type.
|
||||
|
||||
Usage
|
||||
"""""
|
||||
|
||||
When a version conflict is encountered during
|
||||
``DocumentManager#flush()``, a ``LockException`` is thrown.
|
||||
This exception can be caught and handled. Potential responses to a
|
||||
``LockException`` are to present the conflict to the user or
|
||||
to refresh or reload objects and then retry the update.
|
||||
|
||||
With PHP promoting a share-nothing architecture,
|
||||
the worst case scenario for a delay between rendering an update form (with existing document data)
|
||||
and modifying the document after a form submission may be your application's session timeout.
|
||||
If the document is changed within that time frame by some other request,
|
||||
it may be preferable to encounter a ``LockException`` when retrieving the document instead of executing the update.
|
||||
|
||||
You can specify the expected version of a document during a query with ``DocumentManager#find()``:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
use Doctrine\ODM\MongoDB\LockMode;
|
||||
use Doctrine\ODM\MongoDB\LockException;
|
||||
use Doctrine\ODM\MongoDB\DocumentManager;
|
||||
|
||||
$theDocumentId = 1;
|
||||
$expectedVersion = 184;
|
||||
|
||||
/* @var $dm DocumentManager */
|
||||
|
||||
try {
|
||||
$document = $dm->find('User', $theDocumentId, LockMode::OPTIMISTIC, $expectedVersion);
|
||||
|
||||
// do the work
|
||||
|
||||
$dm->flush();
|
||||
} catch(LockException $e) {
|
||||
echo "Sorry, but someone else has already changed this document. Please apply the changes again!";
|
||||
}
|
||||
|
||||
Alternatively, an expected version may be specified for an existing document with ``DocumentManager#lock()``:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
use Doctrine\ODM\MongoDB\LockMode;
|
||||
use Doctrine\ODM\MongoDB\LockException;
|
||||
use Doctrine\ODM\MongoDB\DocumentManager;
|
||||
|
||||
$theDocumentId = 1;
|
||||
$expectedVersion = 184;
|
||||
|
||||
/* @var $dm DocumentManager */
|
||||
|
||||
$document = $dm->find('User', $theDocumentId);
|
||||
|
||||
try {
|
||||
// assert version
|
||||
$dm->lock($document, LockMode::OPTIMISTIC, $expectedVersion);
|
||||
|
||||
} catch(LockException $e) {
|
||||
echo "Sorry, but someone else has already changed this document. Please apply the changes again!";
|
||||
}
|
||||
|
||||
Important Implementation Notes
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
You can easily get the optimistic locking workflow wrong if you
|
||||
compare the wrong versions.
|
||||
|
||||
Workflow
|
||||
""""""""
|
||||
|
||||
Say you have Alice and Bob editing a
|
||||
hypothetical blog post:
|
||||
|
||||
- Alice reads the headline of the blog post being "Foo", at
|
||||
optimistic lock version 1 (GET Request)
|
||||
- Bob reads the headline of the blog post being "Foo", at
|
||||
optimistic lock version 1 (GET Request)
|
||||
- Bob updates the headline to "Bar", upgrading the optimistic lock
|
||||
version to 2 (POST Request of a Form)
|
||||
- Alice updates the headline to "Baz", ... (POST Request of a
|
||||
Form)
|
||||
|
||||
At the last stage of this scenario the blog post has to be read
|
||||
again from the database before Alice's headline can be applied. At
|
||||
this point you will want to check if the blog post is still at
|
||||
version 1 (which it is not in this scenario).
|
||||
|
||||
In order to correctly utilize optimistic locking, you *must* add the version as hidden form field or,
|
||||
for more security, session attribute.
|
||||
Otherwise, you cannot verify that the version at the time of update is the same as what was originally read
|
||||
from the database when Alice performed her original GET request for the blog post.
|
||||
Without correlating the version across form submissions, the application could lose updates.
|
||||
|
||||
Example Code
|
||||
""""""""""""
|
||||
|
||||
The form (GET Request):
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
use Doctrine\ODM\MongoDB\DocumentManager;
|
||||
|
||||
/* @var $dm DocumentManager */
|
||||
|
||||
$post = $dm->find('BlogPost', 123456);
|
||||
|
||||
echo '<input type="hidden" name="id" value="' . $post->getId() . '" />';
|
||||
echo '<input type="hidden" name="version" value="' . $post->getCurrentVersion() . '" />';
|
||||
|
||||
And the change headline action (POST Request):
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
use Doctrine\ODM\MongoDB\DocumentManager;
|
||||
use Doctrine\ODM\MongoDB\LockMode;
|
||||
|
||||
/* @var $dm DocumentManager */
|
||||
|
||||
$postId = (int)$_POST['id'];
|
||||
$postVersion = (int)$_POST['version'];
|
||||
|
||||
$post = $dm->find('BlogPost', $postId, LockMode::OPTIMISTIC, $postVersion);
|
||||
|
||||
.. _transactions_and_concurrency_pessimistic_locking:
|
||||
|
||||
Pessimistic Locking
|
||||
~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Doctrine MongoDB ODM also supports pessimistic locking via a configurable ``lock`` field.
|
||||
This functionality is implemented entirely by Doctrine; MongoDB has no native support for pessimistic locking.
|
||||
|
||||
Document Configuration
|
||||
^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
Pessimistic locking requires a document to designate a lock field using the ``int`` type:
|
||||
|
||||
.. configuration-block::
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
/** @Lock @Field(type="int") */
|
||||
private $lock;
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<field fieldName="lock" lock="true" type="int" />
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
lock:
|
||||
type: int
|
||||
lock: true
|
||||
|
||||
Lock Modes
|
||||
^^^^^^^^^^
|
||||
|
||||
Doctrine MongoDB ODM currently supports two pessimistic lock modes:
|
||||
|
||||
- Pessimistic Write
|
||||
(``\Doctrine\ODM\MongoDB\LockMode::PESSIMISTIC_WRITE``): locks the
|
||||
underlying document for concurrent read and write operations.
|
||||
- Pessimistic Read (``\Doctrine\ODM\MongoDB\LockMode::PESSIMISTIC_READ``):
|
||||
locks other concurrent requests that attempt to update or lock documents
|
||||
in write mode.
|
||||
|
||||
Usage
|
||||
^^^^^
|
||||
|
||||
You can use pessimistic locks in two different scenarios:
|
||||
|
||||
1. Using
|
||||
``DocumentManager#find($className, $id, \Doctrine\ODM\MongoDB\LockMode::PESSIMISTIC_WRITE)``
|
||||
or
|
||||
``DocumentManager#find($className, $id, \Doctrine\ODM\MongoDB\LockMode::PESSIMISTIC_READ)``
|
||||
2. Using
|
||||
``DocumentManager#lock($document, \Doctrine\ODM\MongoDB\LockMode::PESSIMISTIC_WRITE)``
|
||||
or
|
||||
``DocumentManager#lock($document, \Doctrine\ODM\MongoDB\LockMode::PESSIMISTIC_READ)``
|
||||
|
||||
.. warning::
|
||||
|
||||
| A few things could go wrong:
|
||||
|
|
||||
| If a request fails to complete (e.g. unhandled exception), you may end up with stale locks.
|
||||
Said locks would need to be manually released or you would need to devise a strategy to automatically do so.
|
||||
One way to mitigate stale locks after an application error would be to gracefully catch the exception
|
||||
and ensure that relevant documents are unlocked before the request ends.
|
||||
|
|
||||
| `Deadlock <https://en.wikipedia.org/wiki/Deadlock>`_ situations are also possible.
|
||||
Suppose process P1 needs resource R1 and has locked resource R2
|
||||
and that another process P2 has locked resource R1 but also needs resource R2.
|
||||
If both processes continue waiting for the respective resources, the application will be stuck.
|
||||
When loading a document, Doctrine can immediately throw an exception if it is already locked.
|
||||
A deadlock could be created by endlessly retrying attempts to acquire the lock.
|
||||
One can avoid a possible deadlock by designating a maximum number of retry attempts
|
||||
and automatically releasing any active locks with the request ends,
|
||||
thereby allowing a process to end gracefully while another completes its task.
|
||||
@@ -0,0 +1,267 @@
|
||||
Trees
|
||||
=====
|
||||
|
||||
MongoDB lends itself quite well to storing hierarchical data. This
|
||||
chapter will demonstrate some examples!
|
||||
|
||||
Full Tree in Single Document
|
||||
----------------------------
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/** @Document */
|
||||
class BlogPost
|
||||
{
|
||||
/** @Id */
|
||||
private $id;
|
||||
|
||||
/** @Field(type="string") */
|
||||
private $title;
|
||||
|
||||
/** @Field(type="string") */
|
||||
private $body;
|
||||
|
||||
/** @EmbedMany(targetDocument="Comment") */
|
||||
private $comments = array();
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
/** @EmbeddedDocument */
|
||||
class Comment
|
||||
{
|
||||
/** @Field(type="string") */
|
||||
private $by;
|
||||
|
||||
/** @Field(type="string") */
|
||||
private $text;
|
||||
|
||||
/** @EmbedMany(targetDocument="Comment") */
|
||||
private $replies = array();
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
Retrieve a blog post and only select the first 10 comments:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$post = $dm->createQueryBuilder('BlogPost')
|
||||
->selectSlice('replies', 0, 10)
|
||||
->getQuery()
|
||||
->getSingleResult();
|
||||
|
||||
$replies = $post->getReplies();
|
||||
|
||||
You can read more about this pattern on the MongoDB documentation page "Trees in MongoDB" in the
|
||||
`Full Tree in Single Document <http://www.mongodb.org/display/DOCS/Trees+in+MongoDB#TreesinMongoDB-FullTreeinSingleDocument>`_ section.
|
||||
|
||||
Parent Reference
|
||||
----------------
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/** @Document */
|
||||
class Category
|
||||
{
|
||||
/** @Id */
|
||||
private $id;
|
||||
|
||||
/** @Field(type="string") */
|
||||
private $name;
|
||||
|
||||
/**
|
||||
* @ReferenceOne(targetDocument="Category")
|
||||
* @Index
|
||||
*/
|
||||
private $parent;
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
Query for children by a specific parent id:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$children = $dm->createQueryBuilder('Category')
|
||||
->field('parent.id')->equals('theid')
|
||||
->getQuery()
|
||||
->execute();
|
||||
|
||||
You can read more about this pattern on the MongoDB documentation page "Trees in MongoDB" in the
|
||||
`Parent Links <https://docs.mongodb.com/manual/tutorial/model-tree-structures/#model-tree-structures-with-parent-references>`_ section.
|
||||
|
||||
Child Reference
|
||||
---------------
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/** @Document */
|
||||
class Category
|
||||
{
|
||||
/** @Id */
|
||||
private $id;
|
||||
|
||||
/** @Field(type="string") */
|
||||
private $name;
|
||||
|
||||
/**
|
||||
* @ReferenceMany(targetDocument="Category")
|
||||
* @Index
|
||||
*/
|
||||
private $children = array();
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
Query for immediate children of a category:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$category = $dm->createQueryBuilder('Category')
|
||||
->field('id')->equals('theid')
|
||||
->getQuery()
|
||||
->getSingleResult();
|
||||
|
||||
$children = $category->getChildren();
|
||||
|
||||
Query for immediate parent of a category:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$parent = $dm->createQueryBuilder('Category')
|
||||
->field('children.id')->equals('theid')
|
||||
->getQuery()
|
||||
->getSingleResult();
|
||||
|
||||
You can read more about this pattern on the MongoDB documentation page "Trees in MongoDB" in the
|
||||
`Child Links <https://docs.mongodb.com/manual/tutorial/model-tree-structures/#model-tree-structures-with-child-references>`_ section.
|
||||
|
||||
Array of Ancestors
|
||||
------------------
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/** @MappedSuperclass */
|
||||
class BaseCategory
|
||||
{
|
||||
/** @Field(type="string") */
|
||||
private $name;
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
/** @Document */
|
||||
class Category extends BaseCategory
|
||||
{
|
||||
/** @Id */
|
||||
private $id;
|
||||
|
||||
/**
|
||||
* @ReferenceMany(targetDocument="Category")
|
||||
* @Index
|
||||
*/
|
||||
private $ancestors = array();
|
||||
|
||||
/**
|
||||
* @ReferenceOne(targetDocument="Category")
|
||||
* @Index
|
||||
*/
|
||||
private $parent;
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
/** @EmbeddedDocument */
|
||||
class SubCategory extends BaseCategory
|
||||
{
|
||||
}
|
||||
|
||||
Query for all descendants of a category:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$categories = $dm->createQueryBuilder('Category')
|
||||
->field('ancestors.id')->equals('theid')
|
||||
->getQuery()
|
||||
->execute();
|
||||
|
||||
Query for all ancestors of a category:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$category = $dm->createQuery('Category')
|
||||
->field('id')->equals('theid')
|
||||
->getQuery()
|
||||
->getSingleResult();
|
||||
|
||||
$ancestors = $category->getAncestors();
|
||||
|
||||
You can read more about this pattern on the MongoDB documentation page "Trees in MongoDB" in the
|
||||
`Array of Ancestors <https://docs.mongodb.com/manual/tutorial/model-tree-structures/#model-tree-structures-with-an-array-of-ancestors>`_ section.
|
||||
|
||||
Materialized Paths
|
||||
------------------
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
/** @Document */
|
||||
class Category
|
||||
{
|
||||
/** @Id */
|
||||
private $id;
|
||||
|
||||
/** @Field(type="string") */
|
||||
private $name;
|
||||
|
||||
/** @Field(type="string") */
|
||||
private $path;
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
Query for the entire tree:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$categories = $dm->createQuery('Category')
|
||||
->sort('path', 'asc')
|
||||
->getQuery()
|
||||
->execute();
|
||||
|
||||
Query for the node 'b' and all its descendants:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
$categories = $dm->createQuery('Category')
|
||||
->field('path')->equals('/^a,b,/')
|
||||
->getQuery()
|
||||
->execute();
|
||||
|
||||
You can read more about this pattern on the MongoDB documentation page "Trees in MongoDB" in the
|
||||
`Materialized Paths (Full Path in Each Node) <https://docs.mongodb.com/manual/tutorial/model-tree-structures/#model-tree-structures-with-materialized-paths>`_ section.
|
||||
@@ -0,0 +1,34 @@
|
||||
Upserting Documents
|
||||
===================
|
||||
|
||||
Upserting documents in the MongoDB ODM is easy. All you really have to do
|
||||
is specify an ID ahead of time and Doctrine will perform an ``update`` operation
|
||||
with the ``upsert`` flag internally instead of a ``batchInsert``.
|
||||
|
||||
Example:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$article = new Article();
|
||||
$article->setId($articleId);
|
||||
$article->incrementNumViews();
|
||||
$dm->persist($article);
|
||||
$dm->flush();
|
||||
|
||||
The above would result in an operation like the following:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$articleCollection->update(
|
||||
array('_id' => new MongoId($articleId)),
|
||||
array('$inc' => array('numViews' => 1)),
|
||||
array('upsert' => true, 'safe' => true)
|
||||
);
|
||||
|
||||
The extra benefit is the fact that you don't have to fetch the ``$article`` in order
|
||||
to append some new data to the document or change something. All you need is the
|
||||
identifier.
|
||||
@@ -0,0 +1,573 @@
|
||||
Working with Objects
|
||||
====================
|
||||
|
||||
Understanding
|
||||
-------------
|
||||
|
||||
In this chapter we will help you understand the ``DocumentManager``
|
||||
and the ``UnitOfWork``. A Unit of Work is similar to an
|
||||
object-level transaction. A new Unit of Work is implicitly started
|
||||
when a DocumentManager is initially created or after
|
||||
``DocumentManager#flush()`` has been invoked. A Unit of Work is
|
||||
committed (and a new one started) by invoking
|
||||
``DocumentManager#flush()``.
|
||||
|
||||
A Unit of Work can be manually closed by calling
|
||||
``DocumentManager#close()``. Any changes to objects within this
|
||||
Unit of Work that have not yet been persisted are lost.
|
||||
|
||||
The size of a Unit of Work
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
The size of a Unit of Work mainly refers to the number of managed
|
||||
documents at a particular point in time.
|
||||
|
||||
The cost of flush()
|
||||
~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
How costly a flush operation is in terms of performance mainly
|
||||
depends on the size. You can get the size of your Unit of Work as
|
||||
follows:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$uowSize = $dm->getUnitOfWork()->size();
|
||||
|
||||
The size represents the number of managed documents in the Unit of
|
||||
Work. This size affects the performance of flush() operations due
|
||||
to change tracking and, of course, memory consumption, so you may
|
||||
want to check it from time to time during development.
|
||||
|
||||
.. caution::
|
||||
|
||||
Do not invoke ``flush`` after every change to a
|
||||
document or every single invocation of persist/remove/merge/...
|
||||
This is an anti-pattern and unnecessarily reduces the performance
|
||||
of your application. Instead, form units of work that operate on
|
||||
your objects and call ``flush`` when you are done. While serving a
|
||||
single HTTP request there should be usually no need for invoking
|
||||
``flush`` more than 0-2 times.
|
||||
|
||||
Direct access to a Unit of Work
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
You can get direct access to the Unit of Work by calling
|
||||
``DocumentManager#getUnitOfWork()``. This will return the
|
||||
UnitOfWork instance the DocumentManager is currently using.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$uow = $dm->getUnitOfWork();
|
||||
|
||||
.. note::
|
||||
|
||||
Directly manipulating a UnitOfWork is not recommended.
|
||||
When working directly with the UnitOfWork API, respect methods
|
||||
marked as INTERNAL by not using them and carefully read the API
|
||||
documentation.
|
||||
|
||||
Persisting documents
|
||||
--------------------
|
||||
|
||||
A document can be made persistent by passing it to the
|
||||
``DocumentManager#persist($document)`` method. By applying the
|
||||
persist operation on some document, that document becomes MANAGED,
|
||||
which means that its persistence is from now on managed by an
|
||||
DocumentManager. As a result the persistent state of such a
|
||||
document will subsequently be properly synchronized with the
|
||||
database when ``DocumentManager#flush()`` is invoked.
|
||||
|
||||
.. caution::
|
||||
|
||||
Invoking the ``persist`` method on a document does NOT
|
||||
cause an immediate insert to be issued on the database. Doctrine
|
||||
applies a strategy called "transactional write-behind", which means
|
||||
that it will delay most operations until
|
||||
``DocumentManager#flush()`` is invoked which will then issue all
|
||||
necessary queries to synchronize your objects with the database in
|
||||
the most efficient way.
|
||||
|
||||
Example:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$user = new User();
|
||||
$user->setUsername('jwage');
|
||||
$user->setPassword('changeme');
|
||||
$dm->persist($user);
|
||||
$dm->flush();
|
||||
|
||||
.. caution::
|
||||
|
||||
The document identifier is generated during ``persist`` if not previously
|
||||
specified. Users cannot rely on a document identifier being available during
|
||||
the ``prePersist`` event.
|
||||
|
||||
The semantics of the persist operation, applied on a document X,
|
||||
are as follows:
|
||||
|
||||
-
|
||||
If X is a new document, it becomes managed. The document X will be
|
||||
entered into the database as a result of the flush operation.
|
||||
-
|
||||
If X is a preexisting managed document, it is ignored by the
|
||||
persist operation. However, the persist operation is cascaded to
|
||||
documents referenced by X, if the relationships from X to these
|
||||
other documents are mapped with cascade=PERSIST or cascade=ALL.
|
||||
- If X is a removed document, it becomes managed.
|
||||
- If X is a detached document, the behavior is undefined.
|
||||
|
||||
.. caution::
|
||||
|
||||
Do not pass detached documents to the persist operation.
|
||||
|
||||
.. _flush_options:
|
||||
|
||||
Flush Options
|
||||
-------------
|
||||
|
||||
When committing your documents you can specify an array of options to the
|
||||
``flush`` method. With it you can send options to the underlying database
|
||||
like ``safe``, ``fsync``, etc.
|
||||
|
||||
Example:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$user = $dm->getRepository('User')->find($userId);
|
||||
// ...
|
||||
$user->setPassword('changeme');
|
||||
$dm->flush(null, array('safe' => true, 'fsync' => true));
|
||||
|
||||
You can configure the default flush options on your ``Configuration`` object
|
||||
if you want to set them globally for all flushes.
|
||||
|
||||
Example:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$config->setDefaultCommitOptions(array(
|
||||
'safe' => true,
|
||||
'fsync' => true
|
||||
));
|
||||
|
||||
.. note::
|
||||
|
||||
Safe is set to true by default for all writes when using the ODM.
|
||||
|
||||
Removing documents
|
||||
------------------
|
||||
|
||||
A document can be removed from persistent storage by passing it to
|
||||
the ``DocumentManager#remove($document)`` method. By applying the
|
||||
``remove`` operation on some document, that document becomes
|
||||
REMOVED, which means that its persistent state will be deleted once
|
||||
``DocumentManager#flush()`` is invoked. The in-memory state of a
|
||||
document is unaffected by the ``remove`` operation.
|
||||
|
||||
.. caution::
|
||||
|
||||
Just like ``persist``, invoking ``remove`` on a
|
||||
document does NOT cause an immediate query to be issued on the
|
||||
database. The document will be removed on the next invocation of
|
||||
``DocumentManager#flush()`` that involves that document.
|
||||
|
||||
Example:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$dm->remove($user);
|
||||
$dm->flush();
|
||||
|
||||
The semantics of the remove operation, applied to a document X are
|
||||
as follows:
|
||||
|
||||
-
|
||||
If X is a new document, it is ignored by the remove operation.
|
||||
However, the remove operation is cascaded to documents referenced
|
||||
by X, if the relationship from X to these other documents is mapped
|
||||
with cascade=REMOVE or cascade=ALL.
|
||||
-
|
||||
If X is a managed document, the remove operation causes it to
|
||||
become removed. The remove operation is cascaded to documents
|
||||
referenced by X, if the relationships from X to these other
|
||||
documents is mapped with cascade=REMOVE or cascade=ALL.
|
||||
-
|
||||
If X is a detached document, an InvalidArgumentException will be
|
||||
thrown.
|
||||
-
|
||||
If X is a removed document, it is ignored by the remove operation.
|
||||
-
|
||||
A removed document X will be removed from the database as a result
|
||||
of the flush operation.
|
||||
|
||||
Detaching documents
|
||||
-------------------
|
||||
|
||||
A document is detached from a DocumentManager and thus no longer
|
||||
managed by invoking the ``DocumentManager#detach($document)``
|
||||
method on it or by cascading the detach operation to it. Changes
|
||||
made to the detached document, if any (including removal of the
|
||||
document), will not be synchronized to the database after the
|
||||
document has been detached.
|
||||
|
||||
Doctrine will not hold on to any references to a detached
|
||||
document.
|
||||
|
||||
Example:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$dm->detach($document);
|
||||
|
||||
The semantics of the detach operation, applied to a document X are
|
||||
as follows:
|
||||
|
||||
|
||||
-
|
||||
If X is a managed document, the detach operation causes it to
|
||||
become detached. The detach operation is cascaded to documents
|
||||
referenced by X, if the relationships from X to these other
|
||||
documents is mapped with cascade=DETACH or cascade=ALL. Documents
|
||||
which previously referenced X will continue to reference X.
|
||||
-
|
||||
If X is a new or detached document, it is ignored by the detach
|
||||
operation.
|
||||
-
|
||||
If X is a removed document, the detach operation is cascaded to
|
||||
documents referenced by X, if the relationships from X to these
|
||||
other documents is mapped with cascade=DETACH or
|
||||
cascade=ALL/Documents which previously referenced X will continue
|
||||
to reference X.
|
||||
|
||||
There are several situations in which a document is detached
|
||||
automatically without invoking the ``detach`` method:
|
||||
|
||||
|
||||
-
|
||||
When ``DocumentManager#clear()`` is invoked, all documents that are
|
||||
currently managed by the DocumentManager instance become detached.
|
||||
-
|
||||
When serializing a document. The document retrieved upon subsequent
|
||||
unserialization will be detached (This is the case for all
|
||||
documents that are serialized and stored in some cache).
|
||||
|
||||
The ``detach`` operation is usually not as frequently needed and
|
||||
used as ``persist`` and ``remove``.
|
||||
|
||||
Merging documents
|
||||
-----------------
|
||||
|
||||
Merging documents refers to the merging of (usually detached)
|
||||
documents into the context of a DocumentManager so that they
|
||||
become managed again. To merge the state of a document into an
|
||||
DocumentManager use the ``DocumentManager#merge($document)``
|
||||
method. The state of the passed document will be merged into a
|
||||
managed copy of this document and this copy will subsequently be
|
||||
returned.
|
||||
|
||||
Example:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$detachedDocument = unserialize($serializedDocument); // some detached document
|
||||
$document = $dm->merge($detachedDocument);
|
||||
// $document now refers to the fully managed copy returned by the merge operation.
|
||||
// The DocumentManager $dm now manages the persistence of $document as usual.
|
||||
|
||||
The semantics of the merge operation, applied to a document X, are
|
||||
as follows:
|
||||
|
||||
-
|
||||
If X is a detached document, the state of X is copied onto a
|
||||
pre-existing managed document instance X' of the same iddocument or
|
||||
a new managed copy X' of X is created.
|
||||
-
|
||||
If X is a new document instance, an InvalidArgumentException will
|
||||
be thrown.
|
||||
-
|
||||
If X is a removed document instance, an InvalidArgumentException
|
||||
will be thrown.
|
||||
-
|
||||
If X is a managed document, it is ignored by the merge operation,
|
||||
however, the merge operation is cascaded to documents referenced by
|
||||
relationships from X if these relationships have been mapped with
|
||||
the cascade element value MERGE or ALL.
|
||||
-
|
||||
For all documents Y referenced by relationships from X having the
|
||||
cascade element value MERGE or ALL, Y is merged recursively as Y'.
|
||||
For all such Y referenced by X, X' is set to reference Y'. (Note
|
||||
that if X is managed then X is the same object as X'.)
|
||||
-
|
||||
If X is a document merged to X', with a reference to another
|
||||
document Y, where cascade=MERGE or cascade=ALL is not specified,
|
||||
then navigation of the same association from X' yields a reference
|
||||
to a managed object Y' with the same persistent iddocument as Y.
|
||||
|
||||
The ``merge`` operation is usually not as frequently needed and
|
||||
used as ``persist`` and ``remove``. The most common scenario for
|
||||
the ``merge`` operation is to reattach documents to an
|
||||
DocumentManager that come from some cache (and are therefore
|
||||
detached) and you want to modify and persist such a document.
|
||||
|
||||
.. note::
|
||||
|
||||
If you load some detached documents from a cache and you
|
||||
do not need to persist or delete them or otherwise make use of them
|
||||
without the need for persistence services there is no need to use
|
||||
``merge``. I.e. you can simply pass detached objects from a cache
|
||||
directly to the view.
|
||||
|
||||
References
|
||||
----------
|
||||
|
||||
References between documents and embedded documents are represented
|
||||
just like in regular object-oriented PHP, with references to other
|
||||
objects or collections of objects.
|
||||
|
||||
Establishing References
|
||||
-----------------------
|
||||
|
||||
Establishing a reference to another document is straight forward:
|
||||
|
||||
Here is an example where we add a new comment to an article:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$comment = new Comment();
|
||||
// ...
|
||||
|
||||
$article->getComments()->add($comment);
|
||||
|
||||
Or you can set a single reference:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$address = new Address();
|
||||
// ...
|
||||
|
||||
$user->setAddress($address);
|
||||
|
||||
Removing References
|
||||
-------------------
|
||||
|
||||
Removing an association between two documents is similarly
|
||||
straight-forward. There are two strategies to do so, by key and by
|
||||
element. Here are some examples:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$article->getComments()->removeElement($comment);
|
||||
$article->getComments()->remove($ithComment);
|
||||
|
||||
Or you can remove a single reference:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$user->setAddress(null);
|
||||
|
||||
When working with collections, keep in mind that a Collection is
|
||||
essentially an ordered map (just like a PHP array). That is why the
|
||||
``remove`` operation accepts an index/key. ``removeElement`` is a
|
||||
separate method that has O(n) complexity, where n is the size of
|
||||
the map.
|
||||
|
||||
Transitive persistence
|
||||
----------------------
|
||||
|
||||
Persisting, removing, detaching and merging individual documents
|
||||
can become pretty cumbersome, especially when a larger object graph
|
||||
with collections is involved. Therefore Doctrine provides a
|
||||
mechanism for transitive persistence through cascading of these
|
||||
operations. Each reference to another document or a collection of
|
||||
documents can be configured to automatically cascade certain
|
||||
operations. By default, no operations are cascaded.
|
||||
|
||||
The following cascade options exist:
|
||||
|
||||
|
||||
-
|
||||
persist : Cascades persist operations to the associated documents.
|
||||
- remove : Cascades remove operations to the associated documents.
|
||||
- merge : Cascades merge operations to the associated documents.
|
||||
- detach : Cascades detach operations to the associated documents.
|
||||
-
|
||||
all : Cascades persist, remove, merge and detach operations to
|
||||
associated documents.
|
||||
|
||||
The following example shows an association to a number of
|
||||
addresses. If persist() or remove() is invoked on any User
|
||||
document, it will be cascaded to all associated Address documents
|
||||
in the $addresses collection.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
class User
|
||||
{
|
||||
//...
|
||||
/**
|
||||
* @ReferenceMany(targetDocument="Address", cascade={"persist", "remove"})
|
||||
*/
|
||||
private $addresses;
|
||||
//...
|
||||
}
|
||||
|
||||
Even though automatic cascading is convenient it should be used
|
||||
with care. Do not blindly apply cascade=all to all associations as
|
||||
it will unnecessarily degrade the performance of your application.
|
||||
|
||||
Querying
|
||||
--------
|
||||
|
||||
Doctrine provides the following ways, in increasing level of power
|
||||
and flexibility, to query for persistent objects. You should always
|
||||
start with the simplest one that suits your needs.
|
||||
|
||||
By Primary Key
|
||||
~~~~~~~~~~~~~~
|
||||
|
||||
The most basic way to query for a persistent object is by its
|
||||
identifier / primary key using the
|
||||
``DocumentManager#find($documentName, $id)`` method. Here is an
|
||||
example:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$user = $dm->find('User', $id);
|
||||
|
||||
The return value is either the found document instance or null if
|
||||
no instance could be found with the given identifier.
|
||||
|
||||
Essentially, ``DocumentManager#find()`` is just a shortcut for the
|
||||
following:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$user = $dm->getRepository('User')->find($id);
|
||||
|
||||
``DocumentManager#getRepository($documentName)`` returns a
|
||||
repository object which provides many ways to retrieve documents of
|
||||
the specified type. By default, the repository instance is of type
|
||||
``Doctrine\ODM\MongoDB\DocumentRepository``. You can also use
|
||||
custom repository classes.
|
||||
|
||||
By Simple Conditions
|
||||
~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
To query for one or more documents based on several conditions that
|
||||
form a logical conjunction, use the ``findBy`` and ``findOneBy``
|
||||
methods on a repository as follows:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
// All users that are 20 years old
|
||||
$users = $dm->getRepository('User')->findBy(array('age' => 20));
|
||||
|
||||
// All users that are 20 years old and have a surname of 'Miller'
|
||||
$users = $dm->getRepository('User')->findBy(array('age' => 20, 'surname' => 'Miller'));
|
||||
|
||||
// A single user by its nickname
|
||||
$user = $dm->getRepository('User')->findOneBy(array('nickname' => 'romanb'));
|
||||
|
||||
A DocumentRepository also provides a mechanism for more concise
|
||||
calls through its use of ``__call``. Thus, the following two
|
||||
examples are equivalent:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
// A single user by its nickname
|
||||
$user = $dm->getRepository('User')->findOneBy(array('nickname' => 'romanb'));
|
||||
|
||||
// A single user by its nickname (__call magic)
|
||||
$user = $dm->getRepository('User')->findOneByNickname('romanb');
|
||||
|
||||
.. note::
|
||||
|
||||
You can learn more about Repositories in a :ref:`dedicated chapter <document_repositories>`.
|
||||
|
||||
By Lazy Loading
|
||||
~~~~~~~~~~~~~~~
|
||||
|
||||
Whenever you have a managed document instance at hand, you can
|
||||
traverse and use any associations of that document as if they were
|
||||
in-memory already. Doctrine will automatically load the associated
|
||||
objects on demand through the concept of lazy-loading.
|
||||
|
||||
By Query Builder Objects
|
||||
~~~~~~~~~~~~~~~~
|
||||
|
||||
The most powerful and flexible method to query for persistent
|
||||
objects is the Query\Builder object. The Query\Builder object enables you to query
|
||||
for persistent objects with a fluent object oriented interface.
|
||||
|
||||
You can create a query using
|
||||
``DocumentManager#createQueryBuilder($documentName = null)``. Here is a
|
||||
simple example:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
// All users with an age between 20 and 30 (inclusive).
|
||||
$qb = $dm->createQueryBuilder('User')
|
||||
->field('age')->range(20, 30);
|
||||
$q = $qb->getQuery()
|
||||
$users = $q->execute();
|
||||
|
||||
By Reference
|
||||
~~~~~~~~~~~~~~~~
|
||||
|
||||
To query documents with a ReferenceOne association to another document, use the ``references($document)`` expression:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$group = $dm->find('Group', $id);
|
||||
$usersWithGroup = $dm->createQueryBuilder('User')
|
||||
->field('group')->references($group)
|
||||
->getQuery()->execute();
|
||||
|
||||
To find documents with a ReferenceMany association that includes a certain document, use the ``includesReferenceTo($document)`` expression:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$users = $dm->createQueryBuilder('User')
|
||||
->field('groups')->includesReferenceTo($group)
|
||||
->getQuery()->execute();
|
||||
@@ -0,0 +1,188 @@
|
||||
XML Mapping
|
||||
===========
|
||||
|
||||
The XML mapping driver enables you to provide the ODM metadata in
|
||||
form of XML documents.
|
||||
|
||||
The XML driver is backed by an XML Schema document that describes
|
||||
the structure of a mapping document. The most recent version of the
|
||||
XML Schema document is available online at
|
||||
`http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping.xsd <http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping.xsd>`_.
|
||||
The most convenient way to work with XML mapping files is to use an
|
||||
IDE/editor that can provide code-completion based on such an XML
|
||||
Schema document. The following is an outline of a XML mapping
|
||||
document with the proper xmlns/xsi setup for the latest code in
|
||||
trunk.
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<doctrine-mongo-mapping xmlns="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping
|
||||
http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping.xsd">
|
||||
|
||||
...
|
||||
|
||||
</doctrine-mongo-mapping>
|
||||
|
||||
.. note::
|
||||
|
||||
If you do not want to use latest XML Schema document please use link like
|
||||
`http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping-1.0.0-BETA12.xsd <http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping-1.0.0-BETA12.xsd>`_.
|
||||
You can change ``1.0.0-BETA12`` part of the URL to
|
||||
`any other ODM version <https://github.com/doctrine/mongodb-odm/releases>`_.
|
||||
|
||||
The XML mapping document of a class is loaded on-demand the first
|
||||
time it is requested and subsequently stored in the metadata cache.
|
||||
In order to work, this requires certain conventions:
|
||||
|
||||
|
||||
-
|
||||
Each document/mapped superclass must get its own dedicated XML
|
||||
mapping document.
|
||||
-
|
||||
The name of the mapping document must consist of the fully
|
||||
qualified name of the class, where namespace separators are
|
||||
replaced by dots (.).
|
||||
-
|
||||
All mapping documents should get the extension ".dcm.xml" to
|
||||
identify it as a Doctrine mapping file. This is more of a
|
||||
convention and you are not forced to do this. You can change the
|
||||
file extension easily enough.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$driver->setFileExtension('.xml');
|
||||
|
||||
It is recommended to put all XML mapping documents in a single
|
||||
folder but you can spread the documents over several folders if you
|
||||
want to. In order to tell the XmlDriver where to look for your
|
||||
mapping documents, supply an array of paths as the first argument
|
||||
of the constructor, like this:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
// $config instanceof Doctrine\ODM\MongoDB\Configuration
|
||||
$driver = new XmlDriver(array('/path/to/files'));
|
||||
$config->setMetadataDriverImpl($driver);
|
||||
|
||||
Simplified XML Driver
|
||||
~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
The Symfony project sponsored a driver that simplifies usage of the XML Driver.
|
||||
The changes between the original driver are:
|
||||
|
||||
1. File Extension is .mongodb-odm.xml
|
||||
2. Filenames are shortened, "MyProject\Documents\User" will become User.mongodb-odm.xml
|
||||
3. You can add a global file and add multiple documents in this file.
|
||||
|
||||
Configuration of this client works a little bit different:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
$namespaces = array(
|
||||
'MyProject\Documents' => '/path/to/files1',
|
||||
'OtherProject\Documents' => '/path/to/files2'
|
||||
);
|
||||
$driver = new \Doctrine\ODM\MongoDB\Mapping\Driver\SimplifiedXmlDriver($namespaces);
|
||||
$driver->setGlobalBasename('global'); // global.mongodb-odm.xml
|
||||
|
||||
Example
|
||||
-------
|
||||
|
||||
As a quick start, here is a small example document that makes use
|
||||
of several common elements:
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
// Documents.User.dcm.xml
|
||||
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
|
||||
<doctrine-mongo-mapping xmlns="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping
|
||||
http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping.xsd">
|
||||
|
||||
<document name="Documents\User" db="documents" collection="users">
|
||||
<field fieldName="id" id="true" />
|
||||
<field fieldName="username" name="login" type="string" />
|
||||
<field fieldName="email" type="string" unique="true" order="desc" />
|
||||
<field fieldName="createdAt" type="date" />
|
||||
<indexes>
|
||||
<index unique="true" dropDups="true">
|
||||
<key name="username" order="desc">
|
||||
<option name="safe" value="true" />
|
||||
</index>
|
||||
</indexes>
|
||||
<embed-one target-document="Documents\Address" field="address" />
|
||||
<reference-one target-document="Documents\Profile" field="profile">
|
||||
<cascade>
|
||||
<all />
|
||||
</cascade>
|
||||
</reference-one>
|
||||
<embed-many target-document="Documents\Phonenumber" field="phonenumbers" />
|
||||
<reference-many target-document="Documents\Group" field="groups">
|
||||
<cascade>
|
||||
<all />
|
||||
</cascade>
|
||||
</reference-many>
|
||||
<reference-one target-document="Documents\Account" field="account">
|
||||
<cascade>
|
||||
<all />
|
||||
</cascade>
|
||||
</reference-one>
|
||||
</document>
|
||||
</doctrine-mongo-mapping>
|
||||
|
||||
Be aware that class-names specified in the XML files should be fully qualified.
|
||||
|
||||
.. note::
|
||||
|
||||
``field-name`` is the name of **property in your object** while ``name`` specifies
|
||||
name of the field **in the database**. Specifying latter is optional and defaults to
|
||||
``field-name`` if not set explicitly.
|
||||
|
||||
Reference
|
||||
---------
|
||||
|
||||
.. _xml_reference_lock:
|
||||
|
||||
Lock
|
||||
^^^^
|
||||
|
||||
The field with the ``lock`` attribute will be used to store lock information for :ref:`pessimistic locking <transactions_and_concurrency_pessimistic_locking>`.
|
||||
This is only compatible with the ``int`` field type, and cannot be combined with ``id="true"``.
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<doctrine-mongo-mapping>
|
||||
<field fieldName="lock" lock="true" type="int" />
|
||||
</doctrine-mongo-mapping>
|
||||
|
||||
.. _xml_reference_version:
|
||||
|
||||
Version
|
||||
^^^^^^^
|
||||
|
||||
The field with the ``version`` attribute will be used to store version information for :ref:`optimistic locking <transactions_and_concurrency_optimistic_locking>`.
|
||||
This is only compatible with ``int`` and ``date`` field types, and cannot be combined with ``id="true"``.
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<doctrine-mongo-mapping>
|
||||
<field fieldName="version" version="true" type="int" />
|
||||
</doctrine-mongo-mapping>
|
||||
|
||||
By default, Doctrine ODM updates :ref:`embed-many <embed_many>` and
|
||||
:ref:`reference-many <reference_many>` collections in separate write operations,
|
||||
which do not bump the document version. Users employing document versioning are
|
||||
encouraged to use the :ref:`atomicSet <atomic_set>` or
|
||||
:ref:`atomicSetArray <atomic_set_array>` strategies for such collections, which
|
||||
will ensure that collections are updated in the same write operation as the
|
||||
versioned parent document.
|
||||
@@ -0,0 +1,211 @@
|
||||
YAML Mapping
|
||||
============
|
||||
|
||||
The YAML mapping driver enables you to provide the ODM metadata in
|
||||
form of YAML documents.
|
||||
|
||||
The YAML mapping document of a class is loaded on-demand the first
|
||||
time it is requested and subsequently stored in the metadata cache.
|
||||
In order to work, this requires certain conventions:
|
||||
|
||||
-
|
||||
Each document/mapped superclass must get its own dedicated YAML
|
||||
mapping document.
|
||||
-
|
||||
The name of the mapping document must consist of the fully
|
||||
qualified name of the class, where namespace separators are
|
||||
replaced by dots (.).
|
||||
-
|
||||
All mapping documents should get the extension ".dcm.yml" to
|
||||
identify it as a Doctrine mapping file. This is more of a
|
||||
convention and you are not forced to do this. You can change the
|
||||
file extension easily enough.
|
||||
|
||||
-
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$driver->setFileExtension('.yml');
|
||||
|
||||
It is recommended to put all YAML mapping documents in a single
|
||||
folder but you can spread the documents over several folders if you
|
||||
want to. In order to tell the YamlDriver where to look for your
|
||||
mapping documents, supply an array of paths as the first argument
|
||||
of the constructor, like this:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
// $config instanceof Doctrine\ODM\MongoDB\Configuration
|
||||
$driver = new YamlDriver(array('/path/to/files'));
|
||||
$config->setMetadataDriverImpl($driver);
|
||||
|
||||
Simplified YAML Driver
|
||||
~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
The Symfony project sponsored a driver that simplifies usage of the YAML Driver.
|
||||
The changes between the original driver are:
|
||||
|
||||
1. File Extension is .mongodb-odm.yml
|
||||
2. Filenames are shortened, "MyProject\\Documents\\User" will become User.mongodb-odm.yml
|
||||
3. You can add a global file and add multiple documents in this file.
|
||||
|
||||
Configuration of this client works a little bit different:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
$namespaces = array(
|
||||
'/path/to/files1' => 'MyProject\Documents',
|
||||
'/path/to/files2' => 'OtherProject\Documents'
|
||||
);
|
||||
$driver = new \Doctrine\ODM\MongoDB\Mapping\Driver\SimplifiedYamlDriver($namespaces);
|
||||
$driver->setGlobalBasename('global'); // global.mongodb-odm.yml
|
||||
|
||||
Example
|
||||
-------
|
||||
|
||||
As a quick start, here is a small example document that makes use
|
||||
of several common elements:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
# Documents.User.dcm.yml
|
||||
|
||||
Documents\User:
|
||||
db: documents
|
||||
collection: user
|
||||
fields:
|
||||
id:
|
||||
id: true
|
||||
username:
|
||||
name: login
|
||||
type: string
|
||||
email:
|
||||
unique:
|
||||
order: desc
|
||||
createdAt:
|
||||
type: date
|
||||
indexes:
|
||||
index1:
|
||||
keys:
|
||||
username: desc
|
||||
options:
|
||||
unique: true
|
||||
dropDups: true
|
||||
safe: true
|
||||
embedOne:
|
||||
address:
|
||||
targetDocument: Documents\Address
|
||||
embedMany:
|
||||
phonenumbers:
|
||||
targetDocument: Documents\Phonenumber
|
||||
referenceOne:
|
||||
profile:
|
||||
targetDocument: Documents\Profile
|
||||
cascade: all
|
||||
account:
|
||||
targetDocument: Documents\Account
|
||||
cascade: all
|
||||
referenceMany:
|
||||
groups:
|
||||
targetDocument: Documents\Group
|
||||
cascade: all
|
||||
|
||||
# Alternative syntax for the exact same example
|
||||
# (allows custom key name for embedded document and reference).
|
||||
Documents\User:
|
||||
db: documents
|
||||
collection: user
|
||||
fields:
|
||||
id:
|
||||
id: true
|
||||
username:
|
||||
name: login
|
||||
type: string
|
||||
email:
|
||||
unique:
|
||||
order: desc
|
||||
createdAt:
|
||||
type: date
|
||||
address:
|
||||
embedded: true
|
||||
type: one
|
||||
targetDocument: Documents\Address
|
||||
phonenumbers:
|
||||
embedded: true
|
||||
type: many
|
||||
targetDocument: Documents\Phonenumber
|
||||
profile:
|
||||
reference: true
|
||||
type: one
|
||||
targetDocument: Documents\Profile
|
||||
cascade: all
|
||||
account:
|
||||
reference: true
|
||||
type: one
|
||||
targetDocument: Documents\Account
|
||||
cascade: all
|
||||
groups:
|
||||
reference: true
|
||||
type: many
|
||||
targetDocument: Documents\Group
|
||||
cascade: all
|
||||
indexes:
|
||||
index1:
|
||||
keys:
|
||||
username: desc
|
||||
options:
|
||||
unique: true
|
||||
dropDups: true
|
||||
safe: true
|
||||
|
||||
Be aware that class-names specified in the YAML files should be fully qualified.
|
||||
|
||||
.. note::
|
||||
|
||||
The ``name`` property is an optional setting to change name of the field
|
||||
**in the database**. Specifying it is optional and defaults to the name
|
||||
of mapped field.
|
||||
|
||||
Reference
|
||||
---------
|
||||
|
||||
.. _yml_reference_lock:
|
||||
|
||||
Lock
|
||||
^^^^
|
||||
|
||||
The field with the ``lock`` property will be used to store lock information for :ref:`pessimistic locking <transactions_and_concurrency_pessimistic_locking>`.
|
||||
This is only compatible with the ``int`` field type, and cannot be combined with ``id: true``.
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
lock:
|
||||
type: int
|
||||
lock: true
|
||||
|
||||
.. _yml_reference_version:
|
||||
|
||||
Version
|
||||
^^^^^^^
|
||||
|
||||
The field with the ``version`` property will be used to store version information for :ref:`optimistic locking <transactions_and_concurrency_optimistic_locking>`.
|
||||
This is only compatible with ``int`` and ``date`` field types, and cannot be combined with ``id: true``.
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
version:
|
||||
type: int
|
||||
version: true
|
||||
|
||||
By default, Doctrine ODM updates :ref:`embed-many <embed_many>` and
|
||||
:ref:`reference-many <reference_many>` collections in separate write operations,
|
||||
which do not bump the document version. Users employing document versioning are
|
||||
encouraged to use the :ref:`atomicSet <atomic_set>` or
|
||||
:ref:`atomicSetArray <atomic_set_array>` strategies for such collections, which
|
||||
will ensure that collections are updated in the same write operation as the
|
||||
versioned parent document.
|
||||
@@ -0,0 +1,301 @@
|
||||
Getting Started
|
||||
===============
|
||||
|
||||
Doctrine is a project that aims to handle the persistence of your
|
||||
domain model in a non-interfering way. Non-relational or no-sql
|
||||
databases like MongoDB give you flexibility of building data store
|
||||
around your object model and not vise versa. You can read more on the
|
||||
initial configuration and setup in :doc:`Introduction to MongoDB Object
|
||||
Document Mapper <../reference/introduction>`. This section will give you a basic
|
||||
overview of what could be accomplished using Doctrine MongoDB ODM.
|
||||
|
||||
Example Model: Simple Blog
|
||||
--------------------------
|
||||
|
||||
To create the simplest example, let’s assume the following in a simple blog web application:
|
||||
|
||||
- Blog has a user.
|
||||
- Blog user can make blog posts
|
||||
|
||||
A first prototype
|
||||
-----------------
|
||||
|
||||
For the above mentioned example, something as simple as this could be modeled with plain PHP classes.
|
||||
First define the ``User`` document:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
namespace Documents;
|
||||
|
||||
class User
|
||||
{
|
||||
private $name;
|
||||
private $email;
|
||||
private $posts = array();
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
Now define the ``BlogPost`` document:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
namespace Documents;
|
||||
|
||||
class BlogPost
|
||||
{
|
||||
private $title;
|
||||
private $body;
|
||||
private $createdAt;
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
Persistent Models
|
||||
-----------------
|
||||
|
||||
To make the above classes persistent, all we need to do is provide Doctrine with some mapping
|
||||
information so that it knows how to consume the objects and persist them to the database.
|
||||
|
||||
You can provide your mapping information in Annotations, XML, or YAML:
|
||||
|
||||
.. configuration-block::
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
|
||||
|
||||
/** @ODM\Document */
|
||||
class User
|
||||
{
|
||||
/** @ODM\Id */
|
||||
private $id;
|
||||
|
||||
/** @ODM\Field(type="string") */
|
||||
private $name;
|
||||
|
||||
/** @ODM\Field(type="string") */
|
||||
private $email;
|
||||
|
||||
/** @ODM\ReferenceMany(targetDocument="BlogPost", cascade="all") */
|
||||
private $posts = array();
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
/** @ODM\Document */
|
||||
class BlogPost
|
||||
{
|
||||
/** @ODM\Id */
|
||||
private $id;
|
||||
|
||||
/** @ODM\Field(type="string") */
|
||||
private $title;
|
||||
|
||||
/** @ODM\Field(type="string") */
|
||||
private $body;
|
||||
|
||||
/** @ODM\Field(type="date") */
|
||||
private $createdAt;
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<doctrine-mongo-mapping xmlns="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping
|
||||
http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping.xsd">
|
||||
<document name="Documents\User">
|
||||
<field fieldName="id" id="true" />
|
||||
<field fieldName="name" type="string" />
|
||||
<field fieldName="email" type="string" />
|
||||
<reference-many fieldName="posts" targetDocument="Documents\BlogPost">
|
||||
<cascade>
|
||||
<all/>
|
||||
</cascade>
|
||||
</reference-many>
|
||||
</document>
|
||||
</doctrine-mongo-mapping>
|
||||
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<doctrine-mongo-mapping xmlns="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping
|
||||
http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping.xsd">
|
||||
<document name="Documents\BlogPost">
|
||||
<field fieldName="id" id="true" />
|
||||
<field fieldName="title" type="string" />
|
||||
<field fieldName="body" type="string" />
|
||||
<field fieldName="createdAt" type="date" />
|
||||
</document>
|
||||
</doctrine-mongo-mapping>
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
Documents\User:
|
||||
fields:
|
||||
id:
|
||||
type: id
|
||||
id: true
|
||||
name:
|
||||
type: string
|
||||
email:
|
||||
type: string
|
||||
referenceMany:
|
||||
posts:
|
||||
targetDocument: Documents\BlogPost
|
||||
cascade: all
|
||||
|
||||
Documents\BlogPost:
|
||||
fields:
|
||||
id:
|
||||
type: id
|
||||
id: true
|
||||
title:
|
||||
type: string
|
||||
body:
|
||||
type: string
|
||||
createdAt:
|
||||
type: date
|
||||
|
||||
That’s it, we have our models, and we can save and retrieve them. Now
|
||||
all we need to do is to properly instantiate the ``DocumentManager``
|
||||
instance. Read more about setting up the Doctrine MongoDB ODM in the
|
||||
:doc:`Introduction to MongoDB Object Document Mapper <../reference/introduction>`:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
use Doctrine\MongoDB\Connection;
|
||||
use Doctrine\ODM\MongoDB\Configuration;
|
||||
use Doctrine\ODM\MongoDB\DocumentManager;
|
||||
use Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver;
|
||||
|
||||
AnnotationDriver::registerAnnotationClasses();
|
||||
|
||||
$config = new Configuration();
|
||||
$config->setProxyDir('/path/to/generate/proxies');
|
||||
$config->setProxyNamespace('Proxies');
|
||||
$config->setHydratorDir('/path/to/generate/hydrators');
|
||||
$config->setHydratorNamespace('Hydrators');
|
||||
$config->setMetadataDriverImpl(AnnotationDriver::create('/path/to/document/classes'));
|
||||
|
||||
$dm = DocumentManager::create(new Connection(), $config);
|
||||
|
||||
Usage
|
||||
-----
|
||||
|
||||
Here is how you would use your models now:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
// ...
|
||||
|
||||
// create user
|
||||
$user = new User();
|
||||
$user->setName('Bulat S.');
|
||||
$user->setEmail('email@example.com');
|
||||
|
||||
// tell Doctrine 2 to save $user on the next flush()
|
||||
$dm->persist($user);
|
||||
|
||||
// create blog post
|
||||
$post = new BlogPost();
|
||||
$post->setTitle('My First Blog Post');
|
||||
$post->setBody('MongoDB + Doctrine 2 ODM = awesomeness!');
|
||||
$post->setCreatedAt(new DateTime());
|
||||
|
||||
$user->addPost($post);
|
||||
|
||||
// store everything to MongoDB
|
||||
$dm->flush();
|
||||
|
||||
.. note::
|
||||
|
||||
Note that you do not need to explicitly call persist on the ``$post`` because the operation
|
||||
will cascade on to the reference automatically.
|
||||
|
||||
Now if you did everything correctly, you should have those two objects
|
||||
stored in MongoDB in correct collections and databases. You can use the
|
||||
`php-mongodb-admin project, hosted on github`_ to look at your
|
||||
``BlogPost`` collection, where you will see only one document:
|
||||
|
||||
::
|
||||
|
||||
Array
|
||||
(
|
||||
[_id] => 4bec5869fdc212081d000000
|
||||
[title] => My First Blog Post
|
||||
[body] => MongoDB + Doctrine 2 ODM = awesomeness!
|
||||
[createdAt] => MongoDate Object
|
||||
(
|
||||
[sec] => 1273723200
|
||||
[usec] => 0
|
||||
)
|
||||
)
|
||||
|
||||
And the ``User`` collection would consist of the following:
|
||||
|
||||
::
|
||||
|
||||
Array
|
||||
(
|
||||
[_id] => 4bec5869fdc212081d010000
|
||||
[name] => Bulat S.
|
||||
[email] => email@example.com
|
||||
[posts] => Array
|
||||
(
|
||||
[0] => Array
|
||||
(
|
||||
[$ref] => blog_posts
|
||||
[$id] => 4bec5869fdc212081d000000
|
||||
[$db] => test_database
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
You can retrieve the user later by its identifier:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
// ...
|
||||
|
||||
$userId = '....';
|
||||
$user = $dm->find('User', $userId);
|
||||
|
||||
Or you can find the user by name even:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$user = $dm->getRepository('User')->findOneByName('Bulat S.');
|
||||
|
||||
If you want to iterate over the posts the user references it is as easy as the following:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
$posts = $dm->getPosts();
|
||||
foreach ($posts as $post) {
|
||||
}
|
||||
|
||||
You will notice that working with objects is nothing magical and you only have access to the properties,
|
||||
getters and setters that you have defined yourself so the semantics are very clear. You can continue
|
||||
reading about the MongoDB in the :doc:`Introduction to MongoDB Object Document Mapper <../reference/introduction>`.
|
||||
|
||||
.. _php-mongodb-admin project, hosted on github: http://github.com/jwage/php-mongodb-admin
|
||||
|
After Width: | Height: | Size: 673 B |
|
After Width: | Height: | Size: 5.8 KiB |
@@ -0,0 +1,639 @@
|
||||
/*
|
||||
* basic.css
|
||||
* ~~~~~~~~~
|
||||
*
|
||||
* Sphinx stylesheet -- basic theme.
|
||||
*
|
||||
* :copyright: Copyright 2007-2017 by the Sphinx team, see AUTHORS.
|
||||
* :license: BSD, see LICENSE for details.
|
||||
*
|
||||
*/
|
||||
|
||||
/* -- main layout ----------------------------------------------------------- */
|
||||
|
||||
div.clearer {
|
||||
clear: both;
|
||||
}
|
||||
|
||||
/* -- relbar ---------------------------------------------------------------- */
|
||||
|
||||
div.related {
|
||||
width: 100%;
|
||||
font-size: 90%;
|
||||
}
|
||||
|
||||
div.related h3 {
|
||||
display: none;
|
||||
}
|
||||
|
||||
div.related ul {
|
||||
margin: 0;
|
||||
padding: 0 0 0 10px;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
div.related li {
|
||||
display: inline;
|
||||
}
|
||||
|
||||
div.related li.right {
|
||||
float: right;
|
||||
margin-right: 5px;
|
||||
}
|
||||
|
||||
/* -- sidebar --------------------------------------------------------------- */
|
||||
|
||||
div.sphinxsidebarwrapper {
|
||||
padding: 10px 5px 0 10px;
|
||||
}
|
||||
|
||||
div.sphinxsidebar {
|
||||
float: left;
|
||||
width: 230px;
|
||||
margin-left: -100%;
|
||||
font-size: 90%;
|
||||
word-wrap: break-word;
|
||||
overflow-wrap : break-word;
|
||||
}
|
||||
|
||||
div.sphinxsidebar ul {
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
div.sphinxsidebar ul ul,
|
||||
div.sphinxsidebar ul.want-points {
|
||||
margin-left: 20px;
|
||||
list-style: square;
|
||||
}
|
||||
|
||||
div.sphinxsidebar ul ul {
|
||||
margin-top: 0;
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
div.sphinxsidebar form {
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
div.sphinxsidebar input {
|
||||
border: 1px solid #98dbcc;
|
||||
font-family: sans-serif;
|
||||
font-size: 1em;
|
||||
}
|
||||
|
||||
div.sphinxsidebar #searchbox input[type="text"] {
|
||||
width: 170px;
|
||||
}
|
||||
|
||||
img {
|
||||
border: 0;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
/* -- search page ----------------------------------------------------------- */
|
||||
|
||||
ul.search {
|
||||
margin: 10px 0 0 20px;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
ul.search li {
|
||||
padding: 5px 0 5px 20px;
|
||||
background-image: url(file.png);
|
||||
background-repeat: no-repeat;
|
||||
background-position: 0 7px;
|
||||
}
|
||||
|
||||
ul.search li a {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
ul.search li div.context {
|
||||
color: #888;
|
||||
margin: 2px 0 0 30px;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
ul.keywordmatches li.goodmatch a {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
/* -- index page ------------------------------------------------------------ */
|
||||
|
||||
table.contentstable {
|
||||
width: 90%;
|
||||
margin-left: auto;
|
||||
margin-right: auto;
|
||||
}
|
||||
|
||||
table.contentstable p.biglink {
|
||||
line-height: 150%;
|
||||
}
|
||||
|
||||
a.biglink {
|
||||
font-size: 1.3em;
|
||||
}
|
||||
|
||||
span.linkdescr {
|
||||
font-style: italic;
|
||||
padding-top: 5px;
|
||||
font-size: 90%;
|
||||
}
|
||||
|
||||
/* -- general index --------------------------------------------------------- */
|
||||
|
||||
table.indextable {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
table.indextable td {
|
||||
text-align: left;
|
||||
vertical-align: top;
|
||||
}
|
||||
|
||||
table.indextable ul {
|
||||
margin-top: 0;
|
||||
margin-bottom: 0;
|
||||
list-style-type: none;
|
||||
}
|
||||
|
||||
table.indextable > tbody > tr > td > ul {
|
||||
padding-left: 0em;
|
||||
}
|
||||
|
||||
table.indextable tr.pcap {
|
||||
height: 10px;
|
||||
}
|
||||
|
||||
table.indextable tr.cap {
|
||||
margin-top: 10px;
|
||||
background-color: #f2f2f2;
|
||||
}
|
||||
|
||||
img.toggler {
|
||||
margin-right: 3px;
|
||||
margin-top: 3px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
div.modindex-jumpbox {
|
||||
border-top: 1px solid #ddd;
|
||||
border-bottom: 1px solid #ddd;
|
||||
margin: 1em 0 1em 0;
|
||||
padding: 0.4em;
|
||||
}
|
||||
|
||||
div.genindex-jumpbox {
|
||||
border-top: 1px solid #ddd;
|
||||
border-bottom: 1px solid #ddd;
|
||||
margin: 1em 0 1em 0;
|
||||
padding: 0.4em;
|
||||
}
|
||||
|
||||
/* -- domain module index --------------------------------------------------- */
|
||||
|
||||
table.modindextable td {
|
||||
padding: 2px;
|
||||
border-collapse: collapse;
|
||||
}
|
||||
|
||||
/* -- general body styles --------------------------------------------------- */
|
||||
|
||||
div.body p, div.body dd, div.body li, div.body blockquote {
|
||||
-moz-hyphens: auto;
|
||||
-ms-hyphens: auto;
|
||||
-webkit-hyphens: auto;
|
||||
hyphens: auto;
|
||||
}
|
||||
|
||||
a.headerlink {
|
||||
visibility: hidden;
|
||||
}
|
||||
|
||||
h1:hover > a.headerlink,
|
||||
h2:hover > a.headerlink,
|
||||
h3:hover > a.headerlink,
|
||||
h4:hover > a.headerlink,
|
||||
h5:hover > a.headerlink,
|
||||
h6:hover > a.headerlink,
|
||||
dt:hover > a.headerlink,
|
||||
caption:hover > a.headerlink,
|
||||
p.caption:hover > a.headerlink,
|
||||
div.code-block-caption:hover > a.headerlink {
|
||||
visibility: visible;
|
||||
}
|
||||
|
||||
div.body p.caption {
|
||||
text-align: inherit;
|
||||
}
|
||||
|
||||
div.body td {
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.first {
|
||||
margin-top: 0 !important;
|
||||
}
|
||||
|
||||
p.rubric {
|
||||
margin-top: 30px;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
img.align-left, .figure.align-left, object.align-left {
|
||||
clear: left;
|
||||
float: left;
|
||||
margin-right: 1em;
|
||||
}
|
||||
|
||||
img.align-right, .figure.align-right, object.align-right {
|
||||
clear: right;
|
||||
float: right;
|
||||
margin-left: 1em;
|
||||
}
|
||||
|
||||
img.align-center, .figure.align-center, object.align-center {
|
||||
display: block;
|
||||
margin-left: auto;
|
||||
margin-right: auto;
|
||||
}
|
||||
|
||||
.align-left {
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.align-center {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.align-right {
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
/* -- sidebars -------------------------------------------------------------- */
|
||||
|
||||
div.sidebar {
|
||||
margin: 0 0 0.5em 1em;
|
||||
border: 1px solid #ddb;
|
||||
padding: 7px 7px 0 7px;
|
||||
background-color: #ffe;
|
||||
width: 40%;
|
||||
float: right;
|
||||
}
|
||||
|
||||
p.sidebar-title {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
/* -- topics ---------------------------------------------------------------- */
|
||||
|
||||
div.topic {
|
||||
border: 1px solid #ccc;
|
||||
padding: 7px 7px 0 7px;
|
||||
margin: 10px 0 10px 0;
|
||||
}
|
||||
|
||||
p.topic-title {
|
||||
font-size: 1.1em;
|
||||
font-weight: bold;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
/* -- admonitions ----------------------------------------------------------- */
|
||||
|
||||
div.admonition {
|
||||
margin-top: 10px;
|
||||
margin-bottom: 10px;
|
||||
padding: 7px;
|
||||
}
|
||||
|
||||
div.admonition dt {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
div.admonition dl {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
p.admonition-title {
|
||||
margin: 0px 10px 5px 0px;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
div.body p.centered {
|
||||
text-align: center;
|
||||
margin-top: 25px;
|
||||
}
|
||||
|
||||
/* -- tables ---------------------------------------------------------------- */
|
||||
|
||||
table.docutils {
|
||||
border: 0;
|
||||
border-collapse: collapse;
|
||||
}
|
||||
|
||||
table caption span.caption-number {
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
table caption span.caption-text {
|
||||
}
|
||||
|
||||
table.docutils td, table.docutils th {
|
||||
padding: 1px 8px 1px 5px;
|
||||
border-top: 0;
|
||||
border-left: 0;
|
||||
border-right: 0;
|
||||
border-bottom: 1px solid #aaa;
|
||||
}
|
||||
|
||||
table.footnote td, table.footnote th {
|
||||
border: 0 !important;
|
||||
}
|
||||
|
||||
th {
|
||||
text-align: left;
|
||||
padding-right: 5px;
|
||||
}
|
||||
|
||||
table.citation {
|
||||
border-left: solid 1px gray;
|
||||
margin-left: 1px;
|
||||
}
|
||||
|
||||
table.citation td {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
/* -- figures --------------------------------------------------------------- */
|
||||
|
||||
div.figure {
|
||||
margin: 0.5em;
|
||||
padding: 0.5em;
|
||||
}
|
||||
|
||||
div.figure p.caption {
|
||||
padding: 0.3em;
|
||||
}
|
||||
|
||||
div.figure p.caption span.caption-number {
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
div.figure p.caption span.caption-text {
|
||||
}
|
||||
|
||||
/* -- field list styles ----------------------------------------------------- */
|
||||
|
||||
table.field-list td, table.field-list th {
|
||||
border: 0 !important;
|
||||
}
|
||||
|
||||
.field-list ul {
|
||||
margin: 0;
|
||||
padding-left: 1em;
|
||||
}
|
||||
|
||||
.field-list p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.field-name {
|
||||
-moz-hyphens: manual;
|
||||
-ms-hyphens: manual;
|
||||
-webkit-hyphens: manual;
|
||||
hyphens: manual;
|
||||
}
|
||||
|
||||
/* -- other body styles ----------------------------------------------------- */
|
||||
|
||||
ol.arabic {
|
||||
list-style: decimal;
|
||||
}
|
||||
|
||||
ol.loweralpha {
|
||||
list-style: lower-alpha;
|
||||
}
|
||||
|
||||
ol.upperalpha {
|
||||
list-style: upper-alpha;
|
||||
}
|
||||
|
||||
ol.lowerroman {
|
||||
list-style: lower-roman;
|
||||
}
|
||||
|
||||
ol.upperroman {
|
||||
list-style: upper-roman;
|
||||
}
|
||||
|
||||
dl {
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
|
||||
dd p {
|
||||
margin-top: 0px;
|
||||
}
|
||||
|
||||
dd ul, dd table {
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
dd {
|
||||
margin-top: 3px;
|
||||
margin-bottom: 10px;
|
||||
margin-left: 30px;
|
||||
}
|
||||
|
||||
dt:target, .highlighted {
|
||||
background-color: #fbe54e;
|
||||
}
|
||||
|
||||
dl.glossary dt {
|
||||
font-weight: bold;
|
||||
font-size: 1.1em;
|
||||
}
|
||||
|
||||
.optional {
|
||||
font-size: 1.3em;
|
||||
}
|
||||
|
||||
.sig-paren {
|
||||
font-size: larger;
|
||||
}
|
||||
|
||||
.versionmodified {
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.system-message {
|
||||
background-color: #fda;
|
||||
padding: 5px;
|
||||
border: 3px solid red;
|
||||
}
|
||||
|
||||
.footnote:target {
|
||||
background-color: #ffa;
|
||||
}
|
||||
|
||||
.line-block {
|
||||
display: block;
|
||||
margin-top: 1em;
|
||||
margin-bottom: 1em;
|
||||
}
|
||||
|
||||
.line-block .line-block {
|
||||
margin-top: 0;
|
||||
margin-bottom: 0;
|
||||
margin-left: 1.5em;
|
||||
}
|
||||
|
||||
.guilabel, .menuselection {
|
||||
font-family: sans-serif;
|
||||
}
|
||||
|
||||
.accelerator {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.classifier {
|
||||
font-style: oblique;
|
||||
}
|
||||
|
||||
abbr, acronym {
|
||||
border-bottom: dotted 1px;
|
||||
cursor: help;
|
||||
}
|
||||
|
||||
/* -- code displays --------------------------------------------------------- */
|
||||
|
||||
pre {
|
||||
overflow: auto;
|
||||
overflow-y: hidden; /* fixes display issues on Chrome browsers */
|
||||
}
|
||||
|
||||
span.pre {
|
||||
-moz-hyphens: none;
|
||||
-ms-hyphens: none;
|
||||
-webkit-hyphens: none;
|
||||
hyphens: none;
|
||||
}
|
||||
|
||||
td.linenos pre {
|
||||
padding: 5px 0px;
|
||||
border: 0;
|
||||
background-color: transparent;
|
||||
color: #aaa;
|
||||
}
|
||||
|
||||
table.highlighttable {
|
||||
margin-left: 0.5em;
|
||||
}
|
||||
|
||||
table.highlighttable td {
|
||||
padding: 0 0.5em 0 0.5em;
|
||||
}
|
||||
|
||||
div.code-block-caption {
|
||||
padding: 2px 5px;
|
||||
font-size: small;
|
||||
}
|
||||
|
||||
div.code-block-caption code {
|
||||
background-color: transparent;
|
||||
}
|
||||
|
||||
div.code-block-caption + div > div.highlight > pre {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
div.code-block-caption span.caption-number {
|
||||
padding: 0.1em 0.3em;
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
div.code-block-caption span.caption-text {
|
||||
}
|
||||
|
||||
div.literal-block-wrapper {
|
||||
padding: 1em 1em 0;
|
||||
}
|
||||
|
||||
div.literal-block-wrapper div.highlight {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
code.descname {
|
||||
background-color: transparent;
|
||||
font-weight: bold;
|
||||
font-size: 1.2em;
|
||||
}
|
||||
|
||||
code.descclassname {
|
||||
background-color: transparent;
|
||||
}
|
||||
|
||||
code.xref, a code {
|
||||
background-color: transparent;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
h1 code, h2 code, h3 code, h4 code, h5 code, h6 code {
|
||||
background-color: transparent;
|
||||
}
|
||||
|
||||
.viewcode-link {
|
||||
float: right;
|
||||
}
|
||||
|
||||
.viewcode-back {
|
||||
float: right;
|
||||
font-family: sans-serif;
|
||||
}
|
||||
|
||||
div.viewcode-block:target {
|
||||
margin: -1px -10px;
|
||||
padding: 0 10px;
|
||||
}
|
||||
|
||||
/* -- math display ---------------------------------------------------------- */
|
||||
|
||||
img.math {
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
div.body div.math p {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
span.eqno {
|
||||
float: right;
|
||||
}
|
||||
|
||||
span.eqno a.headerlink {
|
||||
position: relative;
|
||||
left: 0px;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
div.math:hover a.headerlink {
|
||||
visibility: visible;
|
||||
}
|
||||
|
||||
/* -- printout stylesheet --------------------------------------------------- */
|
||||
|
||||
@media print {
|
||||
div.document,
|
||||
div.documentwrapper,
|
||||
div.bodywrapper {
|
||||
margin: 0 !important;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
div.sphinxsidebar,
|
||||
div.related,
|
||||
div.footer,
|
||||
#top-link {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 3.6 KiB |
|
After Width: | Height: | Size: 108 B |
|
After Width: | Height: | Size: 8.6 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 105 B |
|
After Width: | Height: | Size: 180 B |
|
After Width: | Height: | Size: 2.1 KiB |
|
After Width: | Height: | Size: 756 B |
|
After Width: | Height: | Size: 829 B |
|
After Width: | Height: | Size: 641 B |
@@ -0,0 +1,97 @@
|
||||
div.configuration-block ul.simple
|
||||
{
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
margin-left: 30px;
|
||||
}
|
||||
|
||||
div.configuration-block ul.simple li
|
||||
{
|
||||
margin: 0 !important;
|
||||
margin-right: 5px !important;
|
||||
display: inline;
|
||||
margin-left: 10px;
|
||||
padding: 10px;
|
||||
}
|
||||
|
||||
div.configuration-block em
|
||||
{
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
div.configuration-block li
|
||||
{
|
||||
padding: 5px;
|
||||
}
|
||||
|
||||
div.configuration-block em
|
||||
{
|
||||
font-style: normal;
|
||||
font-size: 90%;
|
||||
}
|
||||
|
||||
div.jsactive
|
||||
{
|
||||
position: relative;
|
||||
}
|
||||
|
||||
div.jsactive ul
|
||||
{
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
div.jsactive li
|
||||
{
|
||||
float: left;
|
||||
list-style: none;
|
||||
margin-left: 0;
|
||||
-moz-border-radius: 5px; -webkit-border-radius: 5px; border-radius: 5px;
|
||||
background-color: #ddd;
|
||||
margin-right: 5px;
|
||||
}
|
||||
|
||||
div.jsactive .selected
|
||||
{
|
||||
background-color: #000;
|
||||
}
|
||||
|
||||
div.jsactive .selected a
|
||||
{
|
||||
color: #fff;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
div.jsactive .selected a:hover
|
||||
{
|
||||
color: #fff;
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
div.jsactive a
|
||||
{
|
||||
color: #000;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
div.jsactive a:hover
|
||||
{
|
||||
color: #000;
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
div.jsactive div
|
||||
{
|
||||
position: absolute;
|
||||
top: 30px;
|
||||
left: 0;
|
||||
}
|
||||
|
||||
div.jsactive div div
|
||||
{
|
||||
position: static;
|
||||
}
|
||||
|
||||
div.jsactive pre
|
||||
{
|
||||
margin: 0;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
$(document).ready(function(){
|
||||
$('div.configuration-block [class^=highlight-]').hide();
|
||||
$('div.configuration-block [class^=highlight-]').width($('div.configuration-block').width());
|
||||
|
||||
$('div.configuration-block').addClass('jsactive');
|
||||
$('div.configuration-block').addClass('clearfix');
|
||||
|
||||
$('div.configuration-block').each(function (){
|
||||
var el = $('[class^=highlight-]:first', $(this));
|
||||
el.show();
|
||||
el.parents('ul').height(el.height() + 40);
|
||||
});
|
||||
|
||||
// Global
|
||||
$('div.configuration-block li').each(function(){
|
||||
var str = $(':first', $(this)).html();
|
||||
$(':first ', $(this)).html('');
|
||||
$(':first ', $(this)).append('<a href="#">' + str + '</a>')
|
||||
$(':first', $(this)).bind('click', function(){
|
||||
$('[class^=highlight-]', $(this).parents('ul')).hide();
|
||||
$('li', $(this).parents('ul')).removeClass('selected');
|
||||
$(this).parent().addClass('selected');
|
||||
|
||||
var block = $('[class^=highlight-]', $(this).parent('li'));
|
||||
block.show();
|
||||
block.parents('ul').height(block.height() + 40);
|
||||
return false;
|
||||
});
|
||||
});
|
||||
|
||||
$('div.configuration-block').each(function (){
|
||||
$('li:first', $(this)).addClass('selected');
|
||||
});
|
||||
});
|
||||
|
After Width: | Height: | Size: 426 B |
@@ -0,0 +1,287 @@
|
||||
/*
|
||||
* doctools.js
|
||||
* ~~~~~~~~~~~
|
||||
*
|
||||
* Sphinx JavaScript utilities for all documentation.
|
||||
*
|
||||
* :copyright: Copyright 2007-2017 by the Sphinx team, see AUTHORS.
|
||||
* :license: BSD, see LICENSE for details.
|
||||
*
|
||||
*/
|
||||
|
||||
/**
|
||||
* select a different prefix for underscore
|
||||
*/
|
||||
$u = _.noConflict();
|
||||
|
||||
/**
|
||||
* make the code below compatible with browsers without
|
||||
* an installed firebug like debugger
|
||||
if (!window.console || !console.firebug) {
|
||||
var names = ["log", "debug", "info", "warn", "error", "assert", "dir",
|
||||
"dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace",
|
||||
"profile", "profileEnd"];
|
||||
window.console = {};
|
||||
for (var i = 0; i < names.length; ++i)
|
||||
window.console[names[i]] = function() {};
|
||||
}
|
||||
*/
|
||||
|
||||
/**
|
||||
* small helper function to urldecode strings
|
||||
*/
|
||||
jQuery.urldecode = function(x) {
|
||||
return decodeURIComponent(x).replace(/\+/g, ' ');
|
||||
};
|
||||
|
||||
/**
|
||||
* small helper function to urlencode strings
|
||||
*/
|
||||
jQuery.urlencode = encodeURIComponent;
|
||||
|
||||
/**
|
||||
* This function returns the parsed url parameters of the
|
||||
* current request. Multiple values per key are supported,
|
||||
* it will always return arrays of strings for the value parts.
|
||||
*/
|
||||
jQuery.getQueryParameters = function(s) {
|
||||
if (typeof s == 'undefined')
|
||||
s = document.location.search;
|
||||
var parts = s.substr(s.indexOf('?') + 1).split('&');
|
||||
var result = {};
|
||||
for (var i = 0; i < parts.length; i++) {
|
||||
var tmp = parts[i].split('=', 2);
|
||||
var key = jQuery.urldecode(tmp[0]);
|
||||
var value = jQuery.urldecode(tmp[1]);
|
||||
if (key in result)
|
||||
result[key].push(value);
|
||||
else
|
||||
result[key] = [value];
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
/**
|
||||
* highlight a given string on a jquery object by wrapping it in
|
||||
* span elements with the given class name.
|
||||
*/
|
||||
jQuery.fn.highlightText = function(text, className) {
|
||||
function highlight(node) {
|
||||
if (node.nodeType == 3) {
|
||||
var val = node.nodeValue;
|
||||
var pos = val.toLowerCase().indexOf(text);
|
||||
if (pos >= 0 && !jQuery(node.parentNode).hasClass(className)) {
|
||||
var span = document.createElement("span");
|
||||
span.className = className;
|
||||
span.appendChild(document.createTextNode(val.substr(pos, text.length)));
|
||||
node.parentNode.insertBefore(span, node.parentNode.insertBefore(
|
||||
document.createTextNode(val.substr(pos + text.length)),
|
||||
node.nextSibling));
|
||||
node.nodeValue = val.substr(0, pos);
|
||||
}
|
||||
}
|
||||
else if (!jQuery(node).is("button, select, textarea")) {
|
||||
jQuery.each(node.childNodes, function() {
|
||||
highlight(this);
|
||||
});
|
||||
}
|
||||
}
|
||||
return this.each(function() {
|
||||
highlight(this);
|
||||
});
|
||||
};
|
||||
|
||||
/*
|
||||
* backward compatibility for jQuery.browser
|
||||
* This will be supported until firefox bug is fixed.
|
||||
*/
|
||||
if (!jQuery.browser) {
|
||||
jQuery.uaMatch = function(ua) {
|
||||
ua = ua.toLowerCase();
|
||||
|
||||
var match = /(chrome)[ \/]([\w.]+)/.exec(ua) ||
|
||||
/(webkit)[ \/]([\w.]+)/.exec(ua) ||
|
||||
/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(ua) ||
|
||||
/(msie) ([\w.]+)/.exec(ua) ||
|
||||
ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua) ||
|
||||
[];
|
||||
|
||||
return {
|
||||
browser: match[ 1 ] || "",
|
||||
version: match[ 2 ] || "0"
|
||||
};
|
||||
};
|
||||
jQuery.browser = {};
|
||||
jQuery.browser[jQuery.uaMatch(navigator.userAgent).browser] = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Small JavaScript module for the documentation.
|
||||
*/
|
||||
var Documentation = {
|
||||
|
||||
init : function() {
|
||||
this.fixFirefoxAnchorBug();
|
||||
this.highlightSearchWords();
|
||||
this.initIndexTable();
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* i18n support
|
||||
*/
|
||||
TRANSLATIONS : {},
|
||||
PLURAL_EXPR : function(n) { return n == 1 ? 0 : 1; },
|
||||
LOCALE : 'unknown',
|
||||
|
||||
// gettext and ngettext don't access this so that the functions
|
||||
// can safely bound to a different name (_ = Documentation.gettext)
|
||||
gettext : function(string) {
|
||||
var translated = Documentation.TRANSLATIONS[string];
|
||||
if (typeof translated == 'undefined')
|
||||
return string;
|
||||
return (typeof translated == 'string') ? translated : translated[0];
|
||||
},
|
||||
|
||||
ngettext : function(singular, plural, n) {
|
||||
var translated = Documentation.TRANSLATIONS[singular];
|
||||
if (typeof translated == 'undefined')
|
||||
return (n == 1) ? singular : plural;
|
||||
return translated[Documentation.PLURALEXPR(n)];
|
||||
},
|
||||
|
||||
addTranslations : function(catalog) {
|
||||
for (var key in catalog.messages)
|
||||
this.TRANSLATIONS[key] = catalog.messages[key];
|
||||
this.PLURAL_EXPR = new Function('n', 'return +(' + catalog.plural_expr + ')');
|
||||
this.LOCALE = catalog.locale;
|
||||
},
|
||||
|
||||
/**
|
||||
* add context elements like header anchor links
|
||||
*/
|
||||
addContextElements : function() {
|
||||
$('div[id] > :header:first').each(function() {
|
||||
$('<a class="headerlink">\u00B6</a>').
|
||||
attr('href', '#' + this.id).
|
||||
attr('title', _('Permalink to this headline')).
|
||||
appendTo(this);
|
||||
});
|
||||
$('dt[id]').each(function() {
|
||||
$('<a class="headerlink">\u00B6</a>').
|
||||
attr('href', '#' + this.id).
|
||||
attr('title', _('Permalink to this definition')).
|
||||
appendTo(this);
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* workaround a firefox stupidity
|
||||
* see: https://bugzilla.mozilla.org/show_bug.cgi?id=645075
|
||||
*/
|
||||
fixFirefoxAnchorBug : function() {
|
||||
if (document.location.hash)
|
||||
window.setTimeout(function() {
|
||||
document.location.href += '';
|
||||
}, 10);
|
||||
},
|
||||
|
||||
/**
|
||||
* highlight the search words provided in the url in the text
|
||||
*/
|
||||
highlightSearchWords : function() {
|
||||
var params = $.getQueryParameters();
|
||||
var terms = (params.highlight) ? params.highlight[0].split(/\s+/) : [];
|
||||
if (terms.length) {
|
||||
var body = $('div.body');
|
||||
if (!body.length) {
|
||||
body = $('body');
|
||||
}
|
||||
window.setTimeout(function() {
|
||||
$.each(terms, function() {
|
||||
body.highlightText(this.toLowerCase(), 'highlighted');
|
||||
});
|
||||
}, 10);
|
||||
$('<p class="highlight-link"><a href="javascript:Documentation.' +
|
||||
'hideSearchWords()">' + _('Hide Search Matches') + '</a></p>')
|
||||
.appendTo($('#searchbox'));
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* init the domain index toggle buttons
|
||||
*/
|
||||
initIndexTable : function() {
|
||||
var togglers = $('img.toggler').click(function() {
|
||||
var src = $(this).attr('src');
|
||||
var idnum = $(this).attr('id').substr(7);
|
||||
$('tr.cg-' + idnum).toggle();
|
||||
if (src.substr(-9) == 'minus.png')
|
||||
$(this).attr('src', src.substr(0, src.length-9) + 'plus.png');
|
||||
else
|
||||
$(this).attr('src', src.substr(0, src.length-8) + 'minus.png');
|
||||
}).css('display', '');
|
||||
if (DOCUMENTATION_OPTIONS.COLLAPSE_INDEX) {
|
||||
togglers.click();
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* helper function to hide the search marks again
|
||||
*/
|
||||
hideSearchWords : function() {
|
||||
$('#searchbox .highlight-link').fadeOut(300);
|
||||
$('span.highlighted').removeClass('highlighted');
|
||||
},
|
||||
|
||||
/**
|
||||
* make the url absolute
|
||||
*/
|
||||
makeURL : function(relativeURL) {
|
||||
return DOCUMENTATION_OPTIONS.URL_ROOT + '/' + relativeURL;
|
||||
},
|
||||
|
||||
/**
|
||||
* get the current relative url
|
||||
*/
|
||||
getCurrentURL : function() {
|
||||
var path = document.location.pathname;
|
||||
var parts = path.split(/\//);
|
||||
$.each(DOCUMENTATION_OPTIONS.URL_ROOT.split(/\//), function() {
|
||||
if (this == '..')
|
||||
parts.pop();
|
||||
});
|
||||
var url = parts.join('/');
|
||||
return path.substring(url.lastIndexOf('/') + 1, path.length - 1);
|
||||
},
|
||||
|
||||
initOnKeyListeners: function() {
|
||||
$(document).keyup(function(event) {
|
||||
var activeElementType = document.activeElement.tagName;
|
||||
// don't navigate when in search box or textarea
|
||||
if (activeElementType !== 'TEXTAREA' && activeElementType !== 'INPUT' && activeElementType !== 'SELECT') {
|
||||
switch (event.keyCode) {
|
||||
case 37: // left
|
||||
var prevHref = $('link[rel="prev"]').prop('href');
|
||||
if (prevHref) {
|
||||
window.location.href = prevHref;
|
||||
return false;
|
||||
}
|
||||
case 39: // right
|
||||
var nextHref = $('link[rel="next"]').prop('href');
|
||||
if (nextHref) {
|
||||
window.location.href = nextHref;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// quick alias for translations
|
||||
_ = Documentation.gettext;
|
||||
|
||||
$(document).ready(function() {
|
||||
Documentation.init();
|
||||
});
|
||||
|
After Width: | Height: | Size: 222 B |
|
After Width: | Height: | Size: 202 B |
|
After Width: | Height: | Size: 286 B |
@@ -0,0 +1,485 @@
|
||||
.clr { clear:both; }
|
||||
.cls{zoom:1;}
|
||||
.cls:after{content:".";display:block;height:0;clear:both;visibility:hidden;}
|
||||
.clr15 { height:15px; clear:both; }
|
||||
.clr20 { height:20px; clear:both; }
|
||||
|
||||
/*fonts.css*/
|
||||
body { font:13px/1.231 "Lucida Grande",verdana,arial,helvetica,clean,sans-serif;*font-size:small;*font:x-small;}table {font-size:inherit;font:100%;}pre,code,kbd,samp,tt{font-family:monospace;*font-size:108%;line-height:100%;}
|
||||
body { background: #010410 url(bg-gradient.jpg) repeat-x top left; }
|
||||
|
||||
button, label { cursor:default; cursor:pointer; zoom:1; display:block; }
|
||||
/* for images */
|
||||
.left { float:left; margin:5px 20px 5px 0; }
|
||||
.right{ float:right; margin:5px 0 5px 20px; }
|
||||
|
||||
em { font-weight:bold !important; }
|
||||
|
||||
a:link, a:visited, a:active { text-decoration:none; color:#3370C9; outline:none; border:0; }
|
||||
a:hover { color: #00508c; text-decoration:underline; border:0; }
|
||||
|
||||
/* selection color */
|
||||
::-moz-selection{ background: #2E6BC8; color: #fff; }
|
||||
::selection { background: #2E6BC8; color: #fff; }
|
||||
|
||||
/* layout */
|
||||
#wrapper { width: 96%; min-width: 1000px; max-width: 1150px; margin-left: auto; margin-right: auto; position: relative; }
|
||||
#header { position:relative; background: transparent url(arrows.jpg) no-repeat top right;}
|
||||
#header h1#h1title { margin: 0; padding: 0; color: #fff; position: absolute; top: 50px; right: 20px; font-weight:bold; font-size:153.9%; text-shadow: #4E89D5 1px 1px 1px; }
|
||||
#header h1#h1title a { color: #fff; }
|
||||
|
||||
#logo a{ width:427px; height:88px; background:transparent url(logo.jpg) no-repeat top left; display:block; overflow:hidden; text-indent:-999em; }
|
||||
|
||||
#nav { text-align:right; position:relative; background:#2e6bc8 url(ur-corner.gif) no-repeat top right;}
|
||||
#nav .tl { background:transparent url(ul-corner.jpg) no-repeat top left; text-align:right; }
|
||||
#nav .tl a { text-decoration:none; }
|
||||
#nav ul { padding: 0; margin: 0; padding-top:10px; float:left; padding-bottom:10px; margin-left:15px; }
|
||||
#nav ul li { padding: 0; margin: 0; display:inline; font:bold 108% "Helvetica Neue", arial, sans-serif; line-height:131%; }
|
||||
#nav ul li a:link,
|
||||
#nav ul li a:visited { color:#fff; padding:7px 10px 10px; text-shadow: #000 0px 0px 3px; }
|
||||
#nav ul li a:hover { border-top: 4px solid #fff; text-shadow: #fff 0px 0px 3px; }
|
||||
#nav ul li a.current { border-top: 4px solid #fff; }
|
||||
|
||||
/* Content */
|
||||
|
||||
#content { width: 100%; margin-left: auto; margin-right: auto; position:relative; background:#fff; padding:30px 0 0; color: #495a7e; font:normal 100% "Lucida Grande", verdana, sans-serif; }
|
||||
#content h1 { margin:10px 0 20px 30px; font-weight:bold; font-size:153.9%; }
|
||||
#content h2 { margin:25px 0 15px 30px; font-weight:bold; font-size:140.0%; }
|
||||
#content h3 { margin:10px 0 20px 30px; font-weight:bold; font-size:130.0%; }
|
||||
#content h4 { margin:10px 0 20px 30px; font-weight:bold; font-size:120.0%; }
|
||||
#content h5 { margin:10px 0 20px 30px; font-weight:bold; font-size:110.0%; }
|
||||
#content ul li, #content ol li { margin:10px 0 0 30px; }
|
||||
#content ul, #content ol { margin-bottom: 10px; }
|
||||
#content p { margin:0 30px 15px 30px; font-size:93%; line-height:182%; }
|
||||
#content dl { margin:0 30px 15px 30px; }
|
||||
|
||||
#content .section a {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
/* Blue Sidebar Box */
|
||||
#sidebar { margin-left: 30px; margin-bottom: 10px; }
|
||||
#sidebar, .blue_box { color: white; margin-right: 30px; width:262px; float:right; }
|
||||
#sidebar, .blue_box { background: #0d418f; }
|
||||
#sidebar a, .blue_box a { color: #fff; }
|
||||
#sidebar .bd, .blue_box .bd { min-height: 300px; width:262px; background: transparent url(sidebox.jpg) no-repeat top right; padding:0 0 15px; }
|
||||
#sidebar .bd h2, .blue_box .bd h2 { margin:0; padding: 15px 20px; font: 138.5% "Lucida Grande", verdana, sans-serif; color:#fff; text-shadow: #000 0px 0px 3px; }
|
||||
#sidebar .bd h3, .blue_box .bd h3 { margin:0; padding: 15px 20px; font: 110.5% "Lucida Grande", verdana, sans-serif; color:#fff; text-shadow: #000 0px 0px 3px; }
|
||||
#sidebar .bd ul { margin-left: 5px; }
|
||||
#sidebar .bd ul li { list-style-type: none; margin: 0 0 0 16px; background: transparent url(bullet_white.gif) no-repeat center left; padding: 3px 15px 3px 20px; font: 93% "Lucida Grande", verdana, sans-serif; color:#fff; }
|
||||
#sidebar .bd ul.tree li { margin: 0 0 0 8px; }
|
||||
#sidebar .ft, .blue_box .ft { width:262px; height:5px; float:right; background: transparent url(sidebox-foot.jpg) no-repeat bottom center; }
|
||||
|
||||
/* Bottom Rounded Corner */
|
||||
|
||||
#bot-rcnr { width: 100%; margin-left: auto; margin-right: auto; height:14px; position:relative; background:#fff url(br-corner.gif) no-repeat bottom right; }
|
||||
#bot-rcnr .tl { width:12px; height:14px; background: transparent url(bl-corner.gif) no-repeat bottom left; }
|
||||
|
||||
/* Footer */
|
||||
|
||||
#footer p { padding:12px 0; text-align:center; font: 85% "Helvetica Neue", verdana, sans-serif; color: white; }
|
||||
#footer { text-align: center; margin-bottom: 20px; color: white; }
|
||||
|
||||
#content em { color:#F06419; font-style:normal; }
|
||||
|
||||
/* Misc. Classes */
|
||||
|
||||
.perfect-overflow {
|
||||
overflow/**/: auto;
|
||||
margin-right: 30px;
|
||||
margin-left: 30px;
|
||||
}
|
||||
|
||||
.perfect-overflow-right {
|
||||
overflow/**/: auto;
|
||||
margin-right: 30px;
|
||||
}
|
||||
|
||||
.form {
|
||||
padding-left: 30px;
|
||||
padding-right: 30px;
|
||||
}
|
||||
|
||||
.form fieldset legend {
|
||||
font-weight: bold;
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.form fieldset .form-row {
|
||||
padding: 10px;
|
||||
margin-top: 10px;
|
||||
margin-bottom: 10px;
|
||||
background: #f5f5f5;
|
||||
border-bottom: 1px solid #ccc;
|
||||
}
|
||||
|
||||
.form fieldset .form-row label {
|
||||
font-weight: bold;
|
||||
float: left;
|
||||
width: 200px;
|
||||
}
|
||||
|
||||
.form fieldset .form-row .form_error, .form fieldset .form-row .error_list {
|
||||
font-weight: bold;
|
||||
color: red;
|
||||
float: right;
|
||||
}
|
||||
|
||||
/* Top 1 and 2 Slots */
|
||||
/* Yellow and grey slots */
|
||||
|
||||
#top1 ul, #top2 ul {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
position: absolute;
|
||||
top: 8px;
|
||||
right: 20px;
|
||||
}
|
||||
|
||||
#top1 ul li, #top2 ul li {
|
||||
display: inline;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
margin-left: 15px;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
#top1 .content {
|
||||
padding: 8px;
|
||||
}
|
||||
|
||||
#top2 .content {
|
||||
padding: 3px;
|
||||
margin-left: 5px;
|
||||
}
|
||||
|
||||
#top1 {
|
||||
background: #F8FFBC;
|
||||
height: 35px;
|
||||
color: #333333;
|
||||
white-space: nowrap;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
#top2 {
|
||||
background: #e0e0e0;
|
||||
height: 25px;
|
||||
border-top: 1px solid #d0d0d0;
|
||||
border-bottom: 1px solid #d0d0d0;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
#top1_left {
|
||||
float: left;
|
||||
}
|
||||
|
||||
#top1_right {
|
||||
float: right;
|
||||
}
|
||||
|
||||
|
||||
/* Breadcrumbs */
|
||||
|
||||
#breadcrumb_trail {
|
||||
position: absolute;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
margin-left: 30px;
|
||||
padding-top: 6px;
|
||||
top: 0;
|
||||
}
|
||||
|
||||
#breadcrumb_trail li {
|
||||
list-style-type: none;
|
||||
margin: 0 !important;
|
||||
padding: 0 !important;
|
||||
text-indent: 20px;
|
||||
margin-right: 15px !important;
|
||||
float: left;
|
||||
background: url(../sf/sf_admin/images/next.png) no-repeat 0px -2px;
|
||||
line-height: 12px;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
#breadcrumb_trail li a {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
|
||||
/* Random Colors */
|
||||
|
||||
.yellow {
|
||||
background: #F8FFBC !important;
|
||||
}
|
||||
|
||||
.light-blue {
|
||||
background: #f4f9fc !important;
|
||||
}
|
||||
|
||||
.grey {
|
||||
background: #f5f5f5 !important;
|
||||
}
|
||||
|
||||
.green {
|
||||
background: #f4fff2 !important;
|
||||
}
|
||||
|
||||
.orange {
|
||||
background: #fdf9f1 !important;
|
||||
}
|
||||
|
||||
/* FEATURES */
|
||||
|
||||
/* Latest Build Link */
|
||||
|
||||
#latest-build {
|
||||
color: #3370C9;
|
||||
font: bold 93% "Lucida Grande", verdana, sans-serif;
|
||||
text-align: left;
|
||||
z-index: 20;
|
||||
}
|
||||
|
||||
#latest-build a {
|
||||
padding:10px 0 10px 25px;
|
||||
background: transparent url(disk.gif) no-repeat left .7em;
|
||||
}
|
||||
|
||||
/* Frequently Asked Questions */
|
||||
|
||||
#faq #index { margin-left: 30px; margin-right: 30px; }
|
||||
#faq #index li { margin-left: 65px; list-style-type: square; }
|
||||
#faq #list li { background: #F5F5F5; padding: 0px; margin-right: 30px; }
|
||||
|
||||
/* Change Log */
|
||||
|
||||
.changelog ul { margin-left: 14px; }
|
||||
.changelog ul li { list-style-type: square; line-height: 18px; }
|
||||
.changelog hr { border: 1px solid black; }
|
||||
|
||||
/* Donate */
|
||||
|
||||
#donate { margin-left: 30px; margin-right: 30px; padding: 10px; }
|
||||
.donate { text-align: center; padding-bottom: 10px; padding-top: 10px; }
|
||||
|
||||
/* Community */
|
||||
|
||||
.community-box {
|
||||
margin-left: 30px;
|
||||
margin-right: 30px;
|
||||
margin-bottom: 10px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
/* Comments */
|
||||
|
||||
div.comment_row .body { margin:12px 10px 10px; }
|
||||
div.comment_row h3 { margin:10px 10px 15px; }
|
||||
div.comment_row { margin-right: 30px; padding: 8px; margin: 0 30px 15px 30px; background: #f8ffbc; }
|
||||
div.comment_row ul { margin-left: 20px; }
|
||||
div.comment_row ul li { list-style-type: square; text-indent: 0; }
|
||||
|
||||
.stability_color_alpha {
|
||||
color: #990000;
|
||||
}
|
||||
|
||||
.stability_color_beta {
|
||||
color: #CC6600;
|
||||
}
|
||||
|
||||
.stability_color_rc {
|
||||
color: #00CC00;
|
||||
}
|
||||
|
||||
.stability_color_stable {
|
||||
color: #32CD32;
|
||||
}
|
||||
|
||||
.rounded_corners {
|
||||
-moz-border-radius : 5px;
|
||||
-webkit-border-radius: 5px;
|
||||
border-radius : 5px;
|
||||
}
|
||||
|
||||
ul.error_list {
|
||||
margin: 0;
|
||||
margin-bottom: 7px;
|
||||
color: #d33;
|
||||
border: none;
|
||||
background-color: #f33;
|
||||
}
|
||||
|
||||
ul.error_list li {
|
||||
padding: 4px;
|
||||
padding-left: 25px;
|
||||
list-style: none;
|
||||
color: #fff;
|
||||
background: url(../images/error.png) no-repeat 4px 4px;
|
||||
}
|
||||
|
||||
.notice {
|
||||
margin: 4px 0;
|
||||
padding: 4px 4px 4px 30px;
|
||||
background: url(../sf/sf_admin/images/tick.png) no-repeat 10px 4px;
|
||||
}
|
||||
|
||||
.error {
|
||||
margin: 4px 0;
|
||||
padding: 4px 4px 4px 30px;
|
||||
background: url(../sf/sf_admin/images/error.png) no-repeat 10px 4px;
|
||||
background-color: #f33;
|
||||
color: red;
|
||||
}
|
||||
|
||||
.notice, .error {
|
||||
background-color: #ffc;
|
||||
margin-bottom: 10px;
|
||||
border: 1px solid #ddd;
|
||||
font-weight: bold;
|
||||
margin-left: 30px;
|
||||
margin-right: 30px;
|
||||
overflow/**/: auto;
|
||||
}
|
||||
|
||||
.doctrine_table {
|
||||
margin-left: 30px;
|
||||
margin-right: 30px;
|
||||
border-collapse: collapse;
|
||||
width: 648px;
|
||||
margin-bottom: 10px;
|
||||
-moz-border-radius : 5px;
|
||||
-webkit-border-radius: 5px;
|
||||
border-radius : 5px;
|
||||
background-color: #2e6bc8;
|
||||
}
|
||||
|
||||
.doctrine_table tbody tr {
|
||||
border-bottom: 1px dotted #ccc;
|
||||
}
|
||||
|
||||
.doctrine_table tbody tr td {
|
||||
padding: 5px;
|
||||
background-color: #ffffff;
|
||||
}
|
||||
|
||||
.doctrine_table tbody tr th {
|
||||
background-color: white;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.doctrine_table tbody tr th label {
|
||||
margin-left: 5px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.doctrine_table tbody tr .title {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.doctrine_table tbody tr .author {
|
||||
white-space: nowrap;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.doctrine_table tbody tr .description {
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.doctrine_table tbody tr .download {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.doctrine_table thead tr th {
|
||||
padding: 8px;
|
||||
color: #ffffff;
|
||||
white-space: nowrap;
|
||||
text-align: left;
|
||||
background-color: inherit;
|
||||
}
|
||||
|
||||
.doctrine_table tfoot tr th {
|
||||
padding: 10px;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.checkbox_list {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.checkbox_list li {
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.checkbox_list li label {
|
||||
margin-right: 25px;
|
||||
float: left;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.checkbox_list li input {
|
||||
float: right;
|
||||
}
|
||||
|
||||
#help {
|
||||
clear: both;
|
||||
padding: 10px;
|
||||
background: #fdf9f1;
|
||||
overflow/**/: auto;
|
||||
margin-right: 30px;
|
||||
margin-left: 30px;
|
||||
color: #000;
|
||||
border: 1px solid #ccc;
|
||||
margin-top: 30px;
|
||||
-moz-border-radius : 5px;
|
||||
-webkit-border-radius: 5px;
|
||||
border-radius : 5px;
|
||||
background-color: #ffc;
|
||||
}
|
||||
|
||||
#help a {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
#help h3 {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
margin-bottom: 15px;
|
||||
font-size: 16px;
|
||||
color: #333;
|
||||
}
|
||||
|
||||
#projects_menu {
|
||||
background: #fff;
|
||||
height: 36px;
|
||||
border-bottom: 1px solid #ccc;
|
||||
}
|
||||
|
||||
#projects_menu ul li {
|
||||
float: left;
|
||||
margin-right: 10px;
|
||||
padding: 10px;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
#projects_menu ul li:hover {
|
||||
background: #333;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
input.download-button {
|
||||
padding: 10px;
|
||||
border: 1px solid #eee;
|
||||
background: #ffc;
|
||||
margin-left: 30px;
|
||||
-moz-border-radius : 5px;
|
||||
-webkit-border-radius: 5px;
|
||||
border-radius : 5px;
|
||||
font-weight: bold;
|
||||
font-size: 18px;
|
||||
color: #333;
|
||||
margin-top: 20px;
|
||||
}
|
||||
|
||||
input.download-button:hover {
|
||||
cursor: pointer;
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
After Width: | Height: | Size: 9.5 KiB |
|
After Width: | Height: | Size: 90 B |
|
After Width: | Height: | Size: 1.3 KiB |
|
After Width: | Height: | Size: 90 B |
@@ -0,0 +1,70 @@
|
||||
.highlight .hll { background-color: #ffffcc }
|
||||
.highlight { background: #000000; }
|
||||
.highlight .c { color: #B729D9; font-style: italic } /* Comment */
|
||||
.highlight .err { color: #a40000; border: 1px solid #ef2929 } /* Error */
|
||||
.highlight .g { color: #ffffff } /* Generic */
|
||||
.highlight .k { color: #FF8400 } /* Keyword */
|
||||
.highlight .l { color: #ffffff } /* Literal */
|
||||
.highlight .n { color: #ffffff } /* Name */
|
||||
.highlight .o { color: #E0882F } /* Operator */
|
||||
.highlight .x { color: #ffffff } /* Other */
|
||||
.highlight .p { color: #999999 } /* Punctuation */
|
||||
.highlight .cm { color: #B729D9; font-style: italic } /* Comment.Multiline */
|
||||
.highlight .cp { color: #a0a0a0 } /* Comment.Preproc */
|
||||
.highlight .c1 { color: #B729D9; font-style: italic } /* Comment.Single */
|
||||
.highlight .cs { color: #B729D9; font-style: italic } /* Comment.Special */
|
||||
.highlight .gd { color: #a40000 } /* Generic.Deleted */
|
||||
.highlight .ge { color: #ffffff; font-style: italic } /* Generic.Emph */
|
||||
.highlight .gr { color: #ef2929 } /* Generic.Error */
|
||||
.highlight .gh { color: #000080 } /* Generic.Heading */
|
||||
.highlight .gi { color: #00A000 } /* Generic.Inserted */
|
||||
.highlight .go { color: #808080 } /* Generic.Output */
|
||||
.highlight .gp { color: #745334 } /* Generic.Prompt */
|
||||
.highlight .gs { color: #ffffff; font-weight: bold } /* Generic.Strong */
|
||||
.highlight .gu { color: #800080; font-weight: bold } /* Generic.Subheading */
|
||||
.highlight .gt { color: #a40000; font-weight: bold } /* Generic.Traceback */
|
||||
.highlight .kc { color: #004461 } /* Keyword.Constant */
|
||||
.highlight .kd { color: #004461 } /* Keyword.Declaration */
|
||||
.highlight .kn { color: #004461 } /* Keyword.Namespace */
|
||||
.highlight .kp { color: #004461 } /* Keyword.Pseudo */
|
||||
.highlight .kr { color: #004461 } /* Keyword.Reserved */
|
||||
.highlight .kt { color: #004461 } /* Keyword.Type */
|
||||
.highlight .ld { color: #ffffff } /* Literal.Date */
|
||||
.highlight .m { color: #1299DA } /* Literal.Number */
|
||||
.highlight .s { color: #56DB3A } /* Literal.String */
|
||||
.highlight .na { color: #ffffff } /* Name.Attribute */
|
||||
.highlight .nb { color: #ffffff } /* Name.Builtin */
|
||||
.highlight .nc { color: #ffffff } /* Name.Class */
|
||||
.highlight .no { color: #ffffff } /* Name.Constant */
|
||||
.highlight .nd { color: #808080 } /* Name.Decorator */
|
||||
.highlight .ni { color: #ce5c00 } /* Name.Entity */
|
||||
.highlight .ne { color: #cc0000 } /* Name.Exception */
|
||||
.highlight .nf { color: #ffffff } /* Name.Function */
|
||||
.highlight .nl { color: #f57900 } /* Name.Label */
|
||||
.highlight .nn { color: #ffffff } /* Name.Namespace */
|
||||
.highlight .nx { color: #ffffff } /* Name.Other */
|
||||
.highlight .py { color: #ffffff } /* Name.Property */
|
||||
.highlight .nt { color: #cccccc } /* Name.Tag */
|
||||
.highlight .nv { color: #ffffff } /* Name.Variable */
|
||||
.highlight .ow { color: #E0882F } /* Operator.Word */
|
||||
.highlight .w { color: #f8f8f8; text-decoration: underline } /* Text.Whitespace */
|
||||
.highlight .mf { color: #1299DA } /* Literal.Number.Float */
|
||||
.highlight .mh { color: #1299DA } /* Literal.Number.Hex */
|
||||
.highlight .mi { color: #1299DA } /* Literal.Number.Integer */
|
||||
.highlight .mo { color: #1299DA } /* Literal.Number.Oct */
|
||||
.highlight .sb { color: #56DB3A } /* Literal.String.Backtick */
|
||||
.highlight .sc { color: #56DB3A } /* Literal.String.Char */
|
||||
.highlight .sd { color: #B729D9; font-style: italic } /* Literal.String.Doc */
|
||||
.highlight .s2 { color: #56DB3A } /* Literal.String.Double */
|
||||
.highlight .se { color: #56DB3A } /* Literal.String.Escape */
|
||||
.highlight .sh { color: #56DB3A } /* Literal.String.Heredoc */
|
||||
.highlight .si { color: #56DB3A } /* Literal.String.Interpol */
|
||||
.highlight .sx { color: #56DB3A } /* Literal.String.Other */
|
||||
.highlight .sr { color: #56DB3A } /* Literal.String.Regex */
|
||||
.highlight .s1 { color: #56DB3A } /* Literal.String.Single */
|
||||
.highlight .ss { color: #56DB3A } /* Literal.String.Symbol */
|
||||
.highlight .bp { color: #3465a4 } /* Name.Builtin.Pseudo */
|
||||
.highlight .vc { color: #ffffff } /* Name.Variable.Class */
|
||||
.highlight .vg { color: #ffffff } /* Name.Variable.Global */
|
||||
.highlight .vi { color: #ffffff } /* Name.Variable.Instance */
|
||||
.highlight .il { color: #1299DA } /* Literal.Number.Integer.Long */
|
||||
@@ -0,0 +1,758 @@
|
||||
/*
|
||||
* searchtools.js_t
|
||||
* ~~~~~~~~~~~~~~~~
|
||||
*
|
||||
* Sphinx JavaScript utilities for the full-text search.
|
||||
*
|
||||
* :copyright: Copyright 2007-2017 by the Sphinx team, see AUTHORS.
|
||||
* :license: BSD, see LICENSE for details.
|
||||
*
|
||||
*/
|
||||
|
||||
|
||||
/* Non-minified version JS is _stemmer.js if file is provided */
|
||||
/**
|
||||
* Porter Stemmer
|
||||
*/
|
||||
var Stemmer = function() {
|
||||
|
||||
var step2list = {
|
||||
ational: 'ate',
|
||||
tional: 'tion',
|
||||
enci: 'ence',
|
||||
anci: 'ance',
|
||||
izer: 'ize',
|
||||
bli: 'ble',
|
||||
alli: 'al',
|
||||
entli: 'ent',
|
||||
eli: 'e',
|
||||
ousli: 'ous',
|
||||
ization: 'ize',
|
||||
ation: 'ate',
|
||||
ator: 'ate',
|
||||
alism: 'al',
|
||||
iveness: 'ive',
|
||||
fulness: 'ful',
|
||||
ousness: 'ous',
|
||||
aliti: 'al',
|
||||
iviti: 'ive',
|
||||
biliti: 'ble',
|
||||
logi: 'log'
|
||||
};
|
||||
|
||||
var step3list = {
|
||||
icate: 'ic',
|
||||
ative: '',
|
||||
alize: 'al',
|
||||
iciti: 'ic',
|
||||
ical: 'ic',
|
||||
ful: '',
|
||||
ness: ''
|
||||
};
|
||||
|
||||
var c = "[^aeiou]"; // consonant
|
||||
var v = "[aeiouy]"; // vowel
|
||||
var C = c + "[^aeiouy]*"; // consonant sequence
|
||||
var V = v + "[aeiou]*"; // vowel sequence
|
||||
|
||||
var mgr0 = "^(" + C + ")?" + V + C; // [C]VC... is m>0
|
||||
var meq1 = "^(" + C + ")?" + V + C + "(" + V + ")?$"; // [C]VC[V] is m=1
|
||||
var mgr1 = "^(" + C + ")?" + V + C + V + C; // [C]VCVC... is m>1
|
||||
var s_v = "^(" + C + ")?" + v; // vowel in stem
|
||||
|
||||
this.stemWord = function (w) {
|
||||
var stem;
|
||||
var suffix;
|
||||
var firstch;
|
||||
var origword = w;
|
||||
|
||||
if (w.length < 3)
|
||||
return w;
|
||||
|
||||
var re;
|
||||
var re2;
|
||||
var re3;
|
||||
var re4;
|
||||
|
||||
firstch = w.substr(0,1);
|
||||
if (firstch == "y")
|
||||
w = firstch.toUpperCase() + w.substr(1);
|
||||
|
||||
// Step 1a
|
||||
re = /^(.+?)(ss|i)es$/;
|
||||
re2 = /^(.+?)([^s])s$/;
|
||||
|
||||
if (re.test(w))
|
||||
w = w.replace(re,"$1$2");
|
||||
else if (re2.test(w))
|
||||
w = w.replace(re2,"$1$2");
|
||||
|
||||
// Step 1b
|
||||
re = /^(.+?)eed$/;
|
||||
re2 = /^(.+?)(ed|ing)$/;
|
||||
if (re.test(w)) {
|
||||
var fp = re.exec(w);
|
||||
re = new RegExp(mgr0);
|
||||
if (re.test(fp[1])) {
|
||||
re = /.$/;
|
||||
w = w.replace(re,"");
|
||||
}
|
||||
}
|
||||
else if (re2.test(w)) {
|
||||
var fp = re2.exec(w);
|
||||
stem = fp[1];
|
||||
re2 = new RegExp(s_v);
|
||||
if (re2.test(stem)) {
|
||||
w = stem;
|
||||
re2 = /(at|bl|iz)$/;
|
||||
re3 = new RegExp("([^aeiouylsz])\\1$");
|
||||
re4 = new RegExp("^" + C + v + "[^aeiouwxy]$");
|
||||
if (re2.test(w))
|
||||
w = w + "e";
|
||||
else if (re3.test(w)) {
|
||||
re = /.$/;
|
||||
w = w.replace(re,"");
|
||||
}
|
||||
else if (re4.test(w))
|
||||
w = w + "e";
|
||||
}
|
||||
}
|
||||
|
||||
// Step 1c
|
||||
re = /^(.+?)y$/;
|
||||
if (re.test(w)) {
|
||||
var fp = re.exec(w);
|
||||
stem = fp[1];
|
||||
re = new RegExp(s_v);
|
||||
if (re.test(stem))
|
||||
w = stem + "i";
|
||||
}
|
||||
|
||||
// Step 2
|
||||
re = /^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/;
|
||||
if (re.test(w)) {
|
||||
var fp = re.exec(w);
|
||||
stem = fp[1];
|
||||
suffix = fp[2];
|
||||
re = new RegExp(mgr0);
|
||||
if (re.test(stem))
|
||||
w = stem + step2list[suffix];
|
||||
}
|
||||
|
||||
// Step 3
|
||||
re = /^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/;
|
||||
if (re.test(w)) {
|
||||
var fp = re.exec(w);
|
||||
stem = fp[1];
|
||||
suffix = fp[2];
|
||||
re = new RegExp(mgr0);
|
||||
if (re.test(stem))
|
||||
w = stem + step3list[suffix];
|
||||
}
|
||||
|
||||
// Step 4
|
||||
re = /^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/;
|
||||
re2 = /^(.+?)(s|t)(ion)$/;
|
||||
if (re.test(w)) {
|
||||
var fp = re.exec(w);
|
||||
stem = fp[1];
|
||||
re = new RegExp(mgr1);
|
||||
if (re.test(stem))
|
||||
w = stem;
|
||||
}
|
||||
else if (re2.test(w)) {
|
||||
var fp = re2.exec(w);
|
||||
stem = fp[1] + fp[2];
|
||||
re2 = new RegExp(mgr1);
|
||||
if (re2.test(stem))
|
||||
w = stem;
|
||||
}
|
||||
|
||||
// Step 5
|
||||
re = /^(.+?)e$/;
|
||||
if (re.test(w)) {
|
||||
var fp = re.exec(w);
|
||||
stem = fp[1];
|
||||
re = new RegExp(mgr1);
|
||||
re2 = new RegExp(meq1);
|
||||
re3 = new RegExp("^" + C + v + "[^aeiouwxy]$");
|
||||
if (re.test(stem) || (re2.test(stem) && !(re3.test(stem))))
|
||||
w = stem;
|
||||
}
|
||||
re = /ll$/;
|
||||
re2 = new RegExp(mgr1);
|
||||
if (re.test(w) && re2.test(w)) {
|
||||
re = /.$/;
|
||||
w = w.replace(re,"");
|
||||
}
|
||||
|
||||
// and turn initial Y back to y
|
||||
if (firstch == "y")
|
||||
w = firstch.toLowerCase() + w.substr(1);
|
||||
return w;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Simple result scoring code.
|
||||
*/
|
||||
var Scorer = {
|
||||
// Implement the following function to further tweak the score for each result
|
||||
// The function takes a result array [filename, title, anchor, descr, score]
|
||||
// and returns the new score.
|
||||
/*
|
||||
score: function(result) {
|
||||
return result[4];
|
||||
},
|
||||
*/
|
||||
|
||||
// query matches the full name of an object
|
||||
objNameMatch: 11,
|
||||
// or matches in the last dotted part of the object name
|
||||
objPartialMatch: 6,
|
||||
// Additive scores depending on the priority of the object
|
||||
objPrio: {0: 15, // used to be importantResults
|
||||
1: 5, // used to be objectResults
|
||||
2: -5}, // used to be unimportantResults
|
||||
// Used when the priority is not in the mapping.
|
||||
objPrioDefault: 0,
|
||||
|
||||
// query found in title
|
||||
title: 15,
|
||||
// query found in terms
|
||||
term: 5
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
var splitChars = (function() {
|
||||
var result = {};
|
||||
var singles = [96, 180, 187, 191, 215, 247, 749, 885, 903, 907, 909, 930, 1014, 1648,
|
||||
1748, 1809, 2416, 2473, 2481, 2526, 2601, 2609, 2612, 2615, 2653, 2702,
|
||||
2706, 2729, 2737, 2740, 2857, 2865, 2868, 2910, 2928, 2948, 2961, 2971,
|
||||
2973, 3085, 3089, 3113, 3124, 3213, 3217, 3241, 3252, 3295, 3341, 3345,
|
||||
3369, 3506, 3516, 3633, 3715, 3721, 3736, 3744, 3748, 3750, 3756, 3761,
|
||||
3781, 3912, 4239, 4347, 4681, 4695, 4697, 4745, 4785, 4799, 4801, 4823,
|
||||
4881, 5760, 5901, 5997, 6313, 7405, 8024, 8026, 8028, 8030, 8117, 8125,
|
||||
8133, 8181, 8468, 8485, 8487, 8489, 8494, 8527, 11311, 11359, 11687, 11695,
|
||||
11703, 11711, 11719, 11727, 11735, 12448, 12539, 43010, 43014, 43019, 43587,
|
||||
43696, 43713, 64286, 64297, 64311, 64317, 64319, 64322, 64325, 65141];
|
||||
var i, j, start, end;
|
||||
for (i = 0; i < singles.length; i++) {
|
||||
result[singles[i]] = true;
|
||||
}
|
||||
var ranges = [[0, 47], [58, 64], [91, 94], [123, 169], [171, 177], [182, 184], [706, 709],
|
||||
[722, 735], [741, 747], [751, 879], [888, 889], [894, 901], [1154, 1161],
|
||||
[1318, 1328], [1367, 1368], [1370, 1376], [1416, 1487], [1515, 1519], [1523, 1568],
|
||||
[1611, 1631], [1642, 1645], [1750, 1764], [1767, 1773], [1789, 1790], [1792, 1807],
|
||||
[1840, 1868], [1958, 1968], [1970, 1983], [2027, 2035], [2038, 2041], [2043, 2047],
|
||||
[2070, 2073], [2075, 2083], [2085, 2087], [2089, 2307], [2362, 2364], [2366, 2383],
|
||||
[2385, 2391], [2402, 2405], [2419, 2424], [2432, 2436], [2445, 2446], [2449, 2450],
|
||||
[2483, 2485], [2490, 2492], [2494, 2509], [2511, 2523], [2530, 2533], [2546, 2547],
|
||||
[2554, 2564], [2571, 2574], [2577, 2578], [2618, 2648], [2655, 2661], [2672, 2673],
|
||||
[2677, 2692], [2746, 2748], [2750, 2767], [2769, 2783], [2786, 2789], [2800, 2820],
|
||||
[2829, 2830], [2833, 2834], [2874, 2876], [2878, 2907], [2914, 2917], [2930, 2946],
|
||||
[2955, 2957], [2966, 2968], [2976, 2978], [2981, 2983], [2987, 2989], [3002, 3023],
|
||||
[3025, 3045], [3059, 3076], [3130, 3132], [3134, 3159], [3162, 3167], [3170, 3173],
|
||||
[3184, 3191], [3199, 3204], [3258, 3260], [3262, 3293], [3298, 3301], [3312, 3332],
|
||||
[3386, 3388], [3390, 3423], [3426, 3429], [3446, 3449], [3456, 3460], [3479, 3481],
|
||||
[3518, 3519], [3527, 3584], [3636, 3647], [3655, 3663], [3674, 3712], [3717, 3718],
|
||||
[3723, 3724], [3726, 3731], [3752, 3753], [3764, 3772], [3774, 3775], [3783, 3791],
|
||||
[3802, 3803], [3806, 3839], [3841, 3871], [3892, 3903], [3949, 3975], [3980, 4095],
|
||||
[4139, 4158], [4170, 4175], [4182, 4185], [4190, 4192], [4194, 4196], [4199, 4205],
|
||||
[4209, 4212], [4226, 4237], [4250, 4255], [4294, 4303], [4349, 4351], [4686, 4687],
|
||||
[4702, 4703], [4750, 4751], [4790, 4791], [4806, 4807], [4886, 4887], [4955, 4968],
|
||||
[4989, 4991], [5008, 5023], [5109, 5120], [5741, 5742], [5787, 5791], [5867, 5869],
|
||||
[5873, 5887], [5906, 5919], [5938, 5951], [5970, 5983], [6001, 6015], [6068, 6102],
|
||||
[6104, 6107], [6109, 6111], [6122, 6127], [6138, 6159], [6170, 6175], [6264, 6271],
|
||||
[6315, 6319], [6390, 6399], [6429, 6469], [6510, 6511], [6517, 6527], [6572, 6592],
|
||||
[6600, 6607], [6619, 6655], [6679, 6687], [6741, 6783], [6794, 6799], [6810, 6822],
|
||||
[6824, 6916], [6964, 6980], [6988, 6991], [7002, 7042], [7073, 7085], [7098, 7167],
|
||||
[7204, 7231], [7242, 7244], [7294, 7400], [7410, 7423], [7616, 7679], [7958, 7959],
|
||||
[7966, 7967], [8006, 8007], [8014, 8015], [8062, 8063], [8127, 8129], [8141, 8143],
|
||||
[8148, 8149], [8156, 8159], [8173, 8177], [8189, 8303], [8306, 8307], [8314, 8318],
|
||||
[8330, 8335], [8341, 8449], [8451, 8454], [8456, 8457], [8470, 8472], [8478, 8483],
|
||||
[8506, 8507], [8512, 8516], [8522, 8525], [8586, 9311], [9372, 9449], [9472, 10101],
|
||||
[10132, 11263], [11493, 11498], [11503, 11516], [11518, 11519], [11558, 11567],
|
||||
[11622, 11630], [11632, 11647], [11671, 11679], [11743, 11822], [11824, 12292],
|
||||
[12296, 12320], [12330, 12336], [12342, 12343], [12349, 12352], [12439, 12444],
|
||||
[12544, 12548], [12590, 12592], [12687, 12689], [12694, 12703], [12728, 12783],
|
||||
[12800, 12831], [12842, 12880], [12896, 12927], [12938, 12976], [12992, 13311],
|
||||
[19894, 19967], [40908, 40959], [42125, 42191], [42238, 42239], [42509, 42511],
|
||||
[42540, 42559], [42592, 42593], [42607, 42622], [42648, 42655], [42736, 42774],
|
||||
[42784, 42785], [42889, 42890], [42893, 43002], [43043, 43055], [43062, 43071],
|
||||
[43124, 43137], [43188, 43215], [43226, 43249], [43256, 43258], [43260, 43263],
|
||||
[43302, 43311], [43335, 43359], [43389, 43395], [43443, 43470], [43482, 43519],
|
||||
[43561, 43583], [43596, 43599], [43610, 43615], [43639, 43641], [43643, 43647],
|
||||
[43698, 43700], [43703, 43704], [43710, 43711], [43715, 43738], [43742, 43967],
|
||||
[44003, 44015], [44026, 44031], [55204, 55215], [55239, 55242], [55292, 55295],
|
||||
[57344, 63743], [64046, 64047], [64110, 64111], [64218, 64255], [64263, 64274],
|
||||
[64280, 64284], [64434, 64466], [64830, 64847], [64912, 64913], [64968, 65007],
|
||||
[65020, 65135], [65277, 65295], [65306, 65312], [65339, 65344], [65371, 65381],
|
||||
[65471, 65473], [65480, 65481], [65488, 65489], [65496, 65497]];
|
||||
for (i = 0; i < ranges.length; i++) {
|
||||
start = ranges[i][0];
|
||||
end = ranges[i][1];
|
||||
for (j = start; j <= end; j++) {
|
||||
result[j] = true;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
})();
|
||||
|
||||
function splitQuery(query) {
|
||||
var result = [];
|
||||
var start = -1;
|
||||
for (var i = 0; i < query.length; i++) {
|
||||
if (splitChars[query.charCodeAt(i)]) {
|
||||
if (start !== -1) {
|
||||
result.push(query.slice(start, i));
|
||||
start = -1;
|
||||
}
|
||||
} else if (start === -1) {
|
||||
start = i;
|
||||
}
|
||||
}
|
||||
if (start !== -1) {
|
||||
result.push(query.slice(start));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Search Module
|
||||
*/
|
||||
var Search = {
|
||||
|
||||
_index : null,
|
||||
_queued_query : null,
|
||||
_pulse_status : -1,
|
||||
|
||||
init : function() {
|
||||
var params = $.getQueryParameters();
|
||||
if (params.q) {
|
||||
var query = params.q[0];
|
||||
$('input[name="q"]')[0].value = query;
|
||||
this.performSearch(query);
|
||||
}
|
||||
},
|
||||
|
||||
loadIndex : function(url) {
|
||||
$.ajax({type: "GET", url: url, data: null,
|
||||
dataType: "script", cache: true,
|
||||
complete: function(jqxhr, textstatus) {
|
||||
if (textstatus != "success") {
|
||||
document.getElementById("searchindexloader").src = url;
|
||||
}
|
||||
}});
|
||||
},
|
||||
|
||||
setIndex : function(index) {
|
||||
var q;
|
||||
this._index = index;
|
||||
if ((q = this._queued_query) !== null) {
|
||||
this._queued_query = null;
|
||||
Search.query(q);
|
||||
}
|
||||
},
|
||||
|
||||
hasIndex : function() {
|
||||
return this._index !== null;
|
||||
},
|
||||
|
||||
deferQuery : function(query) {
|
||||
this._queued_query = query;
|
||||
},
|
||||
|
||||
stopPulse : function() {
|
||||
this._pulse_status = 0;
|
||||
},
|
||||
|
||||
startPulse : function() {
|
||||
if (this._pulse_status >= 0)
|
||||
return;
|
||||
function pulse() {
|
||||
var i;
|
||||
Search._pulse_status = (Search._pulse_status + 1) % 4;
|
||||
var dotString = '';
|
||||
for (i = 0; i < Search._pulse_status; i++)
|
||||
dotString += '.';
|
||||
Search.dots.text(dotString);
|
||||
if (Search._pulse_status > -1)
|
||||
window.setTimeout(pulse, 500);
|
||||
}
|
||||
pulse();
|
||||
},
|
||||
|
||||
/**
|
||||
* perform a search for something (or wait until index is loaded)
|
||||
*/
|
||||
performSearch : function(query) {
|
||||
// create the required interface elements
|
||||
this.out = $('#search-results');
|
||||
this.title = $('<h2>' + _('Searching') + '</h2>').appendTo(this.out);
|
||||
this.dots = $('<span></span>').appendTo(this.title);
|
||||
this.status = $('<p style="display: none"></p>').appendTo(this.out);
|
||||
this.output = $('<ul class="search"/>').appendTo(this.out);
|
||||
|
||||
$('#search-progress').text(_('Preparing search...'));
|
||||
this.startPulse();
|
||||
|
||||
// index already loaded, the browser was quick!
|
||||
if (this.hasIndex())
|
||||
this.query(query);
|
||||
else
|
||||
this.deferQuery(query);
|
||||
},
|
||||
|
||||
/**
|
||||
* execute search (requires search index to be loaded)
|
||||
*/
|
||||
query : function(query) {
|
||||
var i;
|
||||
var stopwords = ["a","and","are","as","at","be","but","by","for","if","in","into","is","it","near","no","not","of","on","or","such","that","the","their","then","there","these","they","this","to","was","will","with"];
|
||||
|
||||
// stem the searchterms and add them to the correct list
|
||||
var stemmer = new Stemmer();
|
||||
var searchterms = [];
|
||||
var excluded = [];
|
||||
var hlterms = [];
|
||||
var tmp = splitQuery(query);
|
||||
var objectterms = [];
|
||||
for (i = 0; i < tmp.length; i++) {
|
||||
if (tmp[i] !== "") {
|
||||
objectterms.push(tmp[i].toLowerCase());
|
||||
}
|
||||
|
||||
if ($u.indexOf(stopwords, tmp[i].toLowerCase()) != -1 || tmp[i].match(/^\d+$/) ||
|
||||
tmp[i] === "") {
|
||||
// skip this "word"
|
||||
continue;
|
||||
}
|
||||
// stem the word
|
||||
var word = stemmer.stemWord(tmp[i].toLowerCase());
|
||||
// prevent stemmer from cutting word smaller than two chars
|
||||
if(word.length < 3 && tmp[i].length >= 3) {
|
||||
word = tmp[i];
|
||||
}
|
||||
var toAppend;
|
||||
// select the correct list
|
||||
if (word[0] == '-') {
|
||||
toAppend = excluded;
|
||||
word = word.substr(1);
|
||||
}
|
||||
else {
|
||||
toAppend = searchterms;
|
||||
hlterms.push(tmp[i].toLowerCase());
|
||||
}
|
||||
// only add if not already in the list
|
||||
if (!$u.contains(toAppend, word))
|
||||
toAppend.push(word);
|
||||
}
|
||||
var highlightstring = '?highlight=' + $.urlencode(hlterms.join(" "));
|
||||
|
||||
// console.debug('SEARCH: searching for:');
|
||||
// console.info('required: ', searchterms);
|
||||
// console.info('excluded: ', excluded);
|
||||
|
||||
// prepare search
|
||||
var terms = this._index.terms;
|
||||
var titleterms = this._index.titleterms;
|
||||
|
||||
// array of [filename, title, anchor, descr, score]
|
||||
var results = [];
|
||||
$('#search-progress').empty();
|
||||
|
||||
// lookup as object
|
||||
for (i = 0; i < objectterms.length; i++) {
|
||||
var others = [].concat(objectterms.slice(0, i),
|
||||
objectterms.slice(i+1, objectterms.length));
|
||||
results = results.concat(this.performObjectSearch(objectterms[i], others));
|
||||
}
|
||||
|
||||
// lookup as search terms in fulltext
|
||||
results = results.concat(this.performTermsSearch(searchterms, excluded, terms, titleterms));
|
||||
|
||||
// let the scorer override scores with a custom scoring function
|
||||
if (Scorer.score) {
|
||||
for (i = 0; i < results.length; i++)
|
||||
results[i][4] = Scorer.score(results[i]);
|
||||
}
|
||||
|
||||
// now sort the results by score (in opposite order of appearance, since the
|
||||
// display function below uses pop() to retrieve items) and then
|
||||
// alphabetically
|
||||
results.sort(function(a, b) {
|
||||
var left = a[4];
|
||||
var right = b[4];
|
||||
if (left > right) {
|
||||
return 1;
|
||||
} else if (left < right) {
|
||||
return -1;
|
||||
} else {
|
||||
// same score: sort alphabetically
|
||||
left = a[1].toLowerCase();
|
||||
right = b[1].toLowerCase();
|
||||
return (left > right) ? -1 : ((left < right) ? 1 : 0);
|
||||
}
|
||||
});
|
||||
|
||||
// for debugging
|
||||
//Search.lastresults = results.slice(); // a copy
|
||||
//console.info('search results:', Search.lastresults);
|
||||
|
||||
// print the results
|
||||
var resultCount = results.length;
|
||||
function displayNextItem() {
|
||||
// results left, load the summary and display it
|
||||
if (results.length) {
|
||||
var item = results.pop();
|
||||
var listItem = $('<li style="display:none"></li>');
|
||||
if (DOCUMENTATION_OPTIONS.FILE_SUFFIX === '') {
|
||||
// dirhtml builder
|
||||
var dirname = item[0] + '/';
|
||||
if (dirname.match(/\/index\/$/)) {
|
||||
dirname = dirname.substring(0, dirname.length-6);
|
||||
} else if (dirname == 'index/') {
|
||||
dirname = '';
|
||||
}
|
||||
listItem.append($('<a/>').attr('href',
|
||||
DOCUMENTATION_OPTIONS.URL_ROOT + dirname +
|
||||
highlightstring + item[2]).html(item[1]));
|
||||
} else {
|
||||
// normal html builders
|
||||
listItem.append($('<a/>').attr('href',
|
||||
item[0] + DOCUMENTATION_OPTIONS.FILE_SUFFIX +
|
||||
highlightstring + item[2]).html(item[1]));
|
||||
}
|
||||
if (item[3]) {
|
||||
listItem.append($('<span> (' + item[3] + ')</span>'));
|
||||
Search.output.append(listItem);
|
||||
listItem.slideDown(5, function() {
|
||||
displayNextItem();
|
||||
});
|
||||
} else if (DOCUMENTATION_OPTIONS.HAS_SOURCE) {
|
||||
var suffix = DOCUMENTATION_OPTIONS.SOURCELINK_SUFFIX;
|
||||
$.ajax({url: DOCUMENTATION_OPTIONS.URL_ROOT + '_sources/' + item[5] + (item[5].slice(-suffix.length) === suffix ? '' : suffix),
|
||||
dataType: "text",
|
||||
complete: function(jqxhr, textstatus) {
|
||||
var data = jqxhr.responseText;
|
||||
if (data !== '' && data !== undefined) {
|
||||
listItem.append(Search.makeSearchSummary(data, searchterms, hlterms));
|
||||
}
|
||||
Search.output.append(listItem);
|
||||
listItem.slideDown(5, function() {
|
||||
displayNextItem();
|
||||
});
|
||||
}});
|
||||
} else {
|
||||
// no source available, just display title
|
||||
Search.output.append(listItem);
|
||||
listItem.slideDown(5, function() {
|
||||
displayNextItem();
|
||||
});
|
||||
}
|
||||
}
|
||||
// search finished, update title and status message
|
||||
else {
|
||||
Search.stopPulse();
|
||||
Search.title.text(_('Search Results'));
|
||||
if (!resultCount)
|
||||
Search.status.text(_('Your search did not match any documents. Please make sure that all words are spelled correctly and that you\'ve selected enough categories.'));
|
||||
else
|
||||
Search.status.text(_('Search finished, found %s page(s) matching the search query.').replace('%s', resultCount));
|
||||
Search.status.fadeIn(500);
|
||||
}
|
||||
}
|
||||
displayNextItem();
|
||||
},
|
||||
|
||||
/**
|
||||
* search for object names
|
||||
*/
|
||||
performObjectSearch : function(object, otherterms) {
|
||||
var filenames = this._index.filenames;
|
||||
var docnames = this._index.docnames;
|
||||
var objects = this._index.objects;
|
||||
var objnames = this._index.objnames;
|
||||
var titles = this._index.titles;
|
||||
|
||||
var i;
|
||||
var results = [];
|
||||
|
||||
for (var prefix in objects) {
|
||||
for (var name in objects[prefix]) {
|
||||
var fullname = (prefix ? prefix + '.' : '') + name;
|
||||
if (fullname.toLowerCase().indexOf(object) > -1) {
|
||||
var score = 0;
|
||||
var parts = fullname.split('.');
|
||||
// check for different match types: exact matches of full name or
|
||||
// "last name" (i.e. last dotted part)
|
||||
if (fullname == object || parts[parts.length - 1] == object) {
|
||||
score += Scorer.objNameMatch;
|
||||
// matches in last name
|
||||
} else if (parts[parts.length - 1].indexOf(object) > -1) {
|
||||
score += Scorer.objPartialMatch;
|
||||
}
|
||||
var match = objects[prefix][name];
|
||||
var objname = objnames[match[1]][2];
|
||||
var title = titles[match[0]];
|
||||
// If more than one term searched for, we require other words to be
|
||||
// found in the name/title/description
|
||||
if (otherterms.length > 0) {
|
||||
var haystack = (prefix + ' ' + name + ' ' +
|
||||
objname + ' ' + title).toLowerCase();
|
||||
var allfound = true;
|
||||
for (i = 0; i < otherterms.length; i++) {
|
||||
if (haystack.indexOf(otherterms[i]) == -1) {
|
||||
allfound = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!allfound) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
var descr = objname + _(', in ') + title;
|
||||
|
||||
var anchor = match[3];
|
||||
if (anchor === '')
|
||||
anchor = fullname;
|
||||
else if (anchor == '-')
|
||||
anchor = objnames[match[1]][1] + '-' + fullname;
|
||||
// add custom score for some objects according to scorer
|
||||
if (Scorer.objPrio.hasOwnProperty(match[2])) {
|
||||
score += Scorer.objPrio[match[2]];
|
||||
} else {
|
||||
score += Scorer.objPrioDefault;
|
||||
}
|
||||
results.push([docnames[match[0]], fullname, '#'+anchor, descr, score, filenames[match[0]]]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
},
|
||||
|
||||
/**
|
||||
* search for full-text terms in the index
|
||||
*/
|
||||
performTermsSearch : function(searchterms, excluded, terms, titleterms) {
|
||||
var docnames = this._index.docnames;
|
||||
var filenames = this._index.filenames;
|
||||
var titles = this._index.titles;
|
||||
|
||||
var i, j, file;
|
||||
var fileMap = {};
|
||||
var scoreMap = {};
|
||||
var results = [];
|
||||
|
||||
// perform the search on the required terms
|
||||
for (i = 0; i < searchterms.length; i++) {
|
||||
var word = searchterms[i];
|
||||
var files = [];
|
||||
var _o = [
|
||||
{files: terms[word], score: Scorer.term},
|
||||
{files: titleterms[word], score: Scorer.title}
|
||||
];
|
||||
|
||||
// no match but word was a required one
|
||||
if ($u.every(_o, function(o){return o.files === undefined;})) {
|
||||
break;
|
||||
}
|
||||
// found search word in contents
|
||||
$u.each(_o, function(o) {
|
||||
var _files = o.files;
|
||||
if (_files === undefined)
|
||||
return
|
||||
|
||||
if (_files.length === undefined)
|
||||
_files = [_files];
|
||||
files = files.concat(_files);
|
||||
|
||||
// set score for the word in each file to Scorer.term
|
||||
for (j = 0; j < _files.length; j++) {
|
||||
file = _files[j];
|
||||
if (!(file in scoreMap))
|
||||
scoreMap[file] = {}
|
||||
scoreMap[file][word] = o.score;
|
||||
}
|
||||
});
|
||||
|
||||
// create the mapping
|
||||
for (j = 0; j < files.length; j++) {
|
||||
file = files[j];
|
||||
if (file in fileMap)
|
||||
fileMap[file].push(word);
|
||||
else
|
||||
fileMap[file] = [word];
|
||||
}
|
||||
}
|
||||
|
||||
// now check if the files don't contain excluded terms
|
||||
for (file in fileMap) {
|
||||
var valid = true;
|
||||
|
||||
// check if all requirements are matched
|
||||
if (fileMap[file].length != searchterms.length)
|
||||
continue;
|
||||
|
||||
// ensure that none of the excluded terms is in the search result
|
||||
for (i = 0; i < excluded.length; i++) {
|
||||
if (terms[excluded[i]] == file ||
|
||||
titleterms[excluded[i]] == file ||
|
||||
$u.contains(terms[excluded[i]] || [], file) ||
|
||||
$u.contains(titleterms[excluded[i]] || [], file)) {
|
||||
valid = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// if we have still a valid result we can add it to the result list
|
||||
if (valid) {
|
||||
// select one (max) score for the file.
|
||||
// for better ranking, we should calculate ranking by using words statistics like basic tf-idf...
|
||||
var score = $u.max($u.map(fileMap[file], function(w){return scoreMap[file][w]}));
|
||||
results.push([docnames[file], titles[file], '', null, score, filenames[file]]);
|
||||
}
|
||||
}
|
||||
return results;
|
||||
},
|
||||
|
||||
/**
|
||||
* helper function to return a node containing the
|
||||
* search summary for a given text. keywords is a list
|
||||
* of stemmed words, hlwords is the list of normal, unstemmed
|
||||
* words. the first one is used to find the occurrence, the
|
||||
* latter for highlighting it.
|
||||
*/
|
||||
makeSearchSummary : function(text, keywords, hlwords) {
|
||||
var textLower = text.toLowerCase();
|
||||
var start = 0;
|
||||
$.each(keywords, function() {
|
||||
var i = textLower.indexOf(this.toLowerCase());
|
||||
if (i > -1)
|
||||
start = i;
|
||||
});
|
||||
start = Math.max(start - 120, 0);
|
||||
var excerpt = ((start > 0) ? '...' : '') +
|
||||
$.trim(text.substr(start, 240)) +
|
||||
((start + 240 - text.length) ? '...' : '');
|
||||
var rv = $('<div class="context"></div>').text(excerpt);
|
||||
$.each(hlwords, function() {
|
||||
rv = rv.highlightText(this, 'highlighted');
|
||||
});
|
||||
return rv;
|
||||
}
|
||||
};
|
||||
|
||||
$(document).ready(function() {
|
||||
Search.init();
|
||||
});
|
||||
|
After Width: | Height: | Size: 3.8 KiB |
|
After Width: | Height: | Size: 437 B |
|
After Width: | Height: | Size: 3.1 KiB |
|
After Width: | Height: | Size: 2.0 KiB |
|
After Width: | Height: | Size: 589 B |
@@ -0,0 +1,999 @@
|
||||
// Underscore.js 1.3.1
|
||||
// (c) 2009-2012 Jeremy Ashkenas, DocumentCloud Inc.
|
||||
// Underscore is freely distributable under the MIT license.
|
||||
// Portions of Underscore are inspired or borrowed from Prototype,
|
||||
// Oliver Steele's Functional, and John Resig's Micro-Templating.
|
||||
// For all details and documentation:
|
||||
// http://documentcloud.github.com/underscore
|
||||
|
||||
(function() {
|
||||
|
||||
// Baseline setup
|
||||
// --------------
|
||||
|
||||
// Establish the root object, `window` in the browser, or `global` on the server.
|
||||
var root = this;
|
||||
|
||||
// Save the previous value of the `_` variable.
|
||||
var previousUnderscore = root._;
|
||||
|
||||
// Establish the object that gets returned to break out of a loop iteration.
|
||||
var breaker = {};
|
||||
|
||||
// Save bytes in the minified (but not gzipped) version:
|
||||
var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
|
||||
|
||||
// Create quick reference variables for speed access to core prototypes.
|
||||
var slice = ArrayProto.slice,
|
||||
unshift = ArrayProto.unshift,
|
||||
toString = ObjProto.toString,
|
||||
hasOwnProperty = ObjProto.hasOwnProperty;
|
||||
|
||||
// All **ECMAScript 5** native function implementations that we hope to use
|
||||
// are declared here.
|
||||
var
|
||||
nativeForEach = ArrayProto.forEach,
|
||||
nativeMap = ArrayProto.map,
|
||||
nativeReduce = ArrayProto.reduce,
|
||||
nativeReduceRight = ArrayProto.reduceRight,
|
||||
nativeFilter = ArrayProto.filter,
|
||||
nativeEvery = ArrayProto.every,
|
||||
nativeSome = ArrayProto.some,
|
||||
nativeIndexOf = ArrayProto.indexOf,
|
||||
nativeLastIndexOf = ArrayProto.lastIndexOf,
|
||||
nativeIsArray = Array.isArray,
|
||||
nativeKeys = Object.keys,
|
||||
nativeBind = FuncProto.bind;
|
||||
|
||||
// Create a safe reference to the Underscore object for use below.
|
||||
var _ = function(obj) { return new wrapper(obj); };
|
||||
|
||||
// Export the Underscore object for **Node.js**, with
|
||||
// backwards-compatibility for the old `require()` API. If we're in
|
||||
// the browser, add `_` as a global object via a string identifier,
|
||||
// for Closure Compiler "advanced" mode.
|
||||
if (typeof exports !== 'undefined') {
|
||||
if (typeof module !== 'undefined' && module.exports) {
|
||||
exports = module.exports = _;
|
||||
}
|
||||
exports._ = _;
|
||||
} else {
|
||||
root['_'] = _;
|
||||
}
|
||||
|
||||
// Current version.
|
||||
_.VERSION = '1.3.1';
|
||||
|
||||
// Collection Functions
|
||||
// --------------------
|
||||
|
||||
// The cornerstone, an `each` implementation, aka `forEach`.
|
||||
// Handles objects with the built-in `forEach`, arrays, and raw objects.
|
||||
// Delegates to **ECMAScript 5**'s native `forEach` if available.
|
||||
var each = _.each = _.forEach = function(obj, iterator, context) {
|
||||
if (obj == null) return;
|
||||
if (nativeForEach && obj.forEach === nativeForEach) {
|
||||
obj.forEach(iterator, context);
|
||||
} else if (obj.length === +obj.length) {
|
||||
for (var i = 0, l = obj.length; i < l; i++) {
|
||||
if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) return;
|
||||
}
|
||||
} else {
|
||||
for (var key in obj) {
|
||||
if (_.has(obj, key)) {
|
||||
if (iterator.call(context, obj[key], key, obj) === breaker) return;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Return the results of applying the iterator to each element.
|
||||
// Delegates to **ECMAScript 5**'s native `map` if available.
|
||||
_.map = _.collect = function(obj, iterator, context) {
|
||||
var results = [];
|
||||
if (obj == null) return results;
|
||||
if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
|
||||
each(obj, function(value, index, list) {
|
||||
results[results.length] = iterator.call(context, value, index, list);
|
||||
});
|
||||
if (obj.length === +obj.length) results.length = obj.length;
|
||||
return results;
|
||||
};
|
||||
|
||||
// **Reduce** builds up a single result from a list of values, aka `inject`,
|
||||
// or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.
|
||||
_.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {
|
||||
var initial = arguments.length > 2;
|
||||
if (obj == null) obj = [];
|
||||
if (nativeReduce && obj.reduce === nativeReduce) {
|
||||
if (context) iterator = _.bind(iterator, context);
|
||||
return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);
|
||||
}
|
||||
each(obj, function(value, index, list) {
|
||||
if (!initial) {
|
||||
memo = value;
|
||||
initial = true;
|
||||
} else {
|
||||
memo = iterator.call(context, memo, value, index, list);
|
||||
}
|
||||
});
|
||||
if (!initial) throw new TypeError('Reduce of empty array with no initial value');
|
||||
return memo;
|
||||
};
|
||||
|
||||
// The right-associative version of reduce, also known as `foldr`.
|
||||
// Delegates to **ECMAScript 5**'s native `reduceRight` if available.
|
||||
_.reduceRight = _.foldr = function(obj, iterator, memo, context) {
|
||||
var initial = arguments.length > 2;
|
||||
if (obj == null) obj = [];
|
||||
if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
|
||||
if (context) iterator = _.bind(iterator, context);
|
||||
return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
|
||||
}
|
||||
var reversed = _.toArray(obj).reverse();
|
||||
if (context && !initial) iterator = _.bind(iterator, context);
|
||||
return initial ? _.reduce(reversed, iterator, memo, context) : _.reduce(reversed, iterator);
|
||||
};
|
||||
|
||||
// Return the first value which passes a truth test. Aliased as `detect`.
|
||||
_.find = _.detect = function(obj, iterator, context) {
|
||||
var result;
|
||||
any(obj, function(value, index, list) {
|
||||
if (iterator.call(context, value, index, list)) {
|
||||
result = value;
|
||||
return true;
|
||||
}
|
||||
});
|
||||
return result;
|
||||
};
|
||||
|
||||
// Return all the elements that pass a truth test.
|
||||
// Delegates to **ECMAScript 5**'s native `filter` if available.
|
||||
// Aliased as `select`.
|
||||
_.filter = _.select = function(obj, iterator, context) {
|
||||
var results = [];
|
||||
if (obj == null) return results;
|
||||
if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);
|
||||
each(obj, function(value, index, list) {
|
||||
if (iterator.call(context, value, index, list)) results[results.length] = value;
|
||||
});
|
||||
return results;
|
||||
};
|
||||
|
||||
// Return all the elements for which a truth test fails.
|
||||
_.reject = function(obj, iterator, context) {
|
||||
var results = [];
|
||||
if (obj == null) return results;
|
||||
each(obj, function(value, index, list) {
|
||||
if (!iterator.call(context, value, index, list)) results[results.length] = value;
|
||||
});
|
||||
return results;
|
||||
};
|
||||
|
||||
// Determine whether all of the elements match a truth test.
|
||||
// Delegates to **ECMAScript 5**'s native `every` if available.
|
||||
// Aliased as `all`.
|
||||
_.every = _.all = function(obj, iterator, context) {
|
||||
var result = true;
|
||||
if (obj == null) return result;
|
||||
if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);
|
||||
each(obj, function(value, index, list) {
|
||||
if (!(result = result && iterator.call(context, value, index, list))) return breaker;
|
||||
});
|
||||
return result;
|
||||
};
|
||||
|
||||
// Determine if at least one element in the object matches a truth test.
|
||||
// Delegates to **ECMAScript 5**'s native `some` if available.
|
||||
// Aliased as `any`.
|
||||
var any = _.some = _.any = function(obj, iterator, context) {
|
||||
iterator || (iterator = _.identity);
|
||||
var result = false;
|
||||
if (obj == null) return result;
|
||||
if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
|
||||
each(obj, function(value, index, list) {
|
||||
if (result || (result = iterator.call(context, value, index, list))) return breaker;
|
||||
});
|
||||
return !!result;
|
||||
};
|
||||
|
||||
// Determine if a given value is included in the array or object using `===`.
|
||||
// Aliased as `contains`.
|
||||
_.include = _.contains = function(obj, target) {
|
||||
var found = false;
|
||||
if (obj == null) return found;
|
||||
if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
|
||||
found = any(obj, function(value) {
|
||||
return value === target;
|
||||
});
|
||||
return found;
|
||||
};
|
||||
|
||||
// Invoke a method (with arguments) on every item in a collection.
|
||||
_.invoke = function(obj, method) {
|
||||
var args = slice.call(arguments, 2);
|
||||
return _.map(obj, function(value) {
|
||||
return (_.isFunction(method) ? method || value : value[method]).apply(value, args);
|
||||
});
|
||||
};
|
||||
|
||||
// Convenience version of a common use case of `map`: fetching a property.
|
||||
_.pluck = function(obj, key) {
|
||||
return _.map(obj, function(value){ return value[key]; });
|
||||
};
|
||||
|
||||
// Return the maximum element or (element-based computation).
|
||||
_.max = function(obj, iterator, context) {
|
||||
if (!iterator && _.isArray(obj)) return Math.max.apply(Math, obj);
|
||||
if (!iterator && _.isEmpty(obj)) return -Infinity;
|
||||
var result = {computed : -Infinity};
|
||||
each(obj, function(value, index, list) {
|
||||
var computed = iterator ? iterator.call(context, value, index, list) : value;
|
||||
computed >= result.computed && (result = {value : value, computed : computed});
|
||||
});
|
||||
return result.value;
|
||||
};
|
||||
|
||||
// Return the minimum element (or element-based computation).
|
||||
_.min = function(obj, iterator, context) {
|
||||
if (!iterator && _.isArray(obj)) return Math.min.apply(Math, obj);
|
||||
if (!iterator && _.isEmpty(obj)) return Infinity;
|
||||
var result = {computed : Infinity};
|
||||
each(obj, function(value, index, list) {
|
||||
var computed = iterator ? iterator.call(context, value, index, list) : value;
|
||||
computed < result.computed && (result = {value : value, computed : computed});
|
||||
});
|
||||
return result.value;
|
||||
};
|
||||
|
||||
// Shuffle an array.
|
||||
_.shuffle = function(obj) {
|
||||
var shuffled = [], rand;
|
||||
each(obj, function(value, index, list) {
|
||||
if (index == 0) {
|
||||
shuffled[0] = value;
|
||||
} else {
|
||||
rand = Math.floor(Math.random() * (index + 1));
|
||||
shuffled[index] = shuffled[rand];
|
||||
shuffled[rand] = value;
|
||||
}
|
||||
});
|
||||
return shuffled;
|
||||
};
|
||||
|
||||
// Sort the object's values by a criterion produced by an iterator.
|
||||
_.sortBy = function(obj, iterator, context) {
|
||||
return _.pluck(_.map(obj, function(value, index, list) {
|
||||
return {
|
||||
value : value,
|
||||
criteria : iterator.call(context, value, index, list)
|
||||
};
|
||||
}).sort(function(left, right) {
|
||||
var a = left.criteria, b = right.criteria;
|
||||
return a < b ? -1 : a > b ? 1 : 0;
|
||||
}), 'value');
|
||||
};
|
||||
|
||||
// Groups the object's values by a criterion. Pass either a string attribute
|
||||
// to group by, or a function that returns the criterion.
|
||||
_.groupBy = function(obj, val) {
|
||||
var result = {};
|
||||
var iterator = _.isFunction(val) ? val : function(obj) { return obj[val]; };
|
||||
each(obj, function(value, index) {
|
||||
var key = iterator(value, index);
|
||||
(result[key] || (result[key] = [])).push(value);
|
||||
});
|
||||
return result;
|
||||
};
|
||||
|
||||
// Use a comparator function to figure out at what index an object should
|
||||
// be inserted so as to maintain order. Uses binary search.
|
||||
_.sortedIndex = function(array, obj, iterator) {
|
||||
iterator || (iterator = _.identity);
|
||||
var low = 0, high = array.length;
|
||||
while (low < high) {
|
||||
var mid = (low + high) >> 1;
|
||||
iterator(array[mid]) < iterator(obj) ? low = mid + 1 : high = mid;
|
||||
}
|
||||
return low;
|
||||
};
|
||||
|
||||
// Safely convert anything iterable into a real, live array.
|
||||
_.toArray = function(iterable) {
|
||||
if (!iterable) return [];
|
||||
if (iterable.toArray) return iterable.toArray();
|
||||
if (_.isArray(iterable)) return slice.call(iterable);
|
||||
if (_.isArguments(iterable)) return slice.call(iterable);
|
||||
return _.values(iterable);
|
||||
};
|
||||
|
||||
// Return the number of elements in an object.
|
||||
_.size = function(obj) {
|
||||
return _.toArray(obj).length;
|
||||
};
|
||||
|
||||
// Array Functions
|
||||
// ---------------
|
||||
|
||||
// Get the first element of an array. Passing **n** will return the first N
|
||||
// values in the array. Aliased as `head`. The **guard** check allows it to work
|
||||
// with `_.map`.
|
||||
_.first = _.head = function(array, n, guard) {
|
||||
return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
|
||||
};
|
||||
|
||||
// Returns everything but the last entry of the array. Especcialy useful on
|
||||
// the arguments object. Passing **n** will return all the values in
|
||||
// the array, excluding the last N. The **guard** check allows it to work with
|
||||
// `_.map`.
|
||||
_.initial = function(array, n, guard) {
|
||||
return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n));
|
||||
};
|
||||
|
||||
// Get the last element of an array. Passing **n** will return the last N
|
||||
// values in the array. The **guard** check allows it to work with `_.map`.
|
||||
_.last = function(array, n, guard) {
|
||||
if ((n != null) && !guard) {
|
||||
return slice.call(array, Math.max(array.length - n, 0));
|
||||
} else {
|
||||
return array[array.length - 1];
|
||||
}
|
||||
};
|
||||
|
||||
// Returns everything but the first entry of the array. Aliased as `tail`.
|
||||
// Especially useful on the arguments object. Passing an **index** will return
|
||||
// the rest of the values in the array from that index onward. The **guard**
|
||||
// check allows it to work with `_.map`.
|
||||
_.rest = _.tail = function(array, index, guard) {
|
||||
return slice.call(array, (index == null) || guard ? 1 : index);
|
||||
};
|
||||
|
||||
// Trim out all falsy values from an array.
|
||||
_.compact = function(array) {
|
||||
return _.filter(array, function(value){ return !!value; });
|
||||
};
|
||||
|
||||
// Return a completely flattened version of an array.
|
||||
_.flatten = function(array, shallow) {
|
||||
return _.reduce(array, function(memo, value) {
|
||||
if (_.isArray(value)) return memo.concat(shallow ? value : _.flatten(value));
|
||||
memo[memo.length] = value;
|
||||
return memo;
|
||||
}, []);
|
||||
};
|
||||
|
||||
// Return a version of the array that does not contain the specified value(s).
|
||||
_.without = function(array) {
|
||||
return _.difference(array, slice.call(arguments, 1));
|
||||
};
|
||||
|
||||
// Produce a duplicate-free version of the array. If the array has already
|
||||
// been sorted, you have the option of using a faster algorithm.
|
||||
// Aliased as `unique`.
|
||||
_.uniq = _.unique = function(array, isSorted, iterator) {
|
||||
var initial = iterator ? _.map(array, iterator) : array;
|
||||
var result = [];
|
||||
_.reduce(initial, function(memo, el, i) {
|
||||
if (0 == i || (isSorted === true ? _.last(memo) != el : !_.include(memo, el))) {
|
||||
memo[memo.length] = el;
|
||||
result[result.length] = array[i];
|
||||
}
|
||||
return memo;
|
||||
}, []);
|
||||
return result;
|
||||
};
|
||||
|
||||
// Produce an array that contains the union: each distinct element from all of
|
||||
// the passed-in arrays.
|
||||
_.union = function() {
|
||||
return _.uniq(_.flatten(arguments, true));
|
||||
};
|
||||
|
||||
// Produce an array that contains every item shared between all the
|
||||
// passed-in arrays. (Aliased as "intersect" for back-compat.)
|
||||
_.intersection = _.intersect = function(array) {
|
||||
var rest = slice.call(arguments, 1);
|
||||
return _.filter(_.uniq(array), function(item) {
|
||||
return _.every(rest, function(other) {
|
||||
return _.indexOf(other, item) >= 0;
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
// Take the difference between one array and a number of other arrays.
|
||||
// Only the elements present in just the first array will remain.
|
||||
_.difference = function(array) {
|
||||
var rest = _.flatten(slice.call(arguments, 1));
|
||||
return _.filter(array, function(value){ return !_.include(rest, value); });
|
||||
};
|
||||
|
||||
// Zip together multiple lists into a single array -- elements that share
|
||||
// an index go together.
|
||||
_.zip = function() {
|
||||
var args = slice.call(arguments);
|
||||
var length = _.max(_.pluck(args, 'length'));
|
||||
var results = new Array(length);
|
||||
for (var i = 0; i < length; i++) results[i] = _.pluck(args, "" + i);
|
||||
return results;
|
||||
};
|
||||
|
||||
// If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
|
||||
// we need this function. Return the position of the first occurrence of an
|
||||
// item in an array, or -1 if the item is not included in the array.
|
||||
// Delegates to **ECMAScript 5**'s native `indexOf` if available.
|
||||
// If the array is large and already in sort order, pass `true`
|
||||
// for **isSorted** to use binary search.
|
||||
_.indexOf = function(array, item, isSorted) {
|
||||
if (array == null) return -1;
|
||||
var i, l;
|
||||
if (isSorted) {
|
||||
i = _.sortedIndex(array, item);
|
||||
return array[i] === item ? i : -1;
|
||||
}
|
||||
if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item);
|
||||
for (i = 0, l = array.length; i < l; i++) if (i in array && array[i] === item) return i;
|
||||
return -1;
|
||||
};
|
||||
|
||||
// Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
|
||||
_.lastIndexOf = function(array, item) {
|
||||
if (array == null) return -1;
|
||||
if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) return array.lastIndexOf(item);
|
||||
var i = array.length;
|
||||
while (i--) if (i in array && array[i] === item) return i;
|
||||
return -1;
|
||||
};
|
||||
|
||||
// Generate an integer Array containing an arithmetic progression. A port of
|
||||
// the native Python `range()` function. See
|
||||
// [the Python documentation](http://docs.python.org/library/functions.html#range).
|
||||
_.range = function(start, stop, step) {
|
||||
if (arguments.length <= 1) {
|
||||
stop = start || 0;
|
||||
start = 0;
|
||||
}
|
||||
step = arguments[2] || 1;
|
||||
|
||||
var len = Math.max(Math.ceil((stop - start) / step), 0);
|
||||
var idx = 0;
|
||||
var range = new Array(len);
|
||||
|
||||
while(idx < len) {
|
||||
range[idx++] = start;
|
||||
start += step;
|
||||
}
|
||||
|
||||
return range;
|
||||
};
|
||||
|
||||
// Function (ahem) Functions
|
||||
// ------------------
|
||||
|
||||
// Reusable constructor function for prototype setting.
|
||||
var ctor = function(){};
|
||||
|
||||
// Create a function bound to a given object (assigning `this`, and arguments,
|
||||
// optionally). Binding with arguments is also known as `curry`.
|
||||
// Delegates to **ECMAScript 5**'s native `Function.bind` if available.
|
||||
// We check for `func.bind` first, to fail fast when `func` is undefined.
|
||||
_.bind = function bind(func, context) {
|
||||
var bound, args;
|
||||
if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
|
||||
if (!_.isFunction(func)) throw new TypeError;
|
||||
args = slice.call(arguments, 2);
|
||||
return bound = function() {
|
||||
if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));
|
||||
ctor.prototype = func.prototype;
|
||||
var self = new ctor;
|
||||
var result = func.apply(self, args.concat(slice.call(arguments)));
|
||||
if (Object(result) === result) return result;
|
||||
return self;
|
||||
};
|
||||
};
|
||||
|
||||
// Bind all of an object's methods to that object. Useful for ensuring that
|
||||
// all callbacks defined on an object belong to it.
|
||||
_.bindAll = function(obj) {
|
||||
var funcs = slice.call(arguments, 1);
|
||||
if (funcs.length == 0) funcs = _.functions(obj);
|
||||
each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });
|
||||
return obj;
|
||||
};
|
||||
|
||||
// Memoize an expensive function by storing its results.
|
||||
_.memoize = function(func, hasher) {
|
||||
var memo = {};
|
||||
hasher || (hasher = _.identity);
|
||||
return function() {
|
||||
var key = hasher.apply(this, arguments);
|
||||
return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
|
||||
};
|
||||
};
|
||||
|
||||
// Delays a function for the given number of milliseconds, and then calls
|
||||
// it with the arguments supplied.
|
||||
_.delay = function(func, wait) {
|
||||
var args = slice.call(arguments, 2);
|
||||
return setTimeout(function(){ return func.apply(func, args); }, wait);
|
||||
};
|
||||
|
||||
// Defers a function, scheduling it to run after the current call stack has
|
||||
// cleared.
|
||||
_.defer = function(func) {
|
||||
return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
|
||||
};
|
||||
|
||||
// Returns a function, that, when invoked, will only be triggered at most once
|
||||
// during a given window of time.
|
||||
_.throttle = function(func, wait) {
|
||||
var context, args, timeout, throttling, more;
|
||||
var whenDone = _.debounce(function(){ more = throttling = false; }, wait);
|
||||
return function() {
|
||||
context = this; args = arguments;
|
||||
var later = function() {
|
||||
timeout = null;
|
||||
if (more) func.apply(context, args);
|
||||
whenDone();
|
||||
};
|
||||
if (!timeout) timeout = setTimeout(later, wait);
|
||||
if (throttling) {
|
||||
more = true;
|
||||
} else {
|
||||
func.apply(context, args);
|
||||
}
|
||||
whenDone();
|
||||
throttling = true;
|
||||
};
|
||||
};
|
||||
|
||||
// Returns a function, that, as long as it continues to be invoked, will not
|
||||
// be triggered. The function will be called after it stops being called for
|
||||
// N milliseconds.
|
||||
_.debounce = function(func, wait) {
|
||||
var timeout;
|
||||
return function() {
|
||||
var context = this, args = arguments;
|
||||
var later = function() {
|
||||
timeout = null;
|
||||
func.apply(context, args);
|
||||
};
|
||||
clearTimeout(timeout);
|
||||
timeout = setTimeout(later, wait);
|
||||
};
|
||||
};
|
||||
|
||||
// Returns a function that will be executed at most one time, no matter how
|
||||
// often you call it. Useful for lazy initialization.
|
||||
_.once = function(func) {
|
||||
var ran = false, memo;
|
||||
return function() {
|
||||
if (ran) return memo;
|
||||
ran = true;
|
||||
return memo = func.apply(this, arguments);
|
||||
};
|
||||
};
|
||||
|
||||
// Returns the first function passed as an argument to the second,
|
||||
// allowing you to adjust arguments, run code before and after, and
|
||||
// conditionally execute the original function.
|
||||
_.wrap = function(func, wrapper) {
|
||||
return function() {
|
||||
var args = [func].concat(slice.call(arguments, 0));
|
||||
return wrapper.apply(this, args);
|
||||
};
|
||||
};
|
||||
|
||||
// Returns a function that is the composition of a list of functions, each
|
||||
// consuming the return value of the function that follows.
|
||||
_.compose = function() {
|
||||
var funcs = arguments;
|
||||
return function() {
|
||||
var args = arguments;
|
||||
for (var i = funcs.length - 1; i >= 0; i--) {
|
||||
args = [funcs[i].apply(this, args)];
|
||||
}
|
||||
return args[0];
|
||||
};
|
||||
};
|
||||
|
||||
// Returns a function that will only be executed after being called N times.
|
||||
_.after = function(times, func) {
|
||||
if (times <= 0) return func();
|
||||
return function() {
|
||||
if (--times < 1) { return func.apply(this, arguments); }
|
||||
};
|
||||
};
|
||||
|
||||
// Object Functions
|
||||
// ----------------
|
||||
|
||||
// Retrieve the names of an object's properties.
|
||||
// Delegates to **ECMAScript 5**'s native `Object.keys`
|
||||
_.keys = nativeKeys || function(obj) {
|
||||
if (obj !== Object(obj)) throw new TypeError('Invalid object');
|
||||
var keys = [];
|
||||
for (var key in obj) if (_.has(obj, key)) keys[keys.length] = key;
|
||||
return keys;
|
||||
};
|
||||
|
||||
// Retrieve the values of an object's properties.
|
||||
_.values = function(obj) {
|
||||
return _.map(obj, _.identity);
|
||||
};
|
||||
|
||||
// Return a sorted list of the function names available on the object.
|
||||
// Aliased as `methods`
|
||||
_.functions = _.methods = function(obj) {
|
||||
var names = [];
|
||||
for (var key in obj) {
|
||||
if (_.isFunction(obj[key])) names.push(key);
|
||||
}
|
||||
return names.sort();
|
||||
};
|
||||
|
||||
// Extend a given object with all the properties in passed-in object(s).
|
||||
_.extend = function(obj) {
|
||||
each(slice.call(arguments, 1), function(source) {
|
||||
for (var prop in source) {
|
||||
obj[prop] = source[prop];
|
||||
}
|
||||
});
|
||||
return obj;
|
||||
};
|
||||
|
||||
// Fill in a given object with default properties.
|
||||
_.defaults = function(obj) {
|
||||
each(slice.call(arguments, 1), function(source) {
|
||||
for (var prop in source) {
|
||||
if (obj[prop] == null) obj[prop] = source[prop];
|
||||
}
|
||||
});
|
||||
return obj;
|
||||
};
|
||||
|
||||
// Create a (shallow-cloned) duplicate of an object.
|
||||
_.clone = function(obj) {
|
||||
if (!_.isObject(obj)) return obj;
|
||||
return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
|
||||
};
|
||||
|
||||
// Invokes interceptor with the obj, and then returns obj.
|
||||
// The primary purpose of this method is to "tap into" a method chain, in
|
||||
// order to perform operations on intermediate results within the chain.
|
||||
_.tap = function(obj, interceptor) {
|
||||
interceptor(obj);
|
||||
return obj;
|
||||
};
|
||||
|
||||
// Internal recursive comparison function.
|
||||
function eq(a, b, stack) {
|
||||
// Identical objects are equal. `0 === -0`, but they aren't identical.
|
||||
// See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal.
|
||||
if (a === b) return a !== 0 || 1 / a == 1 / b;
|
||||
// A strict comparison is necessary because `null == undefined`.
|
||||
if (a == null || b == null) return a === b;
|
||||
// Unwrap any wrapped objects.
|
||||
if (a._chain) a = a._wrapped;
|
||||
if (b._chain) b = b._wrapped;
|
||||
// Invoke a custom `isEqual` method if one is provided.
|
||||
if (a.isEqual && _.isFunction(a.isEqual)) return a.isEqual(b);
|
||||
if (b.isEqual && _.isFunction(b.isEqual)) return b.isEqual(a);
|
||||
// Compare `[[Class]]` names.
|
||||
var className = toString.call(a);
|
||||
if (className != toString.call(b)) return false;
|
||||
switch (className) {
|
||||
// Strings, numbers, dates, and booleans are compared by value.
|
||||
case '[object String]':
|
||||
// Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
|
||||
// equivalent to `new String("5")`.
|
||||
return a == String(b);
|
||||
case '[object Number]':
|
||||
// `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for
|
||||
// other numeric values.
|
||||
return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b);
|
||||
case '[object Date]':
|
||||
case '[object Boolean]':
|
||||
// Coerce dates and booleans to numeric primitive values. Dates are compared by their
|
||||
// millisecond representations. Note that invalid dates with millisecond representations
|
||||
// of `NaN` are not equivalent.
|
||||
return +a == +b;
|
||||
// RegExps are compared by their source patterns and flags.
|
||||
case '[object RegExp]':
|
||||
return a.source == b.source &&
|
||||
a.global == b.global &&
|
||||
a.multiline == b.multiline &&
|
||||
a.ignoreCase == b.ignoreCase;
|
||||
}
|
||||
if (typeof a != 'object' || typeof b != 'object') return false;
|
||||
// Assume equality for cyclic structures. The algorithm for detecting cyclic
|
||||
// structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
|
||||
var length = stack.length;
|
||||
while (length--) {
|
||||
// Linear search. Performance is inversely proportional to the number of
|
||||
// unique nested structures.
|
||||
if (stack[length] == a) return true;
|
||||
}
|
||||
// Add the first object to the stack of traversed objects.
|
||||
stack.push(a);
|
||||
var size = 0, result = true;
|
||||
// Recursively compare objects and arrays.
|
||||
if (className == '[object Array]') {
|
||||
// Compare array lengths to determine if a deep comparison is necessary.
|
||||
size = a.length;
|
||||
result = size == b.length;
|
||||
if (result) {
|
||||
// Deep compare the contents, ignoring non-numeric properties.
|
||||
while (size--) {
|
||||
// Ensure commutative equality for sparse arrays.
|
||||
if (!(result = size in a == size in b && eq(a[size], b[size], stack))) break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Objects with different constructors are not equivalent.
|
||||
if ('constructor' in a != 'constructor' in b || a.constructor != b.constructor) return false;
|
||||
// Deep compare objects.
|
||||
for (var key in a) {
|
||||
if (_.has(a, key)) {
|
||||
// Count the expected number of properties.
|
||||
size++;
|
||||
// Deep compare each member.
|
||||
if (!(result = _.has(b, key) && eq(a[key], b[key], stack))) break;
|
||||
}
|
||||
}
|
||||
// Ensure that both objects contain the same number of properties.
|
||||
if (result) {
|
||||
for (key in b) {
|
||||
if (_.has(b, key) && !(size--)) break;
|
||||
}
|
||||
result = !size;
|
||||
}
|
||||
}
|
||||
// Remove the first object from the stack of traversed objects.
|
||||
stack.pop();
|
||||
return result;
|
||||
}
|
||||
|
||||
// Perform a deep comparison to check if two objects are equal.
|
||||
_.isEqual = function(a, b) {
|
||||
return eq(a, b, []);
|
||||
};
|
||||
|
||||
// Is a given array, string, or object empty?
|
||||
// An "empty" object has no enumerable own-properties.
|
||||
_.isEmpty = function(obj) {
|
||||
if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
|
||||
for (var key in obj) if (_.has(obj, key)) return false;
|
||||
return true;
|
||||
};
|
||||
|
||||
// Is a given value a DOM element?
|
||||
_.isElement = function(obj) {
|
||||
return !!(obj && obj.nodeType == 1);
|
||||
};
|
||||
|
||||
// Is a given value an array?
|
||||
// Delegates to ECMA5's native Array.isArray
|
||||
_.isArray = nativeIsArray || function(obj) {
|
||||
return toString.call(obj) == '[object Array]';
|
||||
};
|
||||
|
||||
// Is a given variable an object?
|
||||
_.isObject = function(obj) {
|
||||
return obj === Object(obj);
|
||||
};
|
||||
|
||||
// Is a given variable an arguments object?
|
||||
_.isArguments = function(obj) {
|
||||
return toString.call(obj) == '[object Arguments]';
|
||||
};
|
||||
if (!_.isArguments(arguments)) {
|
||||
_.isArguments = function(obj) {
|
||||
return !!(obj && _.has(obj, 'callee'));
|
||||
};
|
||||
}
|
||||
|
||||
// Is a given value a function?
|
||||
_.isFunction = function(obj) {
|
||||
return toString.call(obj) == '[object Function]';
|
||||
};
|
||||
|
||||
// Is a given value a string?
|
||||
_.isString = function(obj) {
|
||||
return toString.call(obj) == '[object String]';
|
||||
};
|
||||
|
||||
// Is a given value a number?
|
||||
_.isNumber = function(obj) {
|
||||
return toString.call(obj) == '[object Number]';
|
||||
};
|
||||
|
||||
// Is the given value `NaN`?
|
||||
_.isNaN = function(obj) {
|
||||
// `NaN` is the only value for which `===` is not reflexive.
|
||||
return obj !== obj;
|
||||
};
|
||||
|
||||
// Is a given value a boolean?
|
||||
_.isBoolean = function(obj) {
|
||||
return obj === true || obj === false || toString.call(obj) == '[object Boolean]';
|
||||
};
|
||||
|
||||
// Is a given value a date?
|
||||
_.isDate = function(obj) {
|
||||
return toString.call(obj) == '[object Date]';
|
||||
};
|
||||
|
||||
// Is the given value a regular expression?
|
||||
_.isRegExp = function(obj) {
|
||||
return toString.call(obj) == '[object RegExp]';
|
||||
};
|
||||
|
||||
// Is a given value equal to null?
|
||||
_.isNull = function(obj) {
|
||||
return obj === null;
|
||||
};
|
||||
|
||||
// Is a given variable undefined?
|
||||
_.isUndefined = function(obj) {
|
||||
return obj === void 0;
|
||||
};
|
||||
|
||||
// Has own property?
|
||||
_.has = function(obj, key) {
|
||||
return hasOwnProperty.call(obj, key);
|
||||
};
|
||||
|
||||
// Utility Functions
|
||||
// -----------------
|
||||
|
||||
// Run Underscore.js in *noConflict* mode, returning the `_` variable to its
|
||||
// previous owner. Returns a reference to the Underscore object.
|
||||
_.noConflict = function() {
|
||||
root._ = previousUnderscore;
|
||||
return this;
|
||||
};
|
||||
|
||||
// Keep the identity function around for default iterators.
|
||||
_.identity = function(value) {
|
||||
return value;
|
||||
};
|
||||
|
||||
// Run a function **n** times.
|
||||
_.times = function (n, iterator, context) {
|
||||
for (var i = 0; i < n; i++) iterator.call(context, i);
|
||||
};
|
||||
|
||||
// Escape a string for HTML interpolation.
|
||||
_.escape = function(string) {
|
||||
return (''+string).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''').replace(/\//g,'/');
|
||||
};
|
||||
|
||||
// Add your own custom functions to the Underscore object, ensuring that
|
||||
// they're correctly added to the OOP wrapper as well.
|
||||
_.mixin = function(obj) {
|
||||
each(_.functions(obj), function(name){
|
||||
addToWrapper(name, _[name] = obj[name]);
|
||||
});
|
||||
};
|
||||
|
||||
// Generate a unique integer id (unique within the entire client session).
|
||||
// Useful for temporary DOM ids.
|
||||
var idCounter = 0;
|
||||
_.uniqueId = function(prefix) {
|
||||
var id = idCounter++;
|
||||
return prefix ? prefix + id : id;
|
||||
};
|
||||
|
||||
// By default, Underscore uses ERB-style template delimiters, change the
|
||||
// following template settings to use alternative delimiters.
|
||||
_.templateSettings = {
|
||||
evaluate : /<%([\s\S]+?)%>/g,
|
||||
interpolate : /<%=([\s\S]+?)%>/g,
|
||||
escape : /<%-([\s\S]+?)%>/g
|
||||
};
|
||||
|
||||
// When customizing `templateSettings`, if you don't want to define an
|
||||
// interpolation, evaluation or escaping regex, we need one that is
|
||||
// guaranteed not to match.
|
||||
var noMatch = /.^/;
|
||||
|
||||
// Within an interpolation, evaluation, or escaping, remove HTML escaping
|
||||
// that had been previously added.
|
||||
var unescape = function(code) {
|
||||
return code.replace(/\\\\/g, '\\').replace(/\\'/g, "'");
|
||||
};
|
||||
|
||||
// JavaScript micro-templating, similar to John Resig's implementation.
|
||||
// Underscore templating handles arbitrary delimiters, preserves whitespace,
|
||||
// and correctly escapes quotes within interpolated code.
|
||||
_.template = function(str, data) {
|
||||
var c = _.templateSettings;
|
||||
var tmpl = 'var __p=[],print=function(){__p.push.apply(__p,arguments);};' +
|
||||
'with(obj||{}){__p.push(\'' +
|
||||
str.replace(/\\/g, '\\\\')
|
||||
.replace(/'/g, "\\'")
|
||||
.replace(c.escape || noMatch, function(match, code) {
|
||||
return "',_.escape(" + unescape(code) + "),'";
|
||||
})
|
||||
.replace(c.interpolate || noMatch, function(match, code) {
|
||||
return "'," + unescape(code) + ",'";
|
||||
})
|
||||
.replace(c.evaluate || noMatch, function(match, code) {
|
||||
return "');" + unescape(code).replace(/[\r\n\t]/g, ' ') + ";__p.push('";
|
||||
})
|
||||
.replace(/\r/g, '\\r')
|
||||
.replace(/\n/g, '\\n')
|
||||
.replace(/\t/g, '\\t')
|
||||
+ "');}return __p.join('');";
|
||||
var func = new Function('obj', '_', tmpl);
|
||||
if (data) return func(data, _);
|
||||
return function(data) {
|
||||
return func.call(this, data, _);
|
||||
};
|
||||
};
|
||||
|
||||
// Add a "chain" function, which will delegate to the wrapper.
|
||||
_.chain = function(obj) {
|
||||
return _(obj).chain();
|
||||
};
|
||||
|
||||
// The OOP Wrapper
|
||||
// ---------------
|
||||
|
||||
// If Underscore is called as a function, it returns a wrapped object that
|
||||
// can be used OO-style. This wrapper holds altered versions of all the
|
||||
// underscore functions. Wrapped objects may be chained.
|
||||
var wrapper = function(obj) { this._wrapped = obj; };
|
||||
|
||||
// Expose `wrapper.prototype` as `_.prototype`
|
||||
_.prototype = wrapper.prototype;
|
||||
|
||||
// Helper function to continue chaining intermediate results.
|
||||
var result = function(obj, chain) {
|
||||
return chain ? _(obj).chain() : obj;
|
||||
};
|
||||
|
||||
// A method to easily add functions to the OOP wrapper.
|
||||
var addToWrapper = function(name, func) {
|
||||
wrapper.prototype[name] = function() {
|
||||
var args = slice.call(arguments);
|
||||
unshift.call(args, this._wrapped);
|
||||
return result(func.apply(_, args), this._chain);
|
||||
};
|
||||
};
|
||||
|
||||
// Add all of the Underscore functions to the wrapper object.
|
||||
_.mixin(_);
|
||||
|
||||
// Add all mutator Array functions to the wrapper.
|
||||
each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
|
||||
var method = ArrayProto[name];
|
||||
wrapper.prototype[name] = function() {
|
||||
var wrapped = this._wrapped;
|
||||
method.apply(wrapped, arguments);
|
||||
var length = wrapped.length;
|
||||
if ((name == 'shift' || name == 'splice') && length === 0) delete wrapped[0];
|
||||
return result(wrapped, this._chain);
|
||||
};
|
||||
});
|
||||
|
||||
// Add all accessor Array functions to the wrapper.
|
||||
each(['concat', 'join', 'slice'], function(name) {
|
||||
var method = ArrayProto[name];
|
||||
wrapper.prototype[name] = function() {
|
||||
return result(method.apply(this._wrapped, arguments), this._chain);
|
||||
};
|
||||
});
|
||||
|
||||
// Start chaining a wrapped Underscore object.
|
||||
wrapper.prototype.chain = function() {
|
||||
this._chain = true;
|
||||
return this;
|
||||
};
|
||||
|
||||
// Extracts the result from a wrapped and chained object.
|
||||
wrapper.prototype.value = function() {
|
||||
return this._wrapped;
|
||||
};
|
||||
|
||||
}).call(this);
|
||||
@@ -0,0 +1,31 @@
|
||||
// Underscore.js 1.3.1
|
||||
// (c) 2009-2012 Jeremy Ashkenas, DocumentCloud Inc.
|
||||
// Underscore is freely distributable under the MIT license.
|
||||
// Portions of Underscore are inspired or borrowed from Prototype,
|
||||
// Oliver Steele's Functional, and John Resig's Micro-Templating.
|
||||
// For all details and documentation:
|
||||
// http://documentcloud.github.com/underscore
|
||||
(function(){function q(a,c,d){if(a===c)return a!==0||1/a==1/c;if(a==null||c==null)return a===c;if(a._chain)a=a._wrapped;if(c._chain)c=c._wrapped;if(a.isEqual&&b.isFunction(a.isEqual))return a.isEqual(c);if(c.isEqual&&b.isFunction(c.isEqual))return c.isEqual(a);var e=l.call(a);if(e!=l.call(c))return false;switch(e){case "[object String]":return a==String(c);case "[object Number]":return a!=+a?c!=+c:a==0?1/a==1/c:a==+c;case "[object Date]":case "[object Boolean]":return+a==+c;case "[object RegExp]":return a.source==
|
||||
c.source&&a.global==c.global&&a.multiline==c.multiline&&a.ignoreCase==c.ignoreCase}if(typeof a!="object"||typeof c!="object")return false;for(var f=d.length;f--;)if(d[f]==a)return true;d.push(a);var f=0,g=true;if(e=="[object Array]"){if(f=a.length,g=f==c.length)for(;f--;)if(!(g=f in a==f in c&&q(a[f],c[f],d)))break}else{if("constructor"in a!="constructor"in c||a.constructor!=c.constructor)return false;for(var h in a)if(b.has(a,h)&&(f++,!(g=b.has(c,h)&&q(a[h],c[h],d))))break;if(g){for(h in c)if(b.has(c,
|
||||
h)&&!f--)break;g=!f}}d.pop();return g}var r=this,G=r._,n={},k=Array.prototype,o=Object.prototype,i=k.slice,H=k.unshift,l=o.toString,I=o.hasOwnProperty,w=k.forEach,x=k.map,y=k.reduce,z=k.reduceRight,A=k.filter,B=k.every,C=k.some,p=k.indexOf,D=k.lastIndexOf,o=Array.isArray,J=Object.keys,s=Function.prototype.bind,b=function(a){return new m(a)};if(typeof exports!=="undefined"){if(typeof module!=="undefined"&&module.exports)exports=module.exports=b;exports._=b}else r._=b;b.VERSION="1.3.1";var j=b.each=
|
||||
b.forEach=function(a,c,d){if(a!=null)if(w&&a.forEach===w)a.forEach(c,d);else if(a.length===+a.length)for(var e=0,f=a.length;e<f;e++){if(e in a&&c.call(d,a[e],e,a)===n)break}else for(e in a)if(b.has(a,e)&&c.call(d,a[e],e,a)===n)break};b.map=b.collect=function(a,c,b){var e=[];if(a==null)return e;if(x&&a.map===x)return a.map(c,b);j(a,function(a,g,h){e[e.length]=c.call(b,a,g,h)});if(a.length===+a.length)e.length=a.length;return e};b.reduce=b.foldl=b.inject=function(a,c,d,e){var f=arguments.length>2;a==
|
||||
null&&(a=[]);if(y&&a.reduce===y)return e&&(c=b.bind(c,e)),f?a.reduce(c,d):a.reduce(c);j(a,function(a,b,i){f?d=c.call(e,d,a,b,i):(d=a,f=true)});if(!f)throw new TypeError("Reduce of empty array with no initial value");return d};b.reduceRight=b.foldr=function(a,c,d,e){var f=arguments.length>2;a==null&&(a=[]);if(z&&a.reduceRight===z)return e&&(c=b.bind(c,e)),f?a.reduceRight(c,d):a.reduceRight(c);var g=b.toArray(a).reverse();e&&!f&&(c=b.bind(c,e));return f?b.reduce(g,c,d,e):b.reduce(g,c)};b.find=b.detect=
|
||||
function(a,c,b){var e;E(a,function(a,g,h){if(c.call(b,a,g,h))return e=a,true});return e};b.filter=b.select=function(a,c,b){var e=[];if(a==null)return e;if(A&&a.filter===A)return a.filter(c,b);j(a,function(a,g,h){c.call(b,a,g,h)&&(e[e.length]=a)});return e};b.reject=function(a,c,b){var e=[];if(a==null)return e;j(a,function(a,g,h){c.call(b,a,g,h)||(e[e.length]=a)});return e};b.every=b.all=function(a,c,b){var e=true;if(a==null)return e;if(B&&a.every===B)return a.every(c,b);j(a,function(a,g,h){if(!(e=
|
||||
e&&c.call(b,a,g,h)))return n});return e};var E=b.some=b.any=function(a,c,d){c||(c=b.identity);var e=false;if(a==null)return e;if(C&&a.some===C)return a.some(c,d);j(a,function(a,b,h){if(e||(e=c.call(d,a,b,h)))return n});return!!e};b.include=b.contains=function(a,c){var b=false;if(a==null)return b;return p&&a.indexOf===p?a.indexOf(c)!=-1:b=E(a,function(a){return a===c})};b.invoke=function(a,c){var d=i.call(arguments,2);return b.map(a,function(a){return(b.isFunction(c)?c||a:a[c]).apply(a,d)})};b.pluck=
|
||||
function(a,c){return b.map(a,function(a){return a[c]})};b.max=function(a,c,d){if(!c&&b.isArray(a))return Math.max.apply(Math,a);if(!c&&b.isEmpty(a))return-Infinity;var e={computed:-Infinity};j(a,function(a,b,h){b=c?c.call(d,a,b,h):a;b>=e.computed&&(e={value:a,computed:b})});return e.value};b.min=function(a,c,d){if(!c&&b.isArray(a))return Math.min.apply(Math,a);if(!c&&b.isEmpty(a))return Infinity;var e={computed:Infinity};j(a,function(a,b,h){b=c?c.call(d,a,b,h):a;b<e.computed&&(e={value:a,computed:b})});
|
||||
return e.value};b.shuffle=function(a){var b=[],d;j(a,function(a,f){f==0?b[0]=a:(d=Math.floor(Math.random()*(f+1)),b[f]=b[d],b[d]=a)});return b};b.sortBy=function(a,c,d){return b.pluck(b.map(a,function(a,b,g){return{value:a,criteria:c.call(d,a,b,g)}}).sort(function(a,b){var c=a.criteria,d=b.criteria;return c<d?-1:c>d?1:0}),"value")};b.groupBy=function(a,c){var d={},e=b.isFunction(c)?c:function(a){return a[c]};j(a,function(a,b){var c=e(a,b);(d[c]||(d[c]=[])).push(a)});return d};b.sortedIndex=function(a,
|
||||
c,d){d||(d=b.identity);for(var e=0,f=a.length;e<f;){var g=e+f>>1;d(a[g])<d(c)?e=g+1:f=g}return e};b.toArray=function(a){return!a?[]:a.toArray?a.toArray():b.isArray(a)?i.call(a):b.isArguments(a)?i.call(a):b.values(a)};b.size=function(a){return b.toArray(a).length};b.first=b.head=function(a,b,d){return b!=null&&!d?i.call(a,0,b):a[0]};b.initial=function(a,b,d){return i.call(a,0,a.length-(b==null||d?1:b))};b.last=function(a,b,d){return b!=null&&!d?i.call(a,Math.max(a.length-b,0)):a[a.length-1]};b.rest=
|
||||
b.tail=function(a,b,d){return i.call(a,b==null||d?1:b)};b.compact=function(a){return b.filter(a,function(a){return!!a})};b.flatten=function(a,c){return b.reduce(a,function(a,e){if(b.isArray(e))return a.concat(c?e:b.flatten(e));a[a.length]=e;return a},[])};b.without=function(a){return b.difference(a,i.call(arguments,1))};b.uniq=b.unique=function(a,c,d){var d=d?b.map(a,d):a,e=[];b.reduce(d,function(d,g,h){if(0==h||(c===true?b.last(d)!=g:!b.include(d,g)))d[d.length]=g,e[e.length]=a[h];return d},[]);
|
||||
return e};b.union=function(){return b.uniq(b.flatten(arguments,true))};b.intersection=b.intersect=function(a){var c=i.call(arguments,1);return b.filter(b.uniq(a),function(a){return b.every(c,function(c){return b.indexOf(c,a)>=0})})};b.difference=function(a){var c=b.flatten(i.call(arguments,1));return b.filter(a,function(a){return!b.include(c,a)})};b.zip=function(){for(var a=i.call(arguments),c=b.max(b.pluck(a,"length")),d=Array(c),e=0;e<c;e++)d[e]=b.pluck(a,""+e);return d};b.indexOf=function(a,c,
|
||||
d){if(a==null)return-1;var e;if(d)return d=b.sortedIndex(a,c),a[d]===c?d:-1;if(p&&a.indexOf===p)return a.indexOf(c);for(d=0,e=a.length;d<e;d++)if(d in a&&a[d]===c)return d;return-1};b.lastIndexOf=function(a,b){if(a==null)return-1;if(D&&a.lastIndexOf===D)return a.lastIndexOf(b);for(var d=a.length;d--;)if(d in a&&a[d]===b)return d;return-1};b.range=function(a,b,d){arguments.length<=1&&(b=a||0,a=0);for(var d=arguments[2]||1,e=Math.max(Math.ceil((b-a)/d),0),f=0,g=Array(e);f<e;)g[f++]=a,a+=d;return g};
|
||||
var F=function(){};b.bind=function(a,c){var d,e;if(a.bind===s&&s)return s.apply(a,i.call(arguments,1));if(!b.isFunction(a))throw new TypeError;e=i.call(arguments,2);return d=function(){if(!(this instanceof d))return a.apply(c,e.concat(i.call(arguments)));F.prototype=a.prototype;var b=new F,g=a.apply(b,e.concat(i.call(arguments)));return Object(g)===g?g:b}};b.bindAll=function(a){var c=i.call(arguments,1);c.length==0&&(c=b.functions(a));j(c,function(c){a[c]=b.bind(a[c],a)});return a};b.memoize=function(a,
|
||||
c){var d={};c||(c=b.identity);return function(){var e=c.apply(this,arguments);return b.has(d,e)?d[e]:d[e]=a.apply(this,arguments)}};b.delay=function(a,b){var d=i.call(arguments,2);return setTimeout(function(){return a.apply(a,d)},b)};b.defer=function(a){return b.delay.apply(b,[a,1].concat(i.call(arguments,1)))};b.throttle=function(a,c){var d,e,f,g,h,i=b.debounce(function(){h=g=false},c);return function(){d=this;e=arguments;var b;f||(f=setTimeout(function(){f=null;h&&a.apply(d,e);i()},c));g?h=true:
|
||||
a.apply(d,e);i();g=true}};b.debounce=function(a,b){var d;return function(){var e=this,f=arguments;clearTimeout(d);d=setTimeout(function(){d=null;a.apply(e,f)},b)}};b.once=function(a){var b=false,d;return function(){if(b)return d;b=true;return d=a.apply(this,arguments)}};b.wrap=function(a,b){return function(){var d=[a].concat(i.call(arguments,0));return b.apply(this,d)}};b.compose=function(){var a=arguments;return function(){for(var b=arguments,d=a.length-1;d>=0;d--)b=[a[d].apply(this,b)];return b[0]}};
|
||||
b.after=function(a,b){return a<=0?b():function(){if(--a<1)return b.apply(this,arguments)}};b.keys=J||function(a){if(a!==Object(a))throw new TypeError("Invalid object");var c=[],d;for(d in a)b.has(a,d)&&(c[c.length]=d);return c};b.values=function(a){return b.map(a,b.identity)};b.functions=b.methods=function(a){var c=[],d;for(d in a)b.isFunction(a[d])&&c.push(d);return c.sort()};b.extend=function(a){j(i.call(arguments,1),function(b){for(var d in b)a[d]=b[d]});return a};b.defaults=function(a){j(i.call(arguments,
|
||||
1),function(b){for(var d in b)a[d]==null&&(a[d]=b[d])});return a};b.clone=function(a){return!b.isObject(a)?a:b.isArray(a)?a.slice():b.extend({},a)};b.tap=function(a,b){b(a);return a};b.isEqual=function(a,b){return q(a,b,[])};b.isEmpty=function(a){if(b.isArray(a)||b.isString(a))return a.length===0;for(var c in a)if(b.has(a,c))return false;return true};b.isElement=function(a){return!!(a&&a.nodeType==1)};b.isArray=o||function(a){return l.call(a)=="[object Array]"};b.isObject=function(a){return a===Object(a)};
|
||||
b.isArguments=function(a){return l.call(a)=="[object Arguments]"};if(!b.isArguments(arguments))b.isArguments=function(a){return!(!a||!b.has(a,"callee"))};b.isFunction=function(a){return l.call(a)=="[object Function]"};b.isString=function(a){return l.call(a)=="[object String]"};b.isNumber=function(a){return l.call(a)=="[object Number]"};b.isNaN=function(a){return a!==a};b.isBoolean=function(a){return a===true||a===false||l.call(a)=="[object Boolean]"};b.isDate=function(a){return l.call(a)=="[object Date]"};
|
||||
b.isRegExp=function(a){return l.call(a)=="[object RegExp]"};b.isNull=function(a){return a===null};b.isUndefined=function(a){return a===void 0};b.has=function(a,b){return I.call(a,b)};b.noConflict=function(){r._=G;return this};b.identity=function(a){return a};b.times=function(a,b,d){for(var e=0;e<a;e++)b.call(d,e)};b.escape=function(a){return(""+a).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'").replace(/\//g,"/")};b.mixin=function(a){j(b.functions(a),
|
||||
function(c){K(c,b[c]=a[c])})};var L=0;b.uniqueId=function(a){var b=L++;return a?a+b:b};b.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var t=/.^/,u=function(a){return a.replace(/\\\\/g,"\\").replace(/\\'/g,"'")};b.template=function(a,c){var d=b.templateSettings,d="var __p=[],print=function(){__p.push.apply(__p,arguments);};with(obj||{}){__p.push('"+a.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(d.escape||t,function(a,b){return"',_.escape("+
|
||||
u(b)+"),'"}).replace(d.interpolate||t,function(a,b){return"',"+u(b)+",'"}).replace(d.evaluate||t,function(a,b){return"');"+u(b).replace(/[\r\n\t]/g," ")+";__p.push('"}).replace(/\r/g,"\\r").replace(/\n/g,"\\n").replace(/\t/g,"\\t")+"');}return __p.join('');",e=new Function("obj","_",d);return c?e(c,b):function(a){return e.call(this,a,b)}};b.chain=function(a){return b(a).chain()};var m=function(a){this._wrapped=a};b.prototype=m.prototype;var v=function(a,c){return c?b(a).chain():a},K=function(a,c){m.prototype[a]=
|
||||
function(){var a=i.call(arguments);H.call(a,this._wrapped);return v(c.apply(b,a),this._chain)}};b.mixin(b);j("pop,push,reverse,shift,sort,splice,unshift".split(","),function(a){var b=k[a];m.prototype[a]=function(){var d=this._wrapped;b.apply(d,arguments);var e=d.length;(a=="shift"||a=="splice")&&e===0&&delete d[0];return v(d,this._chain)}});j(["concat","join","slice"],function(a){var b=k[a];m.prototype[a]=function(){return v(b.apply(this._wrapped,arguments),this._chain)}});m.prototype.chain=function(){this._chain=
|
||||
true;return this};m.prototype.value=function(){return this._wrapped}}).call(this);
|
||||
|
After Width: | Height: | Size: 214 B |
|
After Width: | Height: | Size: 203 B |
|
After Width: | Height: | Size: 116 B |
@@ -0,0 +1,808 @@
|
||||
/*
|
||||
* websupport.js
|
||||
* ~~~~~~~~~~~~~
|
||||
*
|
||||
* sphinx.websupport utilities for all documentation.
|
||||
*
|
||||
* :copyright: Copyright 2007-2017 by the Sphinx team, see AUTHORS.
|
||||
* :license: BSD, see LICENSE for details.
|
||||
*
|
||||
*/
|
||||
|
||||
(function($) {
|
||||
$.fn.autogrow = function() {
|
||||
return this.each(function() {
|
||||
var textarea = this;
|
||||
|
||||
$.fn.autogrow.resize(textarea);
|
||||
|
||||
$(textarea)
|
||||
.focus(function() {
|
||||
textarea.interval = setInterval(function() {
|
||||
$.fn.autogrow.resize(textarea);
|
||||
}, 500);
|
||||
})
|
||||
.blur(function() {
|
||||
clearInterval(textarea.interval);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
$.fn.autogrow.resize = function(textarea) {
|
||||
var lineHeight = parseInt($(textarea).css('line-height'), 10);
|
||||
var lines = textarea.value.split('\n');
|
||||
var columns = textarea.cols;
|
||||
var lineCount = 0;
|
||||
$.each(lines, function() {
|
||||
lineCount += Math.ceil(this.length / columns) || 1;
|
||||
});
|
||||
var height = lineHeight * (lineCount + 1);
|
||||
$(textarea).css('height', height);
|
||||
};
|
||||
})(jQuery);
|
||||
|
||||
(function($) {
|
||||
var comp, by;
|
||||
|
||||
function init() {
|
||||
initEvents();
|
||||
initComparator();
|
||||
}
|
||||
|
||||
function initEvents() {
|
||||
$(document).on("click", 'a.comment-close', function(event) {
|
||||
event.preventDefault();
|
||||
hide($(this).attr('id').substring(2));
|
||||
});
|
||||
$(document).on("click", 'a.vote', function(event) {
|
||||
event.preventDefault();
|
||||
handleVote($(this));
|
||||
});
|
||||
$(document).on("click", 'a.reply', function(event) {
|
||||
event.preventDefault();
|
||||
openReply($(this).attr('id').substring(2));
|
||||
});
|
||||
$(document).on("click", 'a.close-reply', function(event) {
|
||||
event.preventDefault();
|
||||
closeReply($(this).attr('id').substring(2));
|
||||
});
|
||||
$(document).on("click", 'a.sort-option', function(event) {
|
||||
event.preventDefault();
|
||||
handleReSort($(this));
|
||||
});
|
||||
$(document).on("click", 'a.show-proposal', function(event) {
|
||||
event.preventDefault();
|
||||
showProposal($(this).attr('id').substring(2));
|
||||
});
|
||||
$(document).on("click", 'a.hide-proposal', function(event) {
|
||||
event.preventDefault();
|
||||
hideProposal($(this).attr('id').substring(2));
|
||||
});
|
||||
$(document).on("click", 'a.show-propose-change', function(event) {
|
||||
event.preventDefault();
|
||||
showProposeChange($(this).attr('id').substring(2));
|
||||
});
|
||||
$(document).on("click", 'a.hide-propose-change', function(event) {
|
||||
event.preventDefault();
|
||||
hideProposeChange($(this).attr('id').substring(2));
|
||||
});
|
||||
$(document).on("click", 'a.accept-comment', function(event) {
|
||||
event.preventDefault();
|
||||
acceptComment($(this).attr('id').substring(2));
|
||||
});
|
||||
$(document).on("click", 'a.delete-comment', function(event) {
|
||||
event.preventDefault();
|
||||
deleteComment($(this).attr('id').substring(2));
|
||||
});
|
||||
$(document).on("click", 'a.comment-markup', function(event) {
|
||||
event.preventDefault();
|
||||
toggleCommentMarkupBox($(this).attr('id').substring(2));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Set comp, which is a comparator function used for sorting and
|
||||
* inserting comments into the list.
|
||||
*/
|
||||
function setComparator() {
|
||||
// If the first three letters are "asc", sort in ascending order
|
||||
// and remove the prefix.
|
||||
if (by.substring(0,3) == 'asc') {
|
||||
var i = by.substring(3);
|
||||
comp = function(a, b) { return a[i] - b[i]; };
|
||||
} else {
|
||||
// Otherwise sort in descending order.
|
||||
comp = function(a, b) { return b[by] - a[by]; };
|
||||
}
|
||||
|
||||
// Reset link styles and format the selected sort option.
|
||||
$('a.sel').attr('href', '#').removeClass('sel');
|
||||
$('a.by' + by).removeAttr('href').addClass('sel');
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a comp function. If the user has preferences stored in
|
||||
* the sortBy cookie, use those, otherwise use the default.
|
||||
*/
|
||||
function initComparator() {
|
||||
by = 'rating'; // Default to sort by rating.
|
||||
// If the sortBy cookie is set, use that instead.
|
||||
if (document.cookie.length > 0) {
|
||||
var start = document.cookie.indexOf('sortBy=');
|
||||
if (start != -1) {
|
||||
start = start + 7;
|
||||
var end = document.cookie.indexOf(";", start);
|
||||
if (end == -1) {
|
||||
end = document.cookie.length;
|
||||
by = unescape(document.cookie.substring(start, end));
|
||||
}
|
||||
}
|
||||
}
|
||||
setComparator();
|
||||
}
|
||||
|
||||
/**
|
||||
* Show a comment div.
|
||||
*/
|
||||
function show(id) {
|
||||
$('#ao' + id).hide();
|
||||
$('#ah' + id).show();
|
||||
var context = $.extend({id: id}, opts);
|
||||
var popup = $(renderTemplate(popupTemplate, context)).hide();
|
||||
popup.find('textarea[name="proposal"]').hide();
|
||||
popup.find('a.by' + by).addClass('sel');
|
||||
var form = popup.find('#cf' + id);
|
||||
form.submit(function(event) {
|
||||
event.preventDefault();
|
||||
addComment(form);
|
||||
});
|
||||
$('#s' + id).after(popup);
|
||||
popup.slideDown('fast', function() {
|
||||
getComments(id);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Hide a comment div.
|
||||
*/
|
||||
function hide(id) {
|
||||
$('#ah' + id).hide();
|
||||
$('#ao' + id).show();
|
||||
var div = $('#sc' + id);
|
||||
div.slideUp('fast', function() {
|
||||
div.remove();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform an ajax request to get comments for a node
|
||||
* and insert the comments into the comments tree.
|
||||
*/
|
||||
function getComments(id) {
|
||||
$.ajax({
|
||||
type: 'GET',
|
||||
url: opts.getCommentsURL,
|
||||
data: {node: id},
|
||||
success: function(data, textStatus, request) {
|
||||
var ul = $('#cl' + id);
|
||||
var speed = 100;
|
||||
$('#cf' + id)
|
||||
.find('textarea[name="proposal"]')
|
||||
.data('source', data.source);
|
||||
|
||||
if (data.comments.length === 0) {
|
||||
ul.html('<li>No comments yet.</li>');
|
||||
ul.data('empty', true);
|
||||
} else {
|
||||
// If there are comments, sort them and put them in the list.
|
||||
var comments = sortComments(data.comments);
|
||||
speed = data.comments.length * 100;
|
||||
appendComments(comments, ul);
|
||||
ul.data('empty', false);
|
||||
}
|
||||
$('#cn' + id).slideUp(speed + 200);
|
||||
ul.slideDown(speed);
|
||||
},
|
||||
error: function(request, textStatus, error) {
|
||||
showError('Oops, there was a problem retrieving the comments.');
|
||||
},
|
||||
dataType: 'json'
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a comment via ajax and insert the comment into the comment tree.
|
||||
*/
|
||||
function addComment(form) {
|
||||
var node_id = form.find('input[name="node"]').val();
|
||||
var parent_id = form.find('input[name="parent"]').val();
|
||||
var text = form.find('textarea[name="comment"]').val();
|
||||
var proposal = form.find('textarea[name="proposal"]').val();
|
||||
|
||||
if (text == '') {
|
||||
showError('Please enter a comment.');
|
||||
return;
|
||||
}
|
||||
|
||||
// Disable the form that is being submitted.
|
||||
form.find('textarea,input').attr('disabled', 'disabled');
|
||||
|
||||
// Send the comment to the server.
|
||||
$.ajax({
|
||||
type: "POST",
|
||||
url: opts.addCommentURL,
|
||||
dataType: 'json',
|
||||
data: {
|
||||
node: node_id,
|
||||
parent: parent_id,
|
||||
text: text,
|
||||
proposal: proposal
|
||||
},
|
||||
success: function(data, textStatus, error) {
|
||||
// Reset the form.
|
||||
if (node_id) {
|
||||
hideProposeChange(node_id);
|
||||
}
|
||||
form.find('textarea')
|
||||
.val('')
|
||||
.add(form.find('input'))
|
||||
.removeAttr('disabled');
|
||||
var ul = $('#cl' + (node_id || parent_id));
|
||||
if (ul.data('empty')) {
|
||||
$(ul).empty();
|
||||
ul.data('empty', false);
|
||||
}
|
||||
insertComment(data.comment);
|
||||
var ao = $('#ao' + node_id);
|
||||
ao.find('img').attr({'src': opts.commentBrightImage});
|
||||
if (node_id) {
|
||||
// if this was a "root" comment, remove the commenting box
|
||||
// (the user can get it back by reopening the comment popup)
|
||||
$('#ca' + node_id).slideUp();
|
||||
}
|
||||
},
|
||||
error: function(request, textStatus, error) {
|
||||
form.find('textarea,input').removeAttr('disabled');
|
||||
showError('Oops, there was a problem adding the comment.');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively append comments to the main comment list and children
|
||||
* lists, creating the comment tree.
|
||||
*/
|
||||
function appendComments(comments, ul) {
|
||||
$.each(comments, function() {
|
||||
var div = createCommentDiv(this);
|
||||
ul.append($(document.createElement('li')).html(div));
|
||||
appendComments(this.children, div.find('ul.comment-children'));
|
||||
// To avoid stagnating data, don't store the comments children in data.
|
||||
this.children = null;
|
||||
div.data('comment', this);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* After adding a new comment, it must be inserted in the correct
|
||||
* location in the comment tree.
|
||||
*/
|
||||
function insertComment(comment) {
|
||||
var div = createCommentDiv(comment);
|
||||
|
||||
// To avoid stagnating data, don't store the comments children in data.
|
||||
comment.children = null;
|
||||
div.data('comment', comment);
|
||||
|
||||
var ul = $('#cl' + (comment.node || comment.parent));
|
||||
var siblings = getChildren(ul);
|
||||
|
||||
var li = $(document.createElement('li'));
|
||||
li.hide();
|
||||
|
||||
// Determine where in the parents children list to insert this comment.
|
||||
for(i=0; i < siblings.length; i++) {
|
||||
if (comp(comment, siblings[i]) <= 0) {
|
||||
$('#cd' + siblings[i].id)
|
||||
.parent()
|
||||
.before(li.html(div));
|
||||
li.slideDown('fast');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// If we get here, this comment rates lower than all the others,
|
||||
// or it is the only comment in the list.
|
||||
ul.append(li.html(div));
|
||||
li.slideDown('fast');
|
||||
}
|
||||
|
||||
function acceptComment(id) {
|
||||
$.ajax({
|
||||
type: 'POST',
|
||||
url: opts.acceptCommentURL,
|
||||
data: {id: id},
|
||||
success: function(data, textStatus, request) {
|
||||
$('#cm' + id).fadeOut('fast');
|
||||
$('#cd' + id).removeClass('moderate');
|
||||
},
|
||||
error: function(request, textStatus, error) {
|
||||
showError('Oops, there was a problem accepting the comment.');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function deleteComment(id) {
|
||||
$.ajax({
|
||||
type: 'POST',
|
||||
url: opts.deleteCommentURL,
|
||||
data: {id: id},
|
||||
success: function(data, textStatus, request) {
|
||||
var div = $('#cd' + id);
|
||||
if (data == 'delete') {
|
||||
// Moderator mode: remove the comment and all children immediately
|
||||
div.slideUp('fast', function() {
|
||||
div.remove();
|
||||
});
|
||||
return;
|
||||
}
|
||||
// User mode: only mark the comment as deleted
|
||||
div
|
||||
.find('span.user-id:first')
|
||||
.text('[deleted]').end()
|
||||
.find('div.comment-text:first')
|
||||
.text('[deleted]').end()
|
||||
.find('#cm' + id + ', #dc' + id + ', #ac' + id + ', #rc' + id +
|
||||
', #sp' + id + ', #hp' + id + ', #cr' + id + ', #rl' + id)
|
||||
.remove();
|
||||
var comment = div.data('comment');
|
||||
comment.username = '[deleted]';
|
||||
comment.text = '[deleted]';
|
||||
div.data('comment', comment);
|
||||
},
|
||||
error: function(request, textStatus, error) {
|
||||
showError('Oops, there was a problem deleting the comment.');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function showProposal(id) {
|
||||
$('#sp' + id).hide();
|
||||
$('#hp' + id).show();
|
||||
$('#pr' + id).slideDown('fast');
|
||||
}
|
||||
|
||||
function hideProposal(id) {
|
||||
$('#hp' + id).hide();
|
||||
$('#sp' + id).show();
|
||||
$('#pr' + id).slideUp('fast');
|
||||
}
|
||||
|
||||
function showProposeChange(id) {
|
||||
$('#pc' + id).hide();
|
||||
$('#hc' + id).show();
|
||||
var textarea = $('#pt' + id);
|
||||
textarea.val(textarea.data('source'));
|
||||
$.fn.autogrow.resize(textarea[0]);
|
||||
textarea.slideDown('fast');
|
||||
}
|
||||
|
||||
function hideProposeChange(id) {
|
||||
$('#hc' + id).hide();
|
||||
$('#pc' + id).show();
|
||||
var textarea = $('#pt' + id);
|
||||
textarea.val('').removeAttr('disabled');
|
||||
textarea.slideUp('fast');
|
||||
}
|
||||
|
||||
function toggleCommentMarkupBox(id) {
|
||||
$('#mb' + id).toggle();
|
||||
}
|
||||
|
||||
/** Handle when the user clicks on a sort by link. */
|
||||
function handleReSort(link) {
|
||||
var classes = link.attr('class').split(/\s+/);
|
||||
for (var i=0; i<classes.length; i++) {
|
||||
if (classes[i] != 'sort-option') {
|
||||
by = classes[i].substring(2);
|
||||
}
|
||||
}
|
||||
setComparator();
|
||||
// Save/update the sortBy cookie.
|
||||
var expiration = new Date();
|
||||
expiration.setDate(expiration.getDate() + 365);
|
||||
document.cookie= 'sortBy=' + escape(by) +
|
||||
';expires=' + expiration.toUTCString();
|
||||
$('ul.comment-ul').each(function(index, ul) {
|
||||
var comments = getChildren($(ul), true);
|
||||
comments = sortComments(comments);
|
||||
appendComments(comments, $(ul).empty());
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to process a vote when a user clicks an arrow.
|
||||
*/
|
||||
function handleVote(link) {
|
||||
if (!opts.voting) {
|
||||
showError("You'll need to login to vote.");
|
||||
return;
|
||||
}
|
||||
|
||||
var id = link.attr('id');
|
||||
if (!id) {
|
||||
// Didn't click on one of the voting arrows.
|
||||
return;
|
||||
}
|
||||
// If it is an unvote, the new vote value is 0,
|
||||
// Otherwise it's 1 for an upvote, or -1 for a downvote.
|
||||
var value = 0;
|
||||
if (id.charAt(1) != 'u') {
|
||||
value = id.charAt(0) == 'u' ? 1 : -1;
|
||||
}
|
||||
// The data to be sent to the server.
|
||||
var d = {
|
||||
comment_id: id.substring(2),
|
||||
value: value
|
||||
};
|
||||
|
||||
// Swap the vote and unvote links.
|
||||
link.hide();
|
||||
$('#' + id.charAt(0) + (id.charAt(1) == 'u' ? 'v' : 'u') + d.comment_id)
|
||||
.show();
|
||||
|
||||
// The div the comment is displayed in.
|
||||
var div = $('div#cd' + d.comment_id);
|
||||
var data = div.data('comment');
|
||||
|
||||
// If this is not an unvote, and the other vote arrow has
|
||||
// already been pressed, unpress it.
|
||||
if ((d.value !== 0) && (data.vote === d.value * -1)) {
|
||||
$('#' + (d.value == 1 ? 'd' : 'u') + 'u' + d.comment_id).hide();
|
||||
$('#' + (d.value == 1 ? 'd' : 'u') + 'v' + d.comment_id).show();
|
||||
}
|
||||
|
||||
// Update the comments rating in the local data.
|
||||
data.rating += (data.vote === 0) ? d.value : (d.value - data.vote);
|
||||
data.vote = d.value;
|
||||
div.data('comment', data);
|
||||
|
||||
// Change the rating text.
|
||||
div.find('.rating:first')
|
||||
.text(data.rating + ' point' + (data.rating == 1 ? '' : 's'));
|
||||
|
||||
// Send the vote information to the server.
|
||||
$.ajax({
|
||||
type: "POST",
|
||||
url: opts.processVoteURL,
|
||||
data: d,
|
||||
error: function(request, textStatus, error) {
|
||||
showError('Oops, there was a problem casting that vote.');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Open a reply form used to reply to an existing comment.
|
||||
*/
|
||||
function openReply(id) {
|
||||
// Swap out the reply link for the hide link
|
||||
$('#rl' + id).hide();
|
||||
$('#cr' + id).show();
|
||||
|
||||
// Add the reply li to the children ul.
|
||||
var div = $(renderTemplate(replyTemplate, {id: id})).hide();
|
||||
$('#cl' + id)
|
||||
.prepend(div)
|
||||
// Setup the submit handler for the reply form.
|
||||
.find('#rf' + id)
|
||||
.submit(function(event) {
|
||||
event.preventDefault();
|
||||
addComment($('#rf' + id));
|
||||
closeReply(id);
|
||||
})
|
||||
.find('input[type=button]')
|
||||
.click(function() {
|
||||
closeReply(id);
|
||||
});
|
||||
div.slideDown('fast', function() {
|
||||
$('#rf' + id).find('textarea').focus();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the reply form opened with openReply.
|
||||
*/
|
||||
function closeReply(id) {
|
||||
// Remove the reply div from the DOM.
|
||||
$('#rd' + id).slideUp('fast', function() {
|
||||
$(this).remove();
|
||||
});
|
||||
|
||||
// Swap out the hide link for the reply link
|
||||
$('#cr' + id).hide();
|
||||
$('#rl' + id).show();
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively sort a tree of comments using the comp comparator.
|
||||
*/
|
||||
function sortComments(comments) {
|
||||
comments.sort(comp);
|
||||
$.each(comments, function() {
|
||||
this.children = sortComments(this.children);
|
||||
});
|
||||
return comments;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the children comments from a ul. If recursive is true,
|
||||
* recursively include childrens' children.
|
||||
*/
|
||||
function getChildren(ul, recursive) {
|
||||
var children = [];
|
||||
ul.children().children("[id^='cd']")
|
||||
.each(function() {
|
||||
var comment = $(this).data('comment');
|
||||
if (recursive)
|
||||
comment.children = getChildren($(this).find('#cl' + comment.id), true);
|
||||
children.push(comment);
|
||||
});
|
||||
return children;
|
||||
}
|
||||
|
||||
/** Create a div to display a comment in. */
|
||||
function createCommentDiv(comment) {
|
||||
if (!comment.displayed && !opts.moderator) {
|
||||
return $('<div class="moderate">Thank you! Your comment will show up '
|
||||
+ 'once it is has been approved by a moderator.</div>');
|
||||
}
|
||||
// Prettify the comment rating.
|
||||
comment.pretty_rating = comment.rating + ' point' +
|
||||
(comment.rating == 1 ? '' : 's');
|
||||
// Make a class (for displaying not yet moderated comments differently)
|
||||
comment.css_class = comment.displayed ? '' : ' moderate';
|
||||
// Create a div for this comment.
|
||||
var context = $.extend({}, opts, comment);
|
||||
var div = $(renderTemplate(commentTemplate, context));
|
||||
|
||||
// If the user has voted on this comment, highlight the correct arrow.
|
||||
if (comment.vote) {
|
||||
var direction = (comment.vote == 1) ? 'u' : 'd';
|
||||
div.find('#' + direction + 'v' + comment.id).hide();
|
||||
div.find('#' + direction + 'u' + comment.id).show();
|
||||
}
|
||||
|
||||
if (opts.moderator || comment.text != '[deleted]') {
|
||||
div.find('a.reply').show();
|
||||
if (comment.proposal_diff)
|
||||
div.find('#sp' + comment.id).show();
|
||||
if (opts.moderator && !comment.displayed)
|
||||
div.find('#cm' + comment.id).show();
|
||||
if (opts.moderator || (opts.username == comment.username))
|
||||
div.find('#dc' + comment.id).show();
|
||||
}
|
||||
return div;
|
||||
}
|
||||
|
||||
/**
|
||||
* A simple template renderer. Placeholders such as <%id%> are replaced
|
||||
* by context['id'] with items being escaped. Placeholders such as <#id#>
|
||||
* are not escaped.
|
||||
*/
|
||||
function renderTemplate(template, context) {
|
||||
var esc = $(document.createElement('div'));
|
||||
|
||||
function handle(ph, escape) {
|
||||
var cur = context;
|
||||
$.each(ph.split('.'), function() {
|
||||
cur = cur[this];
|
||||
});
|
||||
return escape ? esc.text(cur || "").html() : cur;
|
||||
}
|
||||
|
||||
return template.replace(/<([%#])([\w\.]*)\1>/g, function() {
|
||||
return handle(arguments[2], arguments[1] == '%' ? true : false);
|
||||
});
|
||||
}
|
||||
|
||||
/** Flash an error message briefly. */
|
||||
function showError(message) {
|
||||
$(document.createElement('div')).attr({'class': 'popup-error'})
|
||||
.append($(document.createElement('div'))
|
||||
.attr({'class': 'error-message'}).text(message))
|
||||
.appendTo('body')
|
||||
.fadeIn("slow")
|
||||
.delay(2000)
|
||||
.fadeOut("slow");
|
||||
}
|
||||
|
||||
/** Add a link the user uses to open the comments popup. */
|
||||
$.fn.comment = function() {
|
||||
return this.each(function() {
|
||||
var id = $(this).attr('id').substring(1);
|
||||
var count = COMMENT_METADATA[id];
|
||||
var title = count + ' comment' + (count == 1 ? '' : 's');
|
||||
var image = count > 0 ? opts.commentBrightImage : opts.commentImage;
|
||||
var addcls = count == 0 ? ' nocomment' : '';
|
||||
$(this)
|
||||
.append(
|
||||
$(document.createElement('a')).attr({
|
||||
href: '#',
|
||||
'class': 'sphinx-comment-open' + addcls,
|
||||
id: 'ao' + id
|
||||
})
|
||||
.append($(document.createElement('img')).attr({
|
||||
src: image,
|
||||
alt: 'comment',
|
||||
title: title
|
||||
}))
|
||||
.click(function(event) {
|
||||
event.preventDefault();
|
||||
show($(this).attr('id').substring(2));
|
||||
})
|
||||
)
|
||||
.append(
|
||||
$(document.createElement('a')).attr({
|
||||
href: '#',
|
||||
'class': 'sphinx-comment-close hidden',
|
||||
id: 'ah' + id
|
||||
})
|
||||
.append($(document.createElement('img')).attr({
|
||||
src: opts.closeCommentImage,
|
||||
alt: 'close',
|
||||
title: 'close'
|
||||
}))
|
||||
.click(function(event) {
|
||||
event.preventDefault();
|
||||
hide($(this).attr('id').substring(2));
|
||||
})
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
var opts = {
|
||||
processVoteURL: '/_process_vote',
|
||||
addCommentURL: '/_add_comment',
|
||||
getCommentsURL: '/_get_comments',
|
||||
acceptCommentURL: '/_accept_comment',
|
||||
deleteCommentURL: '/_delete_comment',
|
||||
commentImage: '/static/_static/comment.png',
|
||||
closeCommentImage: '/static/_static/comment-close.png',
|
||||
loadingImage: '/static/_static/ajax-loader.gif',
|
||||
commentBrightImage: '/static/_static/comment-bright.png',
|
||||
upArrow: '/static/_static/up.png',
|
||||
downArrow: '/static/_static/down.png',
|
||||
upArrowPressed: '/static/_static/up-pressed.png',
|
||||
downArrowPressed: '/static/_static/down-pressed.png',
|
||||
voting: false,
|
||||
moderator: false
|
||||
};
|
||||
|
||||
if (typeof COMMENT_OPTIONS != "undefined") {
|
||||
opts = jQuery.extend(opts, COMMENT_OPTIONS);
|
||||
}
|
||||
|
||||
var popupTemplate = '\
|
||||
<div class="sphinx-comments" id="sc<%id%>">\
|
||||
<p class="sort-options">\
|
||||
Sort by:\
|
||||
<a href="#" class="sort-option byrating">best rated</a>\
|
||||
<a href="#" class="sort-option byascage">newest</a>\
|
||||
<a href="#" class="sort-option byage">oldest</a>\
|
||||
</p>\
|
||||
<div class="comment-header">Comments</div>\
|
||||
<div class="comment-loading" id="cn<%id%>">\
|
||||
loading comments... <img src="<%loadingImage%>" alt="" /></div>\
|
||||
<ul id="cl<%id%>" class="comment-ul"></ul>\
|
||||
<div id="ca<%id%>">\
|
||||
<p class="add-a-comment">Add a comment\
|
||||
(<a href="#" class="comment-markup" id="ab<%id%>">markup</a>):</p>\
|
||||
<div class="comment-markup-box" id="mb<%id%>">\
|
||||
reStructured text markup: <i>*emph*</i>, <b>**strong**</b>, \
|
||||
<code>``code``</code>, \
|
||||
code blocks: <code>::</code> and an indented block after blank line</div>\
|
||||
<form method="post" id="cf<%id%>" class="comment-form" action="">\
|
||||
<textarea name="comment" cols="80"></textarea>\
|
||||
<p class="propose-button">\
|
||||
<a href="#" id="pc<%id%>" class="show-propose-change">\
|
||||
Propose a change ▹\
|
||||
</a>\
|
||||
<a href="#" id="hc<%id%>" class="hide-propose-change">\
|
||||
Propose a change ▿\
|
||||
</a>\
|
||||
</p>\
|
||||
<textarea name="proposal" id="pt<%id%>" cols="80"\
|
||||
spellcheck="false"></textarea>\
|
||||
<input type="submit" value="Add comment" />\
|
||||
<input type="hidden" name="node" value="<%id%>" />\
|
||||
<input type="hidden" name="parent" value="" />\
|
||||
</form>\
|
||||
</div>\
|
||||
</div>';
|
||||
|
||||
var commentTemplate = '\
|
||||
<div id="cd<%id%>" class="sphinx-comment<%css_class%>">\
|
||||
<div class="vote">\
|
||||
<div class="arrow">\
|
||||
<a href="#" id="uv<%id%>" class="vote" title="vote up">\
|
||||
<img src="<%upArrow%>" />\
|
||||
</a>\
|
||||
<a href="#" id="uu<%id%>" class="un vote" title="vote up">\
|
||||
<img src="<%upArrowPressed%>" />\
|
||||
</a>\
|
||||
</div>\
|
||||
<div class="arrow">\
|
||||
<a href="#" id="dv<%id%>" class="vote" title="vote down">\
|
||||
<img src="<%downArrow%>" id="da<%id%>" />\
|
||||
</a>\
|
||||
<a href="#" id="du<%id%>" class="un vote" title="vote down">\
|
||||
<img src="<%downArrowPressed%>" />\
|
||||
</a>\
|
||||
</div>\
|
||||
</div>\
|
||||
<div class="comment-content">\
|
||||
<p class="tagline comment">\
|
||||
<span class="user-id"><%username%></span>\
|
||||
<span class="rating"><%pretty_rating%></span>\
|
||||
<span class="delta"><%time.delta%></span>\
|
||||
</p>\
|
||||
<div class="comment-text comment"><#text#></div>\
|
||||
<p class="comment-opts comment">\
|
||||
<a href="#" class="reply hidden" id="rl<%id%>">reply ▹</a>\
|
||||
<a href="#" class="close-reply" id="cr<%id%>">reply ▿</a>\
|
||||
<a href="#" id="sp<%id%>" class="show-proposal">proposal ▹</a>\
|
||||
<a href="#" id="hp<%id%>" class="hide-proposal">proposal ▿</a>\
|
||||
<a href="#" id="dc<%id%>" class="delete-comment hidden">delete</a>\
|
||||
<span id="cm<%id%>" class="moderation hidden">\
|
||||
<a href="#" id="ac<%id%>" class="accept-comment">accept</a>\
|
||||
</span>\
|
||||
</p>\
|
||||
<pre class="proposal" id="pr<%id%>">\
|
||||
<#proposal_diff#>\
|
||||
</pre>\
|
||||
<ul class="comment-children" id="cl<%id%>"></ul>\
|
||||
</div>\
|
||||
<div class="clearleft"></div>\
|
||||
</div>\
|
||||
</div>';
|
||||
|
||||
var replyTemplate = '\
|
||||
<li>\
|
||||
<div class="reply-div" id="rd<%id%>">\
|
||||
<form id="rf<%id%>">\
|
||||
<textarea name="comment" cols="80"></textarea>\
|
||||
<input type="submit" value="Add reply" />\
|
||||
<input type="button" value="Cancel" />\
|
||||
<input type="hidden" name="parent" value="<%id%>" />\
|
||||
<input type="hidden" name="node" value="" />\
|
||||
</form>\
|
||||
</div>\
|
||||
</li>';
|
||||
|
||||
$(document).ready(function() {
|
||||
init();
|
||||
});
|
||||
})(jQuery);
|
||||
|
||||
$(document).ready(function() {
|
||||
// add comment anchors for all paragraphs that are commentable
|
||||
$('.sphinx-has-comment').comment();
|
||||
|
||||
// highlight search words in search results
|
||||
$("div.context").each(function() {
|
||||
var params = $.getQueryParameters();
|
||||
var terms = (params.q) ? params.q[0].split(/\s+/) : [];
|
||||
var result = $(this);
|
||||
$.each(terms, function() {
|
||||
result.highlightText(this.toLowerCase(), 'highlighted');
|
||||
});
|
||||
});
|
||||
|
||||
// directly open comment window if requested
|
||||
var anchor = document.location.hash;
|
||||
if (anchor.substring(0, 9) == '#comment-') {
|
||||
$('#ao' + anchor.substring(9)).click();
|
||||
document.location.hash = '#s' + anchor.substring(9);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,334 @@
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
|
||||
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||
|
||||
<html xmlns="http://www.w3.org/1999/xhtml">
|
||||
<head>
|
||||
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
|
||||
|
||||
<title>Blending the ORM and MongoDB ODM — Doctrine MongoDB ODM 1.1.5 documentation</title>
|
||||
<link rel="stylesheet" href="../_static/bootstrap/css/bootstrap.min.css" type="text/css" />
|
||||
<link rel="stylesheet" href="../_static/default.css" type="text/css" />
|
||||
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
|
||||
<link rel="stylesheet" href="../_static/layout.css" type="text/css" />
|
||||
<link rel="stylesheet" href="../_static/configurationblock.css" type="text/css" />
|
||||
<script type="text/javascript">
|
||||
var DOCUMENTATION_OPTIONS = {
|
||||
URL_ROOT: '../',
|
||||
VERSION: '1.1.5',
|
||||
COLLAPSE_MODINDEX: false,
|
||||
FILE_SUFFIX: '.html',
|
||||
HAS_SOURCE: true
|
||||
};
|
||||
</script>
|
||||
|
||||
<script type="text/javascript" src="../_static/jquery.js"></script>
|
||||
<script type="text/javascript" src="../_static/configurationblock.js"></script>
|
||||
<script type="text/javascript" src="../_static/underscore.js"></script>
|
||||
<script type="text/javascript" src="../_static/configurationblock.js"></script>
|
||||
<script type="text/javascript" src="../_static/doctools.js"></script>
|
||||
<script type="text/javascript" src="../_static/configurationblock.js"></script>
|
||||
<script src="../_static/bootstrap/js/bootstrap.min.js"></script>
|
||||
|
||||
<script type="text/javascript">
|
||||
<!--
|
||||
$(document).ready(function() {
|
||||
$("#versions").change(function() {
|
||||
var docsUrl = $(this).val();
|
||||
window.location.href = docsUrl;
|
||||
});
|
||||
});
|
||||
-->
|
||||
</script>
|
||||
<link rel="shortcut icon" href="../_static/doctrine.ico"/>
|
||||
<link rel="search" title="Search" href="../search.html" />
|
||||
<link rel="top" title="Doctrine MongoDB ODM 1.1.5 documentation" href="../index.html" />
|
||||
</head>
|
||||
<body>
|
||||
<div id="wrapper">
|
||||
<div id="header">
|
||||
<h1 id="h1title"></h1>
|
||||
<div id="logo">
|
||||
<a href="http://www.doctrine-project.org/">Doctrine - PHP Database Libraries</a>
|
||||
</div>
|
||||
</div>
|
||||
<div id="nav" class="cls">
|
||||
<div class="tl cls">
|
||||
<ul>
|
||||
<li><a target="_top" href="http://www.doctrine-project.org/">Home</a></li>
|
||||
<li><a target="_top" href="http://www.doctrine-project.org/about.html">About</a></li>
|
||||
<li><a target="_top" href="http://www.doctrine-project.org/projects.html">Projects</a></li>
|
||||
<li><a target="_top" href="http://www.doctrine-project.org/contribute.html">Contribute</a></li>
|
||||
<li><a target="_top" href="http://www.doctrine-project.org/community.html">Community</a></li>
|
||||
<li><a target="_top" href="http://www.doctrine-project.org/archive.html">Blog</a></li>
|
||||
<li><a target="_top" href="http://www.doctrine-project.org/jira">Development</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<div id="content" class="cls">
|
||||
<div class="related">
|
||||
<h3>Navigation</h3>
|
||||
<ul>
|
||||
<li><a href="/">Doctrine Homepage</a> »</li>
|
||||
<li><a href="../index.html">Doctrine MongoDB ODM 1.1.5 documentation</a> »</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="document">
|
||||
<div class="documentwrapper">
|
||||
<div class="bodywrapper">
|
||||
|
||||
<div class="body" >
|
||||
|
||||
<div class="section" id="blending-the-orm-and-mongodb-odm">
|
||||
<h1>Blending the ORM and MongoDB ODM<a class="headerlink" href="#blending-the-orm-and-mongodb-odm" title="Permalink to this headline">¶</a></h1>
|
||||
<p>Since the start of the <a class="reference external" href="http://www.doctrine-project.org/projects/mongodb_odm">Doctrine MongoDB Object Document Mapper</a> project people have asked how it can be integrated with the <a class="reference external" href="http://www.doctrine-project.org/projects/orm">ORM</a>. This article will demonstrates how you can integrate the two transparently, maintaining a clean domain model.</p>
|
||||
<p>This example will have a <cite>Product</cite> that is stored in MongoDB and the <cite>Order</cite> stored in a MySQL database.</p>
|
||||
<div class="section" id="define-product">
|
||||
<h2>Define Product<a class="headerlink" href="#define-product" title="Permalink to this headline">¶</a></h2>
|
||||
<p>First lets define our <cite>Product</cite> document:</p>
|
||||
<div class="highlight-php"><div class="highlight"><pre><span class="cp"><?php</span>
|
||||
|
||||
<span class="k">namespace</span> <span class="nx">Documents</span><span class="p">;</span>
|
||||
|
||||
<span class="sd">/** @Document */</span>
|
||||
<span class="k">class</span> <span class="nc">Product</span>
|
||||
<span class="p">{</span>
|
||||
<span class="sd">/** @Id */</span>
|
||||
<span class="k">private</span> <span class="nv">$id</span><span class="p">;</span>
|
||||
|
||||
<span class="sd">/** @Field(type="string") */</span>
|
||||
<span class="k">private</span> <span class="nv">$title</span><span class="p">;</span>
|
||||
|
||||
<span class="k">public</span> <span class="k">function</span> <span class="nf">getId</span><span class="p">()</span>
|
||||
<span class="p">{</span>
|
||||
<span class="k">return</span> <span class="nv">$this</span><span class="o">-></span><span class="na">id</span><span class="p">;</span>
|
||||
<span class="p">}</span>
|
||||
|
||||
<span class="k">public</span> <span class="k">function</span> <span class="nf">getTitle</span><span class="p">()</span>
|
||||
<span class="p">{</span>
|
||||
<span class="k">return</span> <span class="nv">$this</span><span class="o">-></span><span class="na">title</span><span class="p">;</span>
|
||||
<span class="p">}</span>
|
||||
|
||||
<span class="k">public</span> <span class="k">function</span> <span class="nf">setTitle</span><span class="p">(</span><span class="nv">$title</span><span class="p">)</span>
|
||||
<span class="p">{</span>
|
||||
<span class="nv">$this</span><span class="o">-></span><span class="na">title</span> <span class="o">=</span> <span class="nv">$title</span><span class="p">;</span>
|
||||
<span class="p">}</span>
|
||||
<span class="p">}</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="section" id="define-entity">
|
||||
<h2>Define Entity<a class="headerlink" href="#define-entity" title="Permalink to this headline">¶</a></h2>
|
||||
<p>Next create the <cite>Order</cite> entity that has a <cite>$product</cite> and <cite>$productId</cite> property linking it to the <cite>Product</cite> that is stored with MongoDB:</p>
|
||||
<div class="highlight-php"><div class="highlight"><pre><span class="cp"><?php</span>
|
||||
|
||||
<span class="k">namespace</span> <span class="nx">Entities</span><span class="p">;</span>
|
||||
|
||||
<span class="k">use</span> <span class="nx">Documents\Product</span><span class="p">;</span>
|
||||
|
||||
<span class="sd">/**</span>
|
||||
<span class="sd"> * @Entity</span>
|
||||
<span class="sd"> * @Table(name="orders")</span>
|
||||
<span class="sd"> */</span>
|
||||
<span class="k">class</span> <span class="nc">Order</span>
|
||||
<span class="p">{</span>
|
||||
<span class="sd">/**</span>
|
||||
<span class="sd"> * @Id @Column(type="integer")</span>
|
||||
<span class="sd"> * @GeneratedValue(strategy="AUTO")</span>
|
||||
<span class="sd"> */</span>
|
||||
<span class="k">private</span> <span class="nv">$id</span><span class="p">;</span>
|
||||
|
||||
<span class="sd">/**</span>
|
||||
<span class="sd"> * @Column(type="string")</span>
|
||||
<span class="sd"> */</span>
|
||||
<span class="k">private</span> <span class="nv">$productId</span><span class="p">;</span>
|
||||
|
||||
<span class="sd">/**</span>
|
||||
<span class="sd"> * @var Documents\Product</span>
|
||||
<span class="sd"> */</span>
|
||||
<span class="k">private</span> <span class="nv">$product</span><span class="p">;</span>
|
||||
|
||||
<span class="k">public</span> <span class="k">function</span> <span class="nf">getId</span><span class="p">()</span>
|
||||
<span class="p">{</span>
|
||||
<span class="k">return</span> <span class="nv">$this</span><span class="o">-></span><span class="na">id</span><span class="p">;</span>
|
||||
<span class="p">}</span>
|
||||
|
||||
<span class="k">public</span> <span class="k">function</span> <span class="nf">getProductId</span><span class="p">()</span>
|
||||
<span class="p">{</span>
|
||||
<span class="k">return</span> <span class="nv">$this</span><span class="o">-></span><span class="na">productId</span><span class="p">;</span>
|
||||
<span class="p">}</span>
|
||||
|
||||
<span class="k">public</span> <span class="k">function</span> <span class="nf">setProduct</span><span class="p">(</span><span class="nx">Product</span> <span class="nv">$product</span><span class="p">)</span>
|
||||
<span class="p">{</span>
|
||||
<span class="nv">$this</span><span class="o">-></span><span class="na">productId</span> <span class="o">=</span> <span class="nv">$product</span><span class="o">-></span><span class="na">getId</span><span class="p">();</span>
|
||||
<span class="nv">$this</span><span class="o">-></span><span class="na">product</span> <span class="o">=</span> <span class="nv">$product</span><span class="p">;</span>
|
||||
<span class="p">}</span>
|
||||
|
||||
<span class="k">public</span> <span class="k">function</span> <span class="nf">getProduct</span><span class="p">()</span>
|
||||
<span class="p">{</span>
|
||||
<span class="k">return</span> <span class="nv">$this</span><span class="o">-></span><span class="na">product</span><span class="p">;</span>
|
||||
<span class="p">}</span>
|
||||
<span class="p">}</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="section" id="event-subscriber">
|
||||
<h2>Event Subscriber<a class="headerlink" href="#event-subscriber" title="Permalink to this headline">¶</a></h2>
|
||||
<p>Now we need to setup an event subscriber that will set the <cite>$product</cite> property of all <cite>Order</cite> instances to a reference to the document product so it can be lazily loaded when it is accessed the first time. So first register a new event subscriber:</p>
|
||||
<div class="highlight-php"><div class="highlight"><pre><span class="cp"><?php</span>
|
||||
|
||||
<span class="nv">$eventManager</span> <span class="o">=</span> <span class="nv">$em</span><span class="o">-></span><span class="na">getEventManager</span><span class="p">();</span>
|
||||
<span class="nv">$eventManager</span><span class="o">-></span><span class="na">addEventListener</span><span class="p">(</span>
|
||||
<span class="k">array</span><span class="p">(</span><span class="nx">\Doctrine\ORM\Events</span><span class="o">::</span><span class="na">postLoad</span><span class="p">),</span> <span class="k">new</span> <span class="nx">MyEventSubscriber</span><span class="p">(</span><span class="nv">$dm</span><span class="p">)</span>
|
||||
<span class="p">);</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>So now we need to define a class named <cite>MyEventSubscriber</cite> and pass a dependency to the <cite>DocumentManager</cite>. It will have a <cite>postLoad()</cite> method that sets the product document reference:</p>
|
||||
<div class="highlight-php"><div class="highlight"><pre><span class="cp"><?php</span>
|
||||
|
||||
<span class="k">use</span> <span class="nx">Doctrine\ODM\MongoDB\DocumentManager</span><span class="p">;</span>
|
||||
<span class="k">use</span> <span class="nx">Doctrine\ORM\Event\LifecycleEventArgs</span><span class="p">;</span>
|
||||
|
||||
<span class="k">class</span> <span class="nc">MyEventSubscriber</span>
|
||||
<span class="p">{</span>
|
||||
<span class="k">public</span> <span class="k">function</span> <span class="nf">__construct</span><span class="p">(</span><span class="nx">DocumentManager</span> <span class="nv">$dm</span><span class="p">)</span>
|
||||
<span class="p">{</span>
|
||||
<span class="nv">$this</span><span class="o">-></span><span class="na">dm</span> <span class="o">=</span> <span class="nv">$dm</span><span class="p">;</span>
|
||||
<span class="p">}</span>
|
||||
|
||||
<span class="k">public</span> <span class="k">function</span> <span class="nf">postLoad</span><span class="p">(</span><span class="nx">LifecycleEventArgs</span> <span class="nv">$eventArgs</span><span class="p">)</span>
|
||||
<span class="p">{</span>
|
||||
<span class="nv">$order</span> <span class="o">=</span> <span class="nv">$eventArgs</span><span class="o">-></span><span class="na">getEntity</span><span class="p">();</span>
|
||||
<span class="nv">$em</span> <span class="o">=</span> <span class="nv">$eventArgs</span><span class="o">-></span><span class="na">getEntityManager</span><span class="p">();</span>
|
||||
<span class="nv">$productReflProp</span> <span class="o">=</span> <span class="nv">$em</span><span class="o">-></span><span class="na">getClassMetadata</span><span class="p">(</span><span class="s1">'Entities\Order'</span><span class="p">)</span>
|
||||
<span class="o">-></span><span class="na">reflClass</span><span class="o">-></span><span class="na">getProperty</span><span class="p">(</span><span class="s1">'product'</span><span class="p">);</span>
|
||||
<span class="nv">$productReflProp</span><span class="o">-></span><span class="na">setAccessible</span><span class="p">(</span><span class="k">true</span><span class="p">);</span>
|
||||
<span class="nv">$productReflProp</span><span class="o">-></span><span class="na">setValue</span><span class="p">(</span>
|
||||
<span class="nv">$order</span><span class="p">,</span> <span class="nv">$this</span><span class="o">-></span><span class="na">dm</span><span class="o">-></span><span class="na">getReference</span><span class="p">(</span><span class="s1">'Documents\Product'</span><span class="p">,</span> <span class="nv">$order</span><span class="o">-></span><span class="na">getProductId</span><span class="p">())</span>
|
||||
<span class="p">);</span>
|
||||
<span class="p">}</span>
|
||||
<span class="p">}</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>The <cite>postLoad</cite> method will be invoked after an ORM entity is loaded from the database. This allows us to use the <cite>DocumentManager</cite> to set the <cite>$product</cite> property with a reference to the <cite>Product</cite> document with the product id we previously stored.</p>
|
||||
</div>
|
||||
<div class="section" id="working-with-products-and-orders">
|
||||
<h2>Working with Products and Orders<a class="headerlink" href="#working-with-products-and-orders" title="Permalink to this headline">¶</a></h2>
|
||||
<p>First create a new <cite>Product</cite>:</p>
|
||||
<div class="highlight-php"><div class="highlight"><pre><span class="cp"><?php</span>
|
||||
|
||||
<span class="nv">$product</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">\Documents\Product</span><span class="p">();</span>
|
||||
<span class="nv">$product</span><span class="o">-></span><span class="na">setTitle</span><span class="p">(</span><span class="s1">'Test Product'</span><span class="p">);</span>
|
||||
<span class="nv">$dm</span><span class="o">-></span><span class="na">persist</span><span class="p">(</span><span class="nv">$product</span><span class="p">);</span>
|
||||
<span class="nv">$dm</span><span class="o">-></span><span class="na">flush</span><span class="p">();</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>Now create a new <cite>Order</cite> and link it to a <cite>Product</cite> in MySQL:</p>
|
||||
<div class="highlight-php"><div class="highlight"><pre><span class="cp"><?php</span>
|
||||
|
||||
<span class="nv">$order</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">\Entities\Order</span><span class="p">();</span>
|
||||
<span class="nv">$order</span><span class="o">-></span><span class="na">setProduct</span><span class="p">(</span><span class="nv">$product</span><span class="p">);</span>
|
||||
<span class="nv">$em</span><span class="o">-></span><span class="na">persist</span><span class="p">(</span><span class="nv">$order</span><span class="p">);</span>
|
||||
<span class="nv">$em</span><span class="o">-></span><span class="na">flush</span><span class="p">();</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>Later we can retrieve the entity and lazily load the reference to the document in MongoDB:</p>
|
||||
<div class="highlight-php"><div class="highlight"><pre><span class="cp"><?php</span>
|
||||
|
||||
<span class="nv">$order</span> <span class="o">=</span> <span class="nv">$em</span><span class="o">-></span><span class="na">find</span><span class="p">(</span><span class="s1">'Order'</span><span class="p">,</span> <span class="nv">$order</span><span class="o">-></span><span class="na">getId</span><span class="p">());</span>
|
||||
|
||||
<span class="c1">// Instance of an uninitialized product proxy</span>
|
||||
<span class="nv">$product</span> <span class="o">=</span> <span class="nv">$order</span><span class="o">-></span><span class="na">getProduct</span><span class="p">();</span>
|
||||
|
||||
<span class="c1">// Initializes proxy and queries the database</span>
|
||||
<span class="k">echo</span> <span class="s2">"Order Title: "</span> <span class="o">.</span> <span class="nv">$product</span><span class="o">-></span><span class="na">getTitle</span><span class="p">();</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>If you were to print the <cite>$order</cite> you would see that we got back regular PHP objects:</p>
|
||||
<div class="highlight-php"><div class="highlight"><pre><span class="cp"><?php</span>
|
||||
|
||||
<span class="nb">print_r</span><span class="p">(</span><span class="nv">$order</span><span class="p">);</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>The above would output the following:</p>
|
||||
<div class="highlight-php"><div class="highlight"><pre><span class="x">Order Object</span>
|
||||
<span class="x">(</span>
|
||||
<span class="x"> [id:Entities\Order:private] => 53</span>
|
||||
<span class="x"> [productId:Entities\Order:private] => 4c74a1868ead0ed7a9000000</span>
|
||||
<span class="x"> [product:Entities\Order:private] => Proxies\DocumentsProductProxy Object</span>
|
||||
<span class="x"> (</span>
|
||||
<span class="x"> [__isInitialized__] => 1</span>
|
||||
<span class="x"> [id:Documents\Product:private] => 4c74a1868ead0ed7a9000000</span>
|
||||
<span class="x"> [title:Documents\Product:private] => Test Product</span>
|
||||
<span class="x"> )</span>
|
||||
<span class="x">)</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
<div class="sphinxsidebar">
|
||||
<div class="sphinxsidebarwrapper">
|
||||
|
||||
<div id="searchbox" style="">
|
||||
<h3>Search</h3>
|
||||
<form class="search" action="http://readthedocs.org/search/project/" method="get">
|
||||
<input type="text" name="q" size="18">
|
||||
<input type="submit" value="Go">
|
||||
<input type="hidden" name="selected_facets" value="project:">
|
||||
</form>
|
||||
</div>
|
||||
<h3><a href="../index.html">Table Of Contents</a></h3>
|
||||
<ul>
|
||||
<li><a class="reference internal" href="#">Blending the ORM and MongoDB ODM</a><ul>
|
||||
<li><a class="reference internal" href="#define-product">Define Product</a></li>
|
||||
<li><a class="reference internal" href="#define-entity">Define Entity</a></li>
|
||||
<li><a class="reference internal" href="#event-subscriber">Event Subscriber</a></li>
|
||||
<li><a class="reference internal" href="#working-with-products-and-orders">Working with Products and Orders</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<h3>This Page</h3>
|
||||
<ul class="this-page-menu">
|
||||
<li><a href="../_sources/cookbook/blending-orm-and-mongodb-odm.rst.txt"
|
||||
rel="nofollow">Show Source</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<div class="clearer"></div>
|
||||
</div>
|
||||
<div class="footer">
|
||||
© Copyright 2013, Doctrine Project Team.
|
||||
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.6.2.
|
||||
<br/>
|
||||
<a target="_BLANK" href="http://www.servergrove.com"><img src="http://www.doctrine-project.org/_static/servergrove.jpg" /></a> <br/><br/>
|
||||
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
|
||||
<input type="hidden" name="cmd" value="_s-xclick" />
|
||||
<input type="hidden" name="hosted_button_id" value="BAE2E3XANQ77Y" />
|
||||
<input type="image" src="https://www.paypal.com/en_US/i/btn/btn_donateCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!" />
|
||||
<img alt="" border="0" src="https://www.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1" />
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="bot-rcnr">
|
||||
<div class="tl"><!-- corner --></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
|
||||
</script>
|
||||
<script type="text/javascript">
|
||||
_uacct = "UA-288343-7";
|
||||
urchinTracker();
|
||||
</script>
|
||||
<a class="githublink" href="http://github.com/doctrine"><img src="https://s3.amazonaws.com/github/ribbons/forkme_right_orange_ff7600.png" alt="Fork me on GitHub"></a>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,264 @@
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
|
||||
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||
|
||||
<html xmlns="http://www.w3.org/1999/xhtml">
|
||||
<head>
|
||||
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
|
||||
|
||||
<title>Implementing ArrayAccess for Domain Objects — Doctrine MongoDB ODM 1.1.5 documentation</title>
|
||||
<link rel="stylesheet" href="../_static/bootstrap/css/bootstrap.min.css" type="text/css" />
|
||||
<link rel="stylesheet" href="../_static/default.css" type="text/css" />
|
||||
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
|
||||
<link rel="stylesheet" href="../_static/layout.css" type="text/css" />
|
||||
<link rel="stylesheet" href="../_static/configurationblock.css" type="text/css" />
|
||||
<script type="text/javascript">
|
||||
var DOCUMENTATION_OPTIONS = {
|
||||
URL_ROOT: '../',
|
||||
VERSION: '1.1.5',
|
||||
COLLAPSE_MODINDEX: false,
|
||||
FILE_SUFFIX: '.html',
|
||||
HAS_SOURCE: true
|
||||
};
|
||||
</script>
|
||||
|
||||
<script type="text/javascript" src="../_static/jquery.js"></script>
|
||||
<script type="text/javascript" src="../_static/configurationblock.js"></script>
|
||||
<script type="text/javascript" src="../_static/underscore.js"></script>
|
||||
<script type="text/javascript" src="../_static/configurationblock.js"></script>
|
||||
<script type="text/javascript" src="../_static/doctools.js"></script>
|
||||
<script type="text/javascript" src="../_static/configurationblock.js"></script>
|
||||
<script src="../_static/bootstrap/js/bootstrap.min.js"></script>
|
||||
|
||||
<script type="text/javascript">
|
||||
<!--
|
||||
$(document).ready(function() {
|
||||
$("#versions").change(function() {
|
||||
var docsUrl = $(this).val();
|
||||
window.location.href = docsUrl;
|
||||
});
|
||||
});
|
||||
-->
|
||||
</script>
|
||||
<link rel="shortcut icon" href="../_static/doctrine.ico"/>
|
||||
<link rel="search" title="Search" href="../search.html" />
|
||||
<link rel="top" title="Doctrine MongoDB ODM 1.1.5 documentation" href="../index.html" />
|
||||
</head>
|
||||
<body>
|
||||
<div id="wrapper">
|
||||
<div id="header">
|
||||
<h1 id="h1title"></h1>
|
||||
<div id="logo">
|
||||
<a href="http://www.doctrine-project.org/">Doctrine - PHP Database Libraries</a>
|
||||
</div>
|
||||
</div>
|
||||
<div id="nav" class="cls">
|
||||
<div class="tl cls">
|
||||
<ul>
|
||||
<li><a target="_top" href="http://www.doctrine-project.org/">Home</a></li>
|
||||
<li><a target="_top" href="http://www.doctrine-project.org/about.html">About</a></li>
|
||||
<li><a target="_top" href="http://www.doctrine-project.org/projects.html">Projects</a></li>
|
||||
<li><a target="_top" href="http://www.doctrine-project.org/contribute.html">Contribute</a></li>
|
||||
<li><a target="_top" href="http://www.doctrine-project.org/community.html">Community</a></li>
|
||||
<li><a target="_top" href="http://www.doctrine-project.org/archive.html">Blog</a></li>
|
||||
<li><a target="_top" href="http://www.doctrine-project.org/jira">Development</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<div id="content" class="cls">
|
||||
<div class="related">
|
||||
<h3>Navigation</h3>
|
||||
<ul>
|
||||
<li><a href="/">Doctrine Homepage</a> »</li>
|
||||
<li><a href="../index.html">Doctrine MongoDB ODM 1.1.5 documentation</a> »</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="document">
|
||||
<div class="documentwrapper">
|
||||
<div class="bodywrapper">
|
||||
|
||||
<div class="body" >
|
||||
|
||||
<div class="section" id="implementing-arrayaccess-for-domain-objects">
|
||||
<h1>Implementing ArrayAccess for Domain Objects<a class="headerlink" href="#implementing-arrayaccess-for-domain-objects" title="Permalink to this headline">¶</a></h1>
|
||||
<p><em>Section author: Roman Borschel (<a class="reference external" href="mailto:roman%40code-factory.org">roman<span>@</span>code-factory<span>.</span>org</a>)</em></p>
|
||||
<p>This recipe will show you how to implement ArrayAccess for your
|
||||
domain objects in order to allow more uniform access, for example
|
||||
in templates. In these examples we will implement ArrayAccess on a
|
||||
<a class="reference external" href="http://martinfowler.com/eaaCatalog/layerSupertype.html">Layer Supertype</a>
|
||||
for all our domain objects.</p>
|
||||
<div class="section" id="option-1">
|
||||
<h2>Option 1<a class="headerlink" href="#option-1" title="Permalink to this headline">¶</a></h2>
|
||||
<p>In this implementation we will make use of PHPs highly dynamic
|
||||
nature to dynamically access properties of a subtype in a supertype
|
||||
at runtime. Note that this implementation has 2 main caveats:</p>
|
||||
<ul class="simple">
|
||||
<li>It will not work with private fields</li>
|
||||
<li>It will not go through any getters/setters</li>
|
||||
</ul>
|
||||
<div class="highlight-php"><div class="highlight"><pre><span class="cp"><?php</span>
|
||||
|
||||
<span class="k">abstract</span> <span class="k">class</span> <span class="nc">DomainObject</span> <span class="k">implements</span> <span class="nx">ArrayAccess</span>
|
||||
<span class="p">{</span>
|
||||
<span class="k">public</span> <span class="k">function</span> <span class="nf">offsetExists</span><span class="p">(</span><span class="nv">$offset</span><span class="p">)</span>
|
||||
<span class="p">{</span>
|
||||
<span class="k">return</span> <span class="nb">isset</span><span class="p">(</span><span class="nv">$this</span><span class="o">-></span><span class="nv">$offset</span><span class="p">);</span>
|
||||
<span class="p">}</span>
|
||||
|
||||
<span class="k">public</span> <span class="k">function</span> <span class="nf">offsetSet</span><span class="p">(</span><span class="nv">$offset</span><span class="p">,</span> <span class="nv">$value</span><span class="p">)</span>
|
||||
<span class="p">{</span>
|
||||
<span class="nv">$this</span><span class="o">-></span><span class="nv">$offset</span> <span class="o">=</span> <span class="nv">$value</span><span class="p">;</span>
|
||||
<span class="p">}</span>
|
||||
|
||||
<span class="k">public</span> <span class="k">function</span> <span class="nf">offsetGet</span><span class="p">(</span><span class="nv">$offset</span><span class="p">)</span>
|
||||
<span class="p">{</span>
|
||||
<span class="k">return</span> <span class="nv">$this</span><span class="o">-></span><span class="nv">$offset</span><span class="p">;</span>
|
||||
<span class="p">}</span>
|
||||
|
||||
<span class="k">public</span> <span class="k">function</span> <span class="nf">offsetUnset</span><span class="p">(</span><span class="nv">$offset</span><span class="p">)</span>
|
||||
<span class="p">{</span>
|
||||
<span class="nv">$this</span><span class="o">-></span><span class="nv">$offset</span> <span class="o">=</span> <span class="k">null</span><span class="p">;</span>
|
||||
<span class="p">}</span>
|
||||
<span class="p">}</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="section" id="option-2">
|
||||
<h2>Option 2<a class="headerlink" href="#option-2" title="Permalink to this headline">¶</a></h2>
|
||||
<p>In this implementation we will dynamically invoke getters/setters.
|
||||
Again we use PHPs dynamic nature to invoke methods on a subtype
|
||||
from a supertype at runtime. This implementation has the following
|
||||
caveats:</p>
|
||||
<ul class="simple">
|
||||
<li>It relies on a naming convention</li>
|
||||
<li>The semantics of offsetExists can differ</li>
|
||||
<li>offsetUnset will not work with typehinted setters</li>
|
||||
</ul>
|
||||
<div class="highlight-php"><div class="highlight"><pre><span class="cp"><?php</span>
|
||||
|
||||
<span class="k">abstract</span> <span class="k">class</span> <span class="nc">DomainObject</span> <span class="k">implements</span> <span class="nx">ArrayAccess</span>
|
||||
<span class="p">{</span>
|
||||
<span class="k">public</span> <span class="k">function</span> <span class="nf">offsetExists</span><span class="p">(</span><span class="nv">$offset</span><span class="p">)</span>
|
||||
<span class="p">{</span>
|
||||
<span class="c1">// In this example we say that exists means it is not null</span>
|
||||
<span class="nv">$value</span> <span class="o">=</span> <span class="nv">$this</span><span class="o">-></span><span class="p">{</span><span class="s2">"get</span><span class="si">$offset</span><span class="s2">"</span><span class="p">}();</span>
|
||||
<span class="k">return</span> <span class="nv">$value</span> <span class="o">!==</span> <span class="k">null</span><span class="p">;</span>
|
||||
<span class="p">}</span>
|
||||
|
||||
<span class="k">public</span> <span class="k">function</span> <span class="nf">offsetSet</span><span class="p">(</span><span class="nv">$offset</span><span class="p">,</span> <span class="nv">$value</span><span class="p">)</span>
|
||||
<span class="p">{</span>
|
||||
<span class="nv">$this</span><span class="o">-></span><span class="p">{</span><span class="s2">"set</span><span class="si">$offset</span><span class="s2">"</span><span class="p">}(</span><span class="nv">$value</span><span class="p">);</span>
|
||||
<span class="p">}</span>
|
||||
|
||||
<span class="k">public</span> <span class="k">function</span> <span class="nf">offsetGet</span><span class="p">(</span><span class="nv">$offset</span><span class="p">)</span>
|
||||
<span class="p">{</span>
|
||||
<span class="k">return</span> <span class="nv">$this</span><span class="o">-></span><span class="p">{</span><span class="s2">"get</span><span class="si">$offset</span><span class="s2">"</span><span class="p">}();</span>
|
||||
<span class="p">}</span>
|
||||
|
||||
<span class="k">public</span> <span class="k">function</span> <span class="nf">offsetUnset</span><span class="p">(</span><span class="nv">$offset</span><span class="p">)</span>
|
||||
<span class="p">{</span>
|
||||
<span class="nv">$this</span><span class="o">-></span><span class="p">{</span><span class="s2">"set</span><span class="si">$offset</span><span class="s2">"</span><span class="p">}(</span><span class="k">null</span><span class="p">);</span>
|
||||
<span class="p">}</span>
|
||||
<span class="p">}</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="section" id="read-only">
|
||||
<h2>Read-only<a class="headerlink" href="#read-only" title="Permalink to this headline">¶</a></h2>
|
||||
<p>You can slightly tweak option 1 or option 2 in order to make array
|
||||
access read-only. This will also circumvent some of the caveats of
|
||||
each option. Simply make offsetSet and offsetUnset throw an
|
||||
exception (i.e. BadMethodCallException).</p>
|
||||
<div class="highlight-php"><div class="highlight"><pre><span class="cp"><?php</span>
|
||||
|
||||
<span class="k">abstract</span> <span class="k">class</span> <span class="nc">DomainObject</span> <span class="k">implements</span> <span class="nx">ArrayAccess</span>
|
||||
<span class="p">{</span>
|
||||
<span class="k">public</span> <span class="k">function</span> <span class="nf">offsetExists</span><span class="p">(</span><span class="nv">$offset</span><span class="p">)</span>
|
||||
<span class="p">{</span>
|
||||
<span class="c1">// option 1 or option 2</span>
|
||||
<span class="p">}</span>
|
||||
|
||||
<span class="k">public</span> <span class="k">function</span> <span class="nf">offsetSet</span><span class="p">(</span><span class="nv">$offset</span><span class="p">,</span> <span class="nv">$value</span><span class="p">)</span>
|
||||
<span class="p">{</span>
|
||||
<span class="k">throw</span> <span class="k">new</span> <span class="nx">BadMethodCallException</span><span class="p">(</span><span class="s2">"Array access of class "</span> <span class="o">.</span> <span class="nb">get_class</span><span class="p">(</span><span class="nv">$this</span><span class="p">)</span> <span class="o">.</span> <span class="s2">" is read-only!"</span><span class="p">);</span>
|
||||
<span class="p">}</span>
|
||||
|
||||
<span class="k">public</span> <span class="k">function</span> <span class="nf">offsetGet</span><span class="p">(</span><span class="nv">$offset</span><span class="p">)</span>
|
||||
<span class="p">{</span>
|
||||
<span class="c1">// option 1 or option 2</span>
|
||||
<span class="p">}</span>
|
||||
|
||||
<span class="k">public</span> <span class="k">function</span> <span class="nf">offsetUnset</span><span class="p">(</span><span class="nv">$offset</span><span class="p">)</span>
|
||||
<span class="p">{</span>
|
||||
<span class="k">throw</span> <span class="k">new</span> <span class="nx">BadMethodCallException</span><span class="p">(</span><span class="s2">"Array access of class "</span> <span class="o">.</span> <span class="nb">get_class</span><span class="p">(</span><span class="nv">$this</span><span class="p">)</span> <span class="o">.</span> <span class="s2">" is read-only!"</span><span class="p">);</span>
|
||||
<span class="p">}</span>
|
||||
<span class="p">}</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
<div class="sphinxsidebar">
|
||||
<div class="sphinxsidebarwrapper">
|
||||
|
||||
<div id="searchbox" style="">
|
||||
<h3>Search</h3>
|
||||
<form class="search" action="http://readthedocs.org/search/project/" method="get">
|
||||
<input type="text" name="q" size="18">
|
||||
<input type="submit" value="Go">
|
||||
<input type="hidden" name="selected_facets" value="project:">
|
||||
</form>
|
||||
</div>
|
||||
<h3><a href="../index.html">Table Of Contents</a></h3>
|
||||
<ul>
|
||||
<li><a class="reference internal" href="#">Implementing ArrayAccess for Domain Objects</a><ul>
|
||||
<li><a class="reference internal" href="#option-1">Option 1</a></li>
|
||||
<li><a class="reference internal" href="#option-2">Option 2</a></li>
|
||||
<li><a class="reference internal" href="#read-only">Read-only</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<h3>This Page</h3>
|
||||
<ul class="this-page-menu">
|
||||
<li><a href="../_sources/cookbook/implementing-array-access-for-domain-objects.rst.txt"
|
||||
rel="nofollow">Show Source</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<div class="clearer"></div>
|
||||
</div>
|
||||
<div class="footer">
|
||||
© Copyright 2013, Doctrine Project Team.
|
||||
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.6.2.
|
||||
<br/>
|
||||
<a target="_BLANK" href="http://www.servergrove.com"><img src="http://www.doctrine-project.org/_static/servergrove.jpg" /></a> <br/><br/>
|
||||
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
|
||||
<input type="hidden" name="cmd" value="_s-xclick" />
|
||||
<input type="hidden" name="hosted_button_id" value="BAE2E3XANQ77Y" />
|
||||
<input type="image" src="https://www.paypal.com/en_US/i/btn/btn_donateCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!" />
|
||||
<img alt="" border="0" src="https://www.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1" />
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="bot-rcnr">
|
||||
<div class="tl"><!-- corner --></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
|
||||
</script>
|
||||
<script type="text/javascript">
|
||||
_uacct = "UA-288343-7";
|
||||
urchinTracker();
|
||||
</script>
|
||||
<a class="githublink" href="http://github.com/doctrine"><img src="https://s3.amazonaws.com/github/ribbons/forkme_right_orange_ff7600.png" alt="Fork me on GitHub"></a>
|
||||
</body>
|
||||
</html>
|
||||