2013-03-17 02:36:36 +04:00
|
|
|
Getting Started with Doctrine
|
|
|
|
=============================
|
2010-11-01 23:16:12 +03:00
|
|
|
|
2013-03-17 02:36:36 +04:00
|
|
|
This guide covers getting started with the Doctrine ORM. After working
|
|
|
|
through the guide you should know:
|
2012-06-16 15:34:23 +04:00
|
|
|
|
2013-03-17 02:36:36 +04:00
|
|
|
- How to install and configure Doctrine by connecting it to a database
|
|
|
|
- Mapping PHP objects to database tables
|
|
|
|
- Generating a database schema from PHP objects
|
|
|
|
- Using the ``EntityManager`` to insert, update, delete and find
|
|
|
|
objects in the database.
|
|
|
|
|
|
|
|
Guide Assumptions
|
|
|
|
-----------------
|
|
|
|
|
|
|
|
This guide is designed for beginners that haven't worked with Doctrine ORM
|
|
|
|
before. There are some prerequesites for the tutorial that have to be
|
|
|
|
installed:
|
|
|
|
|
|
|
|
- PHP 5.3.3 or above
|
|
|
|
- Composer Package Manager (`Install Composer
|
|
|
|
<http://getcomposer.org/doc/00-intro.md>`_)
|
2011-08-27 14:36:37 +04:00
|
|
|
|
2013-03-17 02:36:36 +04:00
|
|
|
The code of this tutorial is `available on Github <https://github.com/doctrine/doctrine2-orm-tutorial>`_.
|
2011-08-27 14:36:37 +04:00
|
|
|
|
2013-03-17 02:36:36 +04:00
|
|
|
.. note::
|
2010-11-01 23:16:12 +03:00
|
|
|
|
2013-08-18 01:07:29 +04:00
|
|
|
This tutorial assumes you work with **Doctrine 2.4** and above.
|
2013-03-17 02:36:36 +04:00
|
|
|
Some of the code will not work with lower versions.
|
2010-11-01 23:16:12 +03:00
|
|
|
|
2013-03-17 02:36:36 +04:00
|
|
|
What is Doctrine?
|
|
|
|
-----------------
|
2011-06-11 11:52:17 +04:00
|
|
|
|
2013-03-17 02:36:36 +04:00
|
|
|
Doctrine 2 is an `object-relational mapper (ORM)
|
|
|
|
<http://en.wikipedia.org/wiki/Object-relational_mapping>`_ for PHP 5.3.3+ that
|
|
|
|
provides transparent persistence for PHP objects. It uses the Data Mapper
|
|
|
|
pattern at the heart, aiming for a complete separation of your domain/business
|
|
|
|
logic from the persistence in a relational database management system.
|
|
|
|
|
|
|
|
The benefit of Doctrine for the programmer is the ability to focus
|
|
|
|
on the object-oriented business logic and worry about persistence only
|
|
|
|
as a secondary problem. This doesn't mean persistence is downplayed by Doctrine
|
|
|
|
2, however it is our belief that there are considerable benefits for
|
2013-03-17 15:26:34 +04:00
|
|
|
object-oriented programming if persistence and entities are kept
|
2013-03-17 02:36:36 +04:00
|
|
|
separated.
|
2010-11-01 23:16:12 +03:00
|
|
|
|
2013-03-17 16:43:16 +04:00
|
|
|
What are Entities?
|
|
|
|
~~~~~~~~~~~~~~~~~~
|
|
|
|
|
|
|
|
Entities are PHP Objects that can be identified over many requests
|
|
|
|
by a unique identifier or primary key. These classes don't need to extend any
|
|
|
|
abstract base class or interface. An entity class must not be final
|
|
|
|
or contain final methods. Additionally it must not implement
|
|
|
|
**clone** nor **wakeup** or :doc:`do so safely <../cookbook/implementing-wakeup-or-clone>`.
|
|
|
|
|
|
|
|
An entity contains persistable properties. A persistable property
|
|
|
|
is an instance variable of the entity that is saved into and retrieved from the database
|
|
|
|
by Doctrine's data mapping capabilities.
|
|
|
|
|
2010-11-01 23:16:12 +03:00
|
|
|
An Example Model: Bug Tracker
|
|
|
|
-----------------------------
|
|
|
|
|
|
|
|
For this Getting Started Guide for Doctrine we will implement the
|
|
|
|
Bug Tracker domain model from the
|
|
|
|
`Zend\_Db\_Table <http://framework.zend.com/manual/en/zend.db.table.html>`_
|
|
|
|
documentation. Reading their documentation we can extract the
|
2013-03-17 02:36:36 +04:00
|
|
|
requirements:
|
2010-11-01 23:16:12 +03:00
|
|
|
|
|
|
|
- A Bugs has a description, creation date, status, reporter and
|
|
|
|
engineer
|
|
|
|
- A bug can occur on different products (platforms)
|
|
|
|
- Products have a name.
|
|
|
|
- Bug Reporter and Engineers are both Users of the System.
|
|
|
|
- A user can create new bugs.
|
|
|
|
- The assigned engineer can close a bug.
|
|
|
|
- A user can see all his reported or assigned bugs.
|
|
|
|
- Bugs can be paginated through a list-view.
|
|
|
|
|
2011-08-27 14:36:37 +04:00
|
|
|
Setup Project
|
|
|
|
-------------
|
|
|
|
|
2012-12-23 16:05:54 +04:00
|
|
|
Create a new empty folder for this tutorial project, for example
|
|
|
|
``doctrine2-tutorial`` and create a new file ``composer.json`` with
|
|
|
|
the following contents:
|
2011-08-27 14:36:37 +04:00
|
|
|
|
|
|
|
::
|
|
|
|
|
2012-12-23 16:05:54 +04:00
|
|
|
{
|
|
|
|
"require": {
|
2013-08-18 08:15:03 +04:00
|
|
|
"doctrine/orm": "2.4.*",
|
2012-12-23 16:05:54 +04:00
|
|
|
"symfony/yaml": "2.*"
|
|
|
|
},
|
|
|
|
"autoload": {
|
2013-03-17 16:43:16 +04:00
|
|
|
"psr-0": {"": "src/"}
|
2013-08-18 08:15:03 +04:00
|
|
|
},
|
|
|
|
"minimum-stability" : "dev"
|
2012-12-23 16:05:54 +04:00
|
|
|
}
|
2011-08-27 14:36:37 +04:00
|
|
|
|
2013-08-18 08:15:03 +04:00
|
|
|
|
2012-12-23 16:05:54 +04:00
|
|
|
Install Doctrine using the Composer Dependency Management tool, by calling:
|
2011-08-27 14:36:37 +04:00
|
|
|
|
|
|
|
::
|
|
|
|
|
2012-12-23 16:05:54 +04:00
|
|
|
$ composer install
|
|
|
|
|
2013-03-12 02:11:50 +04:00
|
|
|
This will install the packages Doctrine Common, Doctrine DBAL, Doctrine ORM,
|
2013-08-18 01:07:29 +04:00
|
|
|
Symfony YAML and Symfony Console into the `vendor` directory. The Symfony
|
|
|
|
dependencies are not required by Doctrine but will be used in this tutorial.
|
2011-08-27 14:36:37 +04:00
|
|
|
|
2013-08-18 08:15:03 +04:00
|
|
|
Add the following directories:
|
2013-08-18 01:07:29 +04:00
|
|
|
::
|
|
|
|
|
|
|
|
doctrine2-tutorial
|
2011-08-27 14:36:37 +04:00
|
|
|
|-- config
|
|
|
|
| |-- xml
|
|
|
|
| `-- yaml
|
2013-08-18 08:15:03 +04:00
|
|
|
`-- src
|
2010-11-01 23:16:12 +03:00
|
|
|
|
2013-03-17 16:43:16 +04:00
|
|
|
Obtaining the EntityManager
|
|
|
|
---------------------------
|
2010-11-01 23:16:12 +03:00
|
|
|
|
2013-03-17 16:43:16 +04:00
|
|
|
Doctrine's public interface is the EntityManager, it provides the
|
|
|
|
access point to the complete lifecycle management of your entities
|
|
|
|
and transforms entities from and back to persistence. You have to
|
|
|
|
configure and create it to use your entities with Doctrine 2. I
|
|
|
|
will show the configuration steps and then discuss them step by
|
|
|
|
step:
|
2010-11-01 23:16:12 +03:00
|
|
|
|
2010-12-03 22:13:10 +03:00
|
|
|
.. code-block:: php
|
2010-11-01 23:16:12 +03:00
|
|
|
|
|
|
|
<?php
|
2013-03-17 16:43:16 +04:00
|
|
|
// bootstrap.php
|
|
|
|
use Doctrine\ORM\Tools\Setup;
|
2013-08-18 08:15:03 +04:00
|
|
|
use Doctrine\ORM\EntityManager;
|
2013-08-18 01:07:29 +04:00
|
|
|
|
2013-03-17 16:43:16 +04:00
|
|
|
require_once "vendor/autoload.php";
|
2013-08-18 01:07:29 +04:00
|
|
|
|
2013-08-18 08:15:03 +04:00
|
|
|
// Create a simple "default" Doctrine ORM configuration for Annotations
|
2013-03-17 16:43:16 +04:00
|
|
|
$isDevMode = true;
|
2013-04-26 13:05:50 +04:00
|
|
|
$config = Setup::createAnnotationMetadataConfiguration(array(__DIR__."/src"), $isDevMode);
|
2013-08-18 08:15:03 +04:00
|
|
|
// or if you prefer yaml or XML
|
2013-03-17 16:43:16 +04:00
|
|
|
//$config = Setup::createXMLMetadataConfiguration(array(__DIR__."/config/xml"), $isDevMode);
|
|
|
|
//$config = Setup::createYAMLMetadataConfiguration(array(__DIR__."/config/yaml"), $isDevMode);
|
2013-08-18 01:07:29 +04:00
|
|
|
|
2013-03-17 16:43:16 +04:00
|
|
|
// database configuration parameters
|
|
|
|
$conn = array(
|
|
|
|
'driver' => 'pdo_sqlite',
|
|
|
|
'path' => __DIR__ . '/db.sqlite',
|
|
|
|
);
|
2013-08-18 01:07:29 +04:00
|
|
|
|
2013-03-17 16:43:16 +04:00
|
|
|
// obtaining the entity manager
|
2013-08-18 08:15:03 +04:00
|
|
|
$entityManager = EntityManager::create($conn, $config);
|
2013-03-17 16:43:16 +04:00
|
|
|
|
|
|
|
The first require statement sets up the autoloading capabilities of Doctrine
|
|
|
|
using the Composer autoload.
|
|
|
|
|
|
|
|
The second block consists of the instantiation of the ORM
|
|
|
|
``Configuration`` object using the Setup helper. It assumes a bunch
|
|
|
|
of defaults that you don't have to bother about for now. You can
|
|
|
|
read up on the configuration details in the
|
|
|
|
:doc:`reference chapter on configuration <../reference/configuration>`.
|
|
|
|
|
|
|
|
The third block shows the configuration options required to connect
|
|
|
|
to a database, in my case a file-based sqlite database. All the
|
|
|
|
configuration options for all the shipped drivers are given in the
|
|
|
|
`DBAL Configuration section of the manual <http://www.doctrine-project.org/documentation/manual/2_0/en/dbal>`_.
|
|
|
|
|
|
|
|
The last block shows how the ``EntityManager`` is obtained from a
|
|
|
|
factory method.
|
|
|
|
|
|
|
|
Generating the Database Schema
|
|
|
|
------------------------------
|
|
|
|
|
|
|
|
Now that we have defined the Metadata Mappings and bootstrapped the
|
|
|
|
EntityManager we want to generate the relational database schema
|
|
|
|
from it. Doctrine has a Command-Line-Interface that allows you to
|
|
|
|
access the SchemaTool, a component that generates the required
|
|
|
|
tables to work with the metadata.
|
|
|
|
|
|
|
|
For the command-line tool to work a cli-config.php file has to be
|
|
|
|
present in the project root directory, where you will execute the
|
|
|
|
doctrine command. Its a fairly simple file:
|
|
|
|
|
|
|
|
.. code-block:: php
|
|
|
|
|
|
|
|
<?php
|
|
|
|
// cli-config.php
|
|
|
|
require_once "bootstrap.php";
|
2013-08-18 01:07:29 +04:00
|
|
|
|
2013-08-18 08:15:03 +04:00
|
|
|
return \Doctrine\ORM\Tools\Console\ConsoleRunner::createHelperSet($entityManager);
|
2013-03-17 16:43:16 +04:00
|
|
|
|
|
|
|
You can then change into your project directory and call the
|
|
|
|
Doctrine command-line tool:
|
|
|
|
|
|
|
|
::
|
|
|
|
|
|
|
|
$ cd project/
|
|
|
|
$ php vendor/bin/doctrine orm:schema-tool:create
|
|
|
|
|
|
|
|
During the development you probably need to re-create the database
|
|
|
|
several times when changing the Entity metadata. You can then
|
|
|
|
either re-create the database:
|
|
|
|
|
|
|
|
::
|
|
|
|
|
|
|
|
$ php vendor/bin/doctrine orm:schema-tool:drop --force
|
|
|
|
$ php vendor/bin/doctrine orm:schema-tool:create
|
|
|
|
|
|
|
|
Or use the update functionality:
|
|
|
|
|
|
|
|
::
|
|
|
|
|
|
|
|
$ php vendor/bin/doctrine orm:schema-tool:update --force
|
|
|
|
|
|
|
|
The updating of databases uses a Diff Algorithm for a given
|
|
|
|
Database Schema, a cornerstone of the ``Doctrine\DBAL`` package,
|
|
|
|
which can even be used without the Doctrine ORM package. However
|
|
|
|
its not available in SQLite since it does not support ALTER TABLE.
|
|
|
|
|
|
|
|
Starting with the Product
|
|
|
|
-------------------------
|
|
|
|
|
|
|
|
We start with the Product entity requirements, because it is the most simple one
|
|
|
|
to get started. Create a ``src/Product.php`` file and put the ``Product``
|
|
|
|
entity definition in there:
|
2012-01-06 01:33:15 +04:00
|
|
|
|
|
|
|
.. code-block:: php
|
|
|
|
|
|
|
|
<?php
|
2013-03-17 15:45:49 +04:00
|
|
|
// src/Product.php
|
2010-11-01 23:16:12 +03:00
|
|
|
class Product
|
|
|
|
{
|
2013-03-17 02:36:36 +04:00
|
|
|
/**
|
|
|
|
* @var int
|
|
|
|
*/
|
2011-08-27 14:36:37 +04:00
|
|
|
protected $id;
|
2013-03-17 02:36:36 +04:00
|
|
|
/**
|
|
|
|
* @var string
|
|
|
|
*/
|
2011-08-27 14:36:37 +04:00
|
|
|
protected $name;
|
|
|
|
|
|
|
|
public function getId()
|
|
|
|
{
|
|
|
|
return $this->id;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function getName()
|
|
|
|
{
|
|
|
|
return $this->name;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function setName($name)
|
|
|
|
{
|
|
|
|
$this->name = $name;
|
|
|
|
}
|
2010-11-01 23:16:12 +03:00
|
|
|
}
|
2012-01-06 01:33:15 +04:00
|
|
|
|
2013-03-17 16:43:16 +04:00
|
|
|
Note how the properties have getter and setter methods defined except
|
2013-04-09 02:00:16 +04:00
|
|
|
``$id``. To access data from entities Doctrine 2 uses the Reflection API, so it
|
|
|
|
is possible for Doctrine to access the value of ``$id``. You don't have to
|
2013-03-17 16:43:16 +04:00
|
|
|
take Doctrine into account when designing access to the state of your objects.
|
|
|
|
|
|
|
|
The next step for persistence with Doctrine is to describe the
|
|
|
|
structure of the ``Product`` entity to Doctrine using a metadata
|
|
|
|
language. The metadata language describes how entities, their
|
|
|
|
properties and references should be persisted and what constraints
|
|
|
|
should be applied to them.
|
|
|
|
|
2013-04-09 02:00:16 +04:00
|
|
|
Metadata for entities are configured using a XML, YAML or Docblock Annotations.
|
|
|
|
This Getting Started Guide will show the mappings for all Mapping Drivers.
|
2013-03-17 16:43:16 +04:00
|
|
|
References in the text will be made to the XML mapping.
|
|
|
|
|
|
|
|
.. configuration-block::
|
|
|
|
|
|
|
|
.. code-block:: php
|
|
|
|
|
|
|
|
<?php
|
|
|
|
// src/Product.php
|
|
|
|
/**
|
|
|
|
* @Entity @Table(name="products")
|
|
|
|
**/
|
|
|
|
class Product
|
|
|
|
{
|
|
|
|
/** @Id @Column(type="integer") @GeneratedValue **/
|
|
|
|
protected $id;
|
|
|
|
/** @Column(type="string") **/
|
|
|
|
protected $name;
|
|
|
|
|
|
|
|
// .. (other code)
|
|
|
|
}
|
|
|
|
|
|
|
|
.. code-block:: xml
|
|
|
|
|
|
|
|
<!-- config/xml/Product.dcm.xml -->
|
|
|
|
<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://raw.github.com/doctrine/doctrine2/master/doctrine-mapping.xsd">
|
|
|
|
|
|
|
|
<entity name="Product" table="products">
|
|
|
|
<id name="id" type="integer">
|
|
|
|
<generator strategy="AUTO" />
|
|
|
|
</id>
|
|
|
|
|
|
|
|
<field name="name" type="string" />
|
|
|
|
</entity>
|
|
|
|
</doctrine-mapping>
|
|
|
|
|
|
|
|
.. code-block:: yaml
|
|
|
|
|
|
|
|
# config/yaml/Product.dcm.yml
|
|
|
|
Product:
|
|
|
|
type: entity
|
|
|
|
table: products
|
|
|
|
id:
|
|
|
|
id:
|
|
|
|
type: integer
|
|
|
|
generator:
|
|
|
|
strategy: AUTO
|
|
|
|
fields:
|
|
|
|
name:
|
|
|
|
type: string
|
|
|
|
|
|
|
|
The top-level ``entity`` definition tag specifies information about
|
|
|
|
the class and table-name. The primitive type ``Product::$name`` is
|
|
|
|
defined as ``field`` attributes. The Id property is defined with
|
|
|
|
the ``id`` tag. The id has a ``generator`` tag nested inside which
|
|
|
|
defines that the primary key generation mechanism automatically
|
|
|
|
uses the database platforms native id generation strategy, for
|
|
|
|
example AUTO INCREMENT in the case of MySql or Sequences in the
|
|
|
|
case of PostgreSql and Oracle.
|
|
|
|
|
|
|
|
You have to update the database now, because we have a first Entity now:
|
|
|
|
|
|
|
|
::
|
|
|
|
|
2013-04-09 02:00:16 +04:00
|
|
|
$ php vendor/bin/doctrine orm:schema-tool:update --force --dump-sql
|
2013-03-17 16:43:16 +04:00
|
|
|
|
2013-04-09 02:00:16 +04:00
|
|
|
Specifying both flags ``--force`` and ``-dump-sql`` prints and executes the DDL
|
|
|
|
statements.
|
|
|
|
|
|
|
|
Now create a new script that will insert products into the database:
|
2013-03-17 16:43:16 +04:00
|
|
|
|
|
|
|
.. code-block:: php
|
|
|
|
|
|
|
|
<?php
|
|
|
|
// create_product.php
|
|
|
|
require_once "bootstrap.php";
|
|
|
|
|
|
|
|
$newProductName = $argv[1];
|
|
|
|
|
|
|
|
$product = new Product();
|
|
|
|
$product->setName($newProductName);
|
|
|
|
|
|
|
|
$entityManager->persist($product);
|
|
|
|
$entityManager->flush();
|
|
|
|
|
|
|
|
echo "Created Product with ID " . $product->getId() . "\n";
|
|
|
|
|
2013-04-09 02:00:16 +04:00
|
|
|
Call this script from the command line to see how new products are created:
|
2013-03-17 16:43:16 +04:00
|
|
|
|
|
|
|
::
|
|
|
|
|
|
|
|
$ php create_product.php ORM
|
|
|
|
$ php create_product.php DBAL
|
|
|
|
|
2013-04-09 02:00:16 +04:00
|
|
|
What is happening here? Using the ``Product`` is pretty standard OOP.
|
|
|
|
The interesting bits are the use of the ``EntityManager`` service. To
|
2013-03-17 16:43:16 +04:00
|
|
|
notify the EntityManager that a new entity should be inserted into the database
|
2013-04-09 02:00:16 +04:00
|
|
|
you have to call ``persist()``. To intiate a transaction to actually perform
|
|
|
|
the insertion, You have to explicitly call ``flush()`` on the ``EntityManager``.
|
2013-03-17 16:43:16 +04:00
|
|
|
|
2013-04-09 02:00:16 +04:00
|
|
|
This distinction between persist and flush is allows to aggregate all writes
|
2013-03-17 16:43:16 +04:00
|
|
|
(INSERT, UPDATE, DELETE) into one single transaction, which is executed when
|
2013-04-09 02:00:16 +04:00
|
|
|
flush is called. Using this approach the write-performance is significantly
|
2013-03-17 16:43:16 +04:00
|
|
|
better than in a scenario where updates are done for each entity in isolation.
|
|
|
|
|
2013-04-09 02:00:16 +04:00
|
|
|
Doctrine follows the UnitOfWork pattern which additionally detects all entities
|
|
|
|
that were fetched and have changed during the request. You don't have to keep track of
|
|
|
|
entities yourself, when Doctrine already knowns about them.
|
2013-03-17 16:43:16 +04:00
|
|
|
|
2013-04-09 02:00:16 +04:00
|
|
|
As a next step we want to fetch a list of all the products. Let's create a
|
|
|
|
new script for this:
|
2013-03-17 16:43:16 +04:00
|
|
|
|
|
|
|
.. code-block:: php
|
|
|
|
|
|
|
|
<?php
|
|
|
|
// list_products.php
|
2013-04-09 02:00:16 +04:00
|
|
|
require_once "bootstrap.php";
|
|
|
|
|
2013-03-17 16:43:16 +04:00
|
|
|
$productRepository = $entityManager->getRepository('Product');
|
|
|
|
$products = $productRepository->findAll();
|
|
|
|
|
|
|
|
foreach ($products as $product) {
|
|
|
|
echo sprintf("-%s\n", $product->getName());
|
|
|
|
}
|
|
|
|
|
2013-04-09 02:00:16 +04:00
|
|
|
The ``EntityManager#getRepository()`` method can create a finder object (called
|
|
|
|
repository) for every entity. It is provided by Doctrine and contains some
|
|
|
|
finder methods such as ``findAll()``.
|
2013-03-17 16:43:16 +04:00
|
|
|
|
2013-04-09 02:00:16 +04:00
|
|
|
Let's continue with displaying the name of a product based on its ID:
|
2013-03-17 16:43:16 +04:00
|
|
|
|
|
|
|
.. code-block:: php
|
|
|
|
|
|
|
|
<?php
|
2013-04-09 02:00:16 +04:00
|
|
|
// show_product.php <id>
|
|
|
|
require_once "bootstrap.php";
|
|
|
|
|
2013-03-17 16:43:16 +04:00
|
|
|
$id = $argv[1];
|
|
|
|
$product = $entityManager->find('Product', $id);
|
|
|
|
|
2013-04-09 02:00:16 +04:00
|
|
|
if ($product === null) {
|
|
|
|
echo "No product found.\n";
|
|
|
|
exit(1);
|
|
|
|
}
|
|
|
|
|
2013-03-17 16:43:16 +04:00
|
|
|
echo sprintf("-%s\n", $product->getName());
|
|
|
|
|
2013-04-09 02:00:16 +04:00
|
|
|
Updating a product name demonstrates the functionality UnitOfWork of pattern
|
|
|
|
discussed before. We only need to find a product entity and all changes to its
|
|
|
|
properties are written to the database:
|
|
|
|
|
|
|
|
.. code-block:: php
|
|
|
|
|
|
|
|
<?php
|
|
|
|
// update_product.php <id> <new-name>
|
|
|
|
require_once "bootstrap.php";
|
|
|
|
|
|
|
|
$id = $argv[1];
|
|
|
|
$newName = $argv[2];
|
|
|
|
|
|
|
|
$product = $entityManager->find('Product', $id);
|
|
|
|
|
|
|
|
if ($product === null) {
|
|
|
|
echo "Product $id does not exist.\n";
|
|
|
|
exit(1);
|
|
|
|
}
|
|
|
|
|
|
|
|
$product->setName($newName);
|
|
|
|
|
|
|
|
$entityManager->flush();
|
|
|
|
|
|
|
|
After calling this script on one of the existing products, you can verify the
|
|
|
|
product name changed by calling the ``show_product.php`` script.
|
|
|
|
|
2013-03-17 16:43:16 +04:00
|
|
|
Adding Bug and User Entities
|
|
|
|
----------------------------
|
|
|
|
|
2013-04-09 02:00:16 +04:00
|
|
|
We continue with the bug tracker domain, by creating the missing classes
|
|
|
|
``Bug`` and ``User`` and putting them into ``src/Bug.php`` and
|
|
|
|
``src/User.php`` respectively.
|
2013-03-17 16:43:16 +04:00
|
|
|
|
|
|
|
.. code-block:: php
|
|
|
|
|
|
|
|
<?php
|
|
|
|
// src/Bug.php
|
2013-04-09 02:00:16 +04:00
|
|
|
/**
|
|
|
|
* @Entity(repositoryClass="BugRepository") @Table(name="bugs")
|
|
|
|
*/
|
2013-03-17 16:43:16 +04:00
|
|
|
class Bug
|
|
|
|
{
|
|
|
|
/**
|
2013-04-09 02:00:16 +04:00
|
|
|
* @Id @Column(type="integer") @GeneratedValue
|
2013-03-17 16:43:16 +04:00
|
|
|
* @var int
|
|
|
|
*/
|
|
|
|
protected $id;
|
|
|
|
/**
|
2013-04-09 02:00:16 +04:00
|
|
|
* @Column(type="string")
|
2013-03-17 16:43:16 +04:00
|
|
|
* @var string
|
|
|
|
*/
|
|
|
|
protected $description;
|
|
|
|
/**
|
2013-04-09 02:00:16 +04:00
|
|
|
* @Column(type="datetime")
|
2013-03-17 16:43:16 +04:00
|
|
|
* @var DateTime
|
|
|
|
*/
|
|
|
|
protected $created;
|
|
|
|
/**
|
2013-04-09 02:00:16 +04:00
|
|
|
* @Column(type="string")
|
2013-03-17 16:43:16 +04:00
|
|
|
* @var string
|
|
|
|
*/
|
|
|
|
protected $status;
|
|
|
|
|
2013-04-09 02:00:16 +04:00
|
|
|
public function getId()
|
|
|
|
{
|
|
|
|
return $this->id;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function getDescription()
|
|
|
|
{
|
|
|
|
return $this->description;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function setDescription($description)
|
|
|
|
{
|
|
|
|
$this->description = $description;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function setCreated(DateTime $created)
|
|
|
|
{
|
|
|
|
$this->created = $created;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function getCreated()
|
|
|
|
{
|
|
|
|
return $this->created;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function setStatus($status)
|
|
|
|
{
|
|
|
|
$this->status = $status;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function getStatus()
|
|
|
|
{
|
|
|
|
return $this->status;
|
|
|
|
}
|
|
|
|
}
|
2013-03-17 16:43:16 +04:00
|
|
|
|
2012-01-06 01:33:15 +04:00
|
|
|
.. code-block:: php
|
2012-01-29 22:48:09 +04:00
|
|
|
|
2012-06-07 15:53:58 +04:00
|
|
|
<?php
|
2013-03-17 15:45:49 +04:00
|
|
|
// src/User.php
|
2013-04-09 02:00:16 +04:00
|
|
|
/**
|
|
|
|
* @Entity @Table(name="users")
|
|
|
|
*/
|
2010-11-01 23:16:12 +03:00
|
|
|
class User
|
|
|
|
{
|
2013-03-17 02:36:36 +04:00
|
|
|
/**
|
2013-04-09 02:00:16 +04:00
|
|
|
* @Id @GeneratedValue @Column(type="integer")
|
2013-03-17 02:36:36 +04:00
|
|
|
* @var int
|
|
|
|
*/
|
2011-08-27 14:36:37 +04:00
|
|
|
protected $id;
|
2013-03-17 02:36:36 +04:00
|
|
|
/**
|
2013-04-09 02:00:16 +04:00
|
|
|
* @Column(type="string")
|
2013-03-17 02:36:36 +04:00
|
|
|
* @var string
|
|
|
|
*/
|
|
|
|
protected $name;
|
2011-08-27 14:36:37 +04:00
|
|
|
|
|
|
|
public function getId()
|
|
|
|
{
|
|
|
|
return $this->id;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function getName()
|
|
|
|
{
|
|
|
|
return $this->name;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function setName($name)
|
|
|
|
{
|
|
|
|
$this->name = $name;
|
|
|
|
}
|
2010-11-01 23:16:12 +03:00
|
|
|
}
|
|
|
|
|
2013-04-09 02:00:16 +04:00
|
|
|
All of the properties discussed so far are simple string and integer values,
|
|
|
|
for example the id fields of the entities, their names, description, status and
|
|
|
|
change dates. With just the scalar values this model cannot describe the dynamics that we want. We
|
|
|
|
want to model references between entities.
|
2013-03-17 02:36:36 +04:00
|
|
|
|
2013-04-09 02:00:16 +04:00
|
|
|
References between objects are foreign keys in the database. You never have to
|
|
|
|
work with the foreign keys directly, only with objects that represent the
|
|
|
|
foreign key through their own identity.
|
2013-03-17 02:36:36 +04:00
|
|
|
|
2013-04-09 02:00:16 +04:00
|
|
|
For every foreign key you either have a Doctrine ManyToOne or OneToOne
|
|
|
|
association. On the inverse sides of these foreign keys you can have
|
|
|
|
OneToMany associations. Obviously you can have ManyToMany associations
|
|
|
|
that connect two tables with each other through a join table with
|
|
|
|
two foreign keys.
|
2013-03-17 02:36:36 +04:00
|
|
|
|
|
|
|
Now that you know the basics about references in Doctrine, we can extend the
|
|
|
|
domain model to match the requirements:
|
2010-11-01 23:16:12 +03:00
|
|
|
|
2010-12-03 22:13:10 +03:00
|
|
|
.. code-block:: php
|
2010-11-01 23:16:12 +03:00
|
|
|
|
|
|
|
<?php
|
2013-03-17 15:45:49 +04:00
|
|
|
// src/Bug.php
|
2010-11-01 23:16:12 +03:00
|
|
|
use Doctrine\Common\Collections\ArrayCollection;
|
2013-03-17 15:26:34 +04:00
|
|
|
|
2010-11-01 23:16:12 +03:00
|
|
|
class Bug
|
|
|
|
{
|
2012-01-29 22:48:09 +04:00
|
|
|
// ... (previous code)
|
|
|
|
|
2013-03-17 02:36:36 +04:00
|
|
|
protected $products;
|
2013-03-17 15:26:34 +04:00
|
|
|
|
2010-11-01 23:16:12 +03:00
|
|
|
public function __construct()
|
|
|
|
{
|
|
|
|
$this->products = new ArrayCollection();
|
|
|
|
}
|
|
|
|
}
|
2011-08-27 14:36:37 +04:00
|
|
|
|
|
|
|
.. code-block:: php
|
|
|
|
|
|
|
|
<?php
|
2013-03-17 15:45:49 +04:00
|
|
|
// src/User.php
|
2012-01-06 01:33:15 +04:00
|
|
|
use Doctrine\Common\Collections\ArrayCollection;
|
2010-11-01 23:16:12 +03:00
|
|
|
class User
|
|
|
|
{
|
2012-01-29 22:48:09 +04:00
|
|
|
// ... (previous code)
|
|
|
|
|
2013-03-17 02:36:36 +04:00
|
|
|
protected $reportedBugs;
|
|
|
|
protected $assignedBugs;
|
2013-03-17 15:26:34 +04:00
|
|
|
|
2010-11-01 23:16:12 +03:00
|
|
|
public function __construct()
|
|
|
|
{
|
|
|
|
$this->reportedBugs = new ArrayCollection();
|
|
|
|
$this->assignedBugs = new ArrayCollection();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Whenever an entity is recreated from the database, an Collection
|
|
|
|
implementation of the type Doctrine is injected into your entity
|
|
|
|
instead of an array. Compared to the ArrayCollection this
|
|
|
|
implementation helps the Doctrine ORM understand the changes that
|
|
|
|
have happened to the collection which are noteworthy for
|
|
|
|
persistence.
|
|
|
|
|
|
|
|
.. warning::
|
|
|
|
|
|
|
|
Lazy load proxies always contain an instance of
|
|
|
|
Doctrine's EntityManager and all its dependencies. Therefore a
|
|
|
|
var\_dump() will possibly dump a very large recursive structure
|
|
|
|
which is impossible to render and read. You have to use
|
|
|
|
``Doctrine\Common\Util\Debug::dump()`` to restrict the dumping to a
|
|
|
|
human readable level. Additionally you should be aware that dumping
|
|
|
|
the EntityManager to a Browser may take several minutes, and the
|
|
|
|
Debug::dump() method just ignores any occurrences of it in Proxy
|
|
|
|
instances.
|
|
|
|
|
|
|
|
Because we only work with collections for the references we must be
|
|
|
|
careful to implement a bidirectional reference in the domain model.
|
|
|
|
The concept of owning or inverse side of a relation is central to
|
|
|
|
this notion and should always be kept in mind. The following
|
|
|
|
assumptions are made about relations and have to be followed to be
|
|
|
|
able to work with Doctrine 2. These assumptions are not unique to
|
|
|
|
Doctrine 2 but are best practices in handling database relations
|
|
|
|
and Object-Relational Mapping.
|
|
|
|
|
|
|
|
|
|
|
|
- Changes to Collections are saved or updated, when the entity on
|
|
|
|
the *owning* side of the collection is saved or updated.
|
|
|
|
- Saving an Entity at the inverse side of a relation never
|
|
|
|
triggers a persist operation to changes to the collection.
|
|
|
|
- In a one-to-one relation the entity holding the foreign key of
|
|
|
|
the related entity on its own database table is *always* the owning
|
|
|
|
side of the relation.
|
|
|
|
- In a many-to-many relation, both sides can be the owning side of
|
|
|
|
the relation. However in a bi-directional many-to-many relation
|
|
|
|
only one is allowed to be.
|
|
|
|
- In a many-to-one relation the Many-side is the owning side by
|
|
|
|
default, because it holds the foreign key.
|
|
|
|
- The OneToMany side of a relation is inverse by default, since
|
|
|
|
the foreign key is saved on the Many side. A OneToMany relation can
|
|
|
|
only be the owning side, if its implemented using a ManyToMany
|
|
|
|
relation with join table and restricting the one side to allow only
|
|
|
|
UNIQUE values per database constraint.
|
|
|
|
|
|
|
|
.. note::
|
|
|
|
|
|
|
|
Consistency of bi-directional references on the inverse side of a
|
|
|
|
relation have to be managed in userland application code. Doctrine
|
|
|
|
cannot magically update your collections to be consistent.
|
|
|
|
|
|
|
|
|
|
|
|
In the case of Users and Bugs we have references back and forth to
|
|
|
|
the assigned and reported bugs from a user, making this relation
|
|
|
|
bi-directional. We have to change the code to ensure consistency of
|
|
|
|
the bi-directional reference:
|
|
|
|
|
2010-12-03 22:13:10 +03:00
|
|
|
.. code-block:: php
|
2010-11-01 23:16:12 +03:00
|
|
|
|
|
|
|
<?php
|
2013-03-17 15:45:49 +04:00
|
|
|
// src/Bug.php
|
2010-11-01 23:16:12 +03:00
|
|
|
class Bug
|
|
|
|
{
|
2012-01-29 22:48:09 +04:00
|
|
|
// ... (previous code)
|
|
|
|
|
2011-08-27 14:36:37 +04:00
|
|
|
protected $engineer;
|
|
|
|
protected $reporter;
|
2013-03-17 15:26:34 +04:00
|
|
|
|
2010-11-01 23:16:12 +03:00
|
|
|
public function setEngineer($engineer)
|
|
|
|
{
|
|
|
|
$engineer->assignedToBug($this);
|
|
|
|
$this->engineer = $engineer;
|
|
|
|
}
|
2013-03-17 15:26:34 +04:00
|
|
|
|
2010-11-01 23:16:12 +03:00
|
|
|
public function setReporter($reporter)
|
|
|
|
{
|
|
|
|
$reporter->addReportedBug($this);
|
|
|
|
$this->reporter = $reporter;
|
|
|
|
}
|
2013-03-17 15:26:34 +04:00
|
|
|
|
2010-11-01 23:16:12 +03:00
|
|
|
public function getEngineer()
|
|
|
|
{
|
|
|
|
return $this->engineer;
|
|
|
|
}
|
2013-03-17 15:26:34 +04:00
|
|
|
|
2010-11-01 23:16:12 +03:00
|
|
|
public function getReporter()
|
|
|
|
{
|
|
|
|
return $this->reporter;
|
|
|
|
}
|
|
|
|
}
|
2011-08-27 14:36:37 +04:00
|
|
|
|
|
|
|
.. code-block:: php
|
|
|
|
|
|
|
|
<?php
|
2013-03-17 15:45:49 +04:00
|
|
|
// src/User.php
|
2010-11-01 23:16:12 +03:00
|
|
|
class User
|
|
|
|
{
|
2012-01-29 22:48:09 +04:00
|
|
|
// ... (previous code)
|
|
|
|
|
2011-08-27 14:36:37 +04:00
|
|
|
protected $reportedBugs = null;
|
|
|
|
protected $assignedBugs = null;
|
2010-12-16 23:59:27 +03:00
|
|
|
|
2010-11-01 23:16:12 +03:00
|
|
|
public function addReportedBug($bug)
|
|
|
|
{
|
|
|
|
$this->reportedBugs[] = $bug;
|
|
|
|
}
|
2013-03-17 15:26:34 +04:00
|
|
|
|
2010-11-01 23:16:12 +03:00
|
|
|
public function assignedToBug($bug)
|
|
|
|
{
|
|
|
|
$this->assignedBugs[] = $bug;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
I chose to name the inverse methods in past-tense, which should
|
|
|
|
indicate that the actual assigning has already taken place and the
|
|
|
|
methods are only used for ensuring consistency of the references.
|
2011-08-27 14:36:37 +04:00
|
|
|
This approach is my personal preference, you can choose whatever
|
|
|
|
method to make this work.
|
|
|
|
|
2010-11-01 23:16:12 +03:00
|
|
|
You can see from ``User::addReportedBug()`` and
|
|
|
|
``User::assignedToBug()`` that using this method in userland alone
|
|
|
|
would not add the Bug to the collection of the owning side in
|
2010-12-03 22:13:10 +03:00
|
|
|
``Bug::$reporter`` or ``Bug::$engineer``. Using these methods and
|
2010-11-01 23:16:12 +03:00
|
|
|
calling Doctrine for persistence would not update the collections
|
|
|
|
representation in the database.
|
|
|
|
|
|
|
|
Only using ``Bug::setEngineer()`` or ``Bug::setReporter()``
|
|
|
|
correctly saves the relation information. We also set both
|
|
|
|
collection instance variables to protected, however with PHP 5.3's
|
|
|
|
new features Doctrine is still able to use Reflection to set and
|
|
|
|
get values from protected and private properties.
|
|
|
|
|
|
|
|
The ``Bug::$reporter`` and ``Bug::$engineer`` properties are
|
|
|
|
Many-To-One relations, which point to a User. In a normalized
|
|
|
|
relational model the foreign key is saved on the Bug's table, hence
|
|
|
|
in our object-relation model the Bug is at the owning side of the
|
|
|
|
relation. You should always make sure that the use-cases of your
|
|
|
|
domain model should drive which side is an inverse or owning one in
|
|
|
|
your Doctrine mapping. In our example, whenever a new bug is saved
|
|
|
|
or an engineer is assigned to the bug, we don't want to update the
|
|
|
|
User to persist the reference, but the Bug. This is the case with
|
|
|
|
the Bug being at the owning side of the relation.
|
|
|
|
|
2011-10-26 00:08:52 +04:00
|
|
|
Bugs reference Products by an uni-directional ManyToMany relation in
|
|
|
|
the database that points from Bugs to Products.
|
2010-11-01 23:16:12 +03:00
|
|
|
|
2010-12-03 22:13:10 +03:00
|
|
|
.. code-block:: php
|
2010-11-01 23:16:12 +03:00
|
|
|
|
|
|
|
<?php
|
2013-03-17 15:45:49 +04:00
|
|
|
// src/Bug.php
|
2010-11-01 23:16:12 +03:00
|
|
|
class Bug
|
|
|
|
{
|
2012-01-29 22:48:09 +04:00
|
|
|
// ... (previous code)
|
|
|
|
|
2011-08-27 14:36:37 +04:00
|
|
|
protected $products = null;
|
2013-03-17 15:26:34 +04:00
|
|
|
|
2010-11-01 23:16:12 +03:00
|
|
|
public function assignToProduct($product)
|
|
|
|
{
|
|
|
|
$this->products[] = $product;
|
|
|
|
}
|
2013-03-17 15:26:34 +04:00
|
|
|
|
2010-11-01 23:16:12 +03:00
|
|
|
public function getProducts()
|
|
|
|
{
|
|
|
|
return $this->products;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
We are now finished with the domain model given the requirements.
|
2013-03-17 16:43:16 +04:00
|
|
|
Now we continue adding metadata mappings for the ``User`` and ``Bug``
|
|
|
|
as we did for the ``Product`` before:
|
2010-11-01 23:16:12 +03:00
|
|
|
|
2010-12-16 23:59:27 +03:00
|
|
|
.. configuration-block::
|
|
|
|
.. code-block:: php
|
2010-11-01 23:16:12 +03:00
|
|
|
|
2010-12-16 23:59:27 +03:00
|
|
|
<?php
|
2013-03-17 15:45:49 +04:00
|
|
|
// src/Bug.php
|
2010-12-16 23:59:27 +03:00
|
|
|
/**
|
|
|
|
* @Entity @Table(name="bugs")
|
2012-01-29 22:48:09 +04:00
|
|
|
**/
|
2010-12-16 23:59:27 +03:00
|
|
|
class Bug
|
|
|
|
{
|
|
|
|
/**
|
|
|
|
* @Id @Column(type="integer") @GeneratedValue
|
2012-01-29 22:48:09 +04:00
|
|
|
**/
|
2011-08-27 14:36:37 +04:00
|
|
|
protected $id;
|
2010-12-16 23:59:27 +03:00
|
|
|
/**
|
|
|
|
* @Column(type="string")
|
2012-01-29 22:48:09 +04:00
|
|
|
**/
|
2011-08-27 14:36:37 +04:00
|
|
|
protected $description;
|
2010-12-16 23:59:27 +03:00
|
|
|
/**
|
|
|
|
* @Column(type="datetime")
|
2012-01-29 22:48:09 +04:00
|
|
|
**/
|
2011-08-27 14:36:37 +04:00
|
|
|
protected $created;
|
2010-12-16 23:59:27 +03:00
|
|
|
/**
|
|
|
|
* @Column(type="string")
|
2012-01-29 22:48:09 +04:00
|
|
|
**/
|
2011-08-27 14:36:37 +04:00
|
|
|
protected $status;
|
2010-12-16 23:59:27 +03:00
|
|
|
|
|
|
|
/**
|
|
|
|
* @ManyToOne(targetEntity="User", inversedBy="assignedBugs")
|
2012-01-29 22:48:09 +04:00
|
|
|
**/
|
2011-08-27 14:36:37 +04:00
|
|
|
protected $engineer;
|
2010-12-16 23:59:27 +03:00
|
|
|
|
|
|
|
/**
|
|
|
|
* @ManyToOne(targetEntity="User", inversedBy="reportedBugs")
|
2012-01-29 22:48:09 +04:00
|
|
|
**/
|
2011-08-27 14:36:37 +04:00
|
|
|
protected $reporter;
|
2010-12-16 23:59:27 +03:00
|
|
|
|
|
|
|
/**
|
|
|
|
* @ManyToMany(targetEntity="Product")
|
2012-01-29 22:48:09 +04:00
|
|
|
**/
|
2011-08-27 14:36:37 +04:00
|
|
|
protected $products;
|
2012-01-29 22:48:09 +04:00
|
|
|
|
|
|
|
// ... (other code)
|
2010-12-16 23:59:27 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
.. code-block:: xml
|
|
|
|
|
2011-08-27 14:36:37 +04:00
|
|
|
<!-- config/xml/Bug.dcm.xml -->
|
2010-12-16 23:59:27 +03:00
|
|
|
<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
|
2012-06-16 14:44:00 +04:00
|
|
|
http://raw.github.com/doctrine/doctrine2/master/doctrine-mapping.xsd">
|
2010-12-16 23:59:27 +03:00
|
|
|
|
|
|
|
<entity name="Bug" table="bugs">
|
|
|
|
<id name="id" type="integer">
|
|
|
|
<generator strategy="AUTO" />
|
|
|
|
</id>
|
|
|
|
|
|
|
|
<field name="description" type="text" />
|
|
|
|
<field name="created" type="datetime" />
|
|
|
|
<field name="status" type="string" />
|
|
|
|
|
|
|
|
<many-to-one target-entity="User" field="reporter" inversed-by="reportedBugs" />
|
|
|
|
<many-to-one target-entity="User" field="engineer" inversed-by="assignedBugs" />
|
|
|
|
|
|
|
|
<many-to-many target-entity="Product" field="products" />
|
|
|
|
</entity>
|
|
|
|
</doctrine-mapping>
|
|
|
|
|
|
|
|
.. code-block:: yaml
|
|
|
|
|
2011-08-27 14:36:37 +04:00
|
|
|
# config/yaml/Bug.dcm.yml
|
2010-12-16 23:59:27 +03:00
|
|
|
Bug:
|
|
|
|
type: entity
|
|
|
|
table: bugs
|
|
|
|
id:
|
|
|
|
id:
|
|
|
|
type: integer
|
|
|
|
generator:
|
|
|
|
strategy: AUTO
|
|
|
|
fields:
|
|
|
|
description:
|
|
|
|
type: text
|
|
|
|
created:
|
|
|
|
type: datetime
|
|
|
|
status:
|
|
|
|
type: string
|
|
|
|
manyToOne:
|
|
|
|
reporter:
|
|
|
|
targetEntity: User
|
|
|
|
inversedBy: reportedBugs
|
|
|
|
engineer:
|
|
|
|
targetEntity: User
|
|
|
|
inversedBy: assignedBugs
|
|
|
|
manyToMany:
|
|
|
|
products:
|
|
|
|
targetEntity: Product
|
2013-03-17 15:26:34 +04:00
|
|
|
|
2010-11-01 23:16:12 +03:00
|
|
|
|
2013-03-17 16:43:16 +04:00
|
|
|
Here we have the entity, id and primitive type definitions.
|
2010-11-01 23:16:12 +03:00
|
|
|
The column names are used from the Zend\_Db\_Table examples and
|
|
|
|
have different names than the properties on the Bug class.
|
|
|
|
Additionally for the "created" field it is specified that it is of
|
|
|
|
the Type "DATETIME", which translates the YYYY-mm-dd HH:mm:ss
|
|
|
|
Database format into a PHP DateTime instance and back.
|
|
|
|
|
|
|
|
After the field definitions the two qualified references to the
|
|
|
|
user entity are defined. They are created by the ``many-to-one``
|
|
|
|
tag. The class name of the related entity has to be specified with
|
|
|
|
the ``target-entity`` attribute, which is enough information for
|
2011-02-26 13:12:58 +03:00
|
|
|
the database mapper to access the foreign-table. Since
|
2010-11-01 23:16:12 +03:00
|
|
|
``reporter`` and ``engineer`` are on the owning side of a
|
|
|
|
bi-directional relation we also have to specify the ``inversed-by``
|
|
|
|
attribute. They have to point to the field names on the inverse
|
2011-02-26 13:12:58 +03:00
|
|
|
side of the relationship. We will see in the next example that the ``inversed-by``
|
|
|
|
attribute has a counterpart ``mapped-by`` which makes that
|
|
|
|
the inverse side.
|
2010-11-01 23:16:12 +03:00
|
|
|
|
|
|
|
The last missing property is the ``Bug::$products`` collection. It
|
|
|
|
holds all products where the specific bug is occurring in. Again
|
|
|
|
you have to define the ``target-entity`` and ``field`` attributes
|
|
|
|
on the ``many-to-many`` tag. Furthermore you have to specify the
|
|
|
|
details of the many-to-many join-table and its foreign key columns.
|
|
|
|
The definition is rather complex, however relying on the XML
|
|
|
|
auto-completion I got it working easily, although I forget the
|
|
|
|
schema details all the time.
|
|
|
|
|
|
|
|
The last missing definition is that of the User entity:
|
|
|
|
|
2010-12-16 23:59:27 +03:00
|
|
|
.. configuration-block::
|
2010-11-01 23:16:12 +03:00
|
|
|
|
2010-12-16 23:59:27 +03:00
|
|
|
.. code-block:: php
|
|
|
|
|
|
|
|
<?php
|
2013-03-17 15:45:49 +04:00
|
|
|
// src/User.php
|
2010-12-16 23:59:27 +03:00
|
|
|
/**
|
|
|
|
* @Entity @Table(name="users")
|
2012-01-29 22:48:09 +04:00
|
|
|
**/
|
2010-12-16 23:59:27 +03:00
|
|
|
class User
|
|
|
|
{
|
|
|
|
/**
|
|
|
|
* @Id @GeneratedValue @Column(type="integer")
|
2012-01-26 20:29:32 +04:00
|
|
|
* @var int
|
2012-01-29 22:48:09 +04:00
|
|
|
**/
|
2011-08-27 14:36:37 +04:00
|
|
|
protected $id;
|
2010-12-16 23:59:27 +03:00
|
|
|
|
|
|
|
/**
|
|
|
|
* @Column(type="string")
|
|
|
|
* @var string
|
2012-01-29 22:48:09 +04:00
|
|
|
**/
|
2011-08-27 14:36:37 +04:00
|
|
|
protected $name;
|
2010-12-16 23:59:27 +03:00
|
|
|
|
|
|
|
/**
|
|
|
|
* @OneToMany(targetEntity="Bug", mappedBy="reporter")
|
|
|
|
* @var Bug[]
|
2012-01-29 22:48:09 +04:00
|
|
|
**/
|
2010-12-16 23:59:27 +03:00
|
|
|
protected $reportedBugs = null;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @OneToMany(targetEntity="Bug", mappedBy="engineer")
|
|
|
|
* @var Bug[]
|
2012-01-29 22:48:09 +04:00
|
|
|
**/
|
2010-12-16 23:59:27 +03:00
|
|
|
protected $assignedBugs = null;
|
|
|
|
|
2012-01-29 22:48:09 +04:00
|
|
|
// .. (other code)
|
|
|
|
}
|
|
|
|
|
2010-12-16 23:59:27 +03:00
|
|
|
.. code-block:: xml
|
|
|
|
|
2011-08-27 14:36:37 +04:00
|
|
|
<!-- config/xml/User.dcm.xml -->
|
2010-12-16 23:59:27 +03:00
|
|
|
<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
|
2012-06-16 14:44:00 +04:00
|
|
|
http://raw.github.com/doctrine/doctrine2/master/doctrine-mapping.xsd">
|
2010-12-16 23:59:27 +03:00
|
|
|
|
2011-08-27 14:36:37 +04:00
|
|
|
<entity name="User" table="users">
|
2010-12-16 23:59:27 +03:00
|
|
|
<id name="id" type="integer">
|
|
|
|
<generator strategy="AUTO" />
|
|
|
|
</id>
|
|
|
|
|
|
|
|
<field name="name" type="string" />
|
|
|
|
|
|
|
|
<one-to-many target-entity="Bug" field="reportedBugs" mapped-by="reporter" />
|
|
|
|
<one-to-many target-entity="Bug" field="assignedBugs" mapped-by="engineer" />
|
|
|
|
</entity>
|
|
|
|
</doctrine-mapping>
|
|
|
|
|
|
|
|
.. code-block:: yaml
|
|
|
|
|
2011-08-27 14:36:37 +04:00
|
|
|
# config/xml/User.dcm.yml
|
2010-12-16 23:59:27 +03:00
|
|
|
User:
|
|
|
|
type: entity
|
|
|
|
table: users
|
|
|
|
id:
|
|
|
|
id:
|
|
|
|
type: integer
|
|
|
|
generator:
|
|
|
|
strategy: AUTO
|
|
|
|
fields:
|
|
|
|
name:
|
|
|
|
type: string
|
|
|
|
oneToMany:
|
|
|
|
reportedBugs:
|
|
|
|
targetEntity: Bug
|
|
|
|
mappedBy: reporter
|
|
|
|
assignedBugs:
|
|
|
|
targetEntity: Bug
|
|
|
|
mappedBy: engineer
|
2010-11-01 23:16:12 +03:00
|
|
|
|
|
|
|
Here are some new things to mention about the ``one-to-many`` tags.
|
|
|
|
Remember that we discussed about the inverse and owning side. Now
|
|
|
|
both reportedBugs and assignedBugs are inverse relations, which
|
|
|
|
means the join details have already been defined on the owning
|
|
|
|
side. Therefore we only have to specify the property on the Bug
|
|
|
|
class that holds the owning sides.
|
|
|
|
|
|
|
|
This example has a fair overview of the most basic features of the
|
|
|
|
metadata definition language.
|
|
|
|
|
2013-03-17 16:43:16 +04:00
|
|
|
Implementing more Requirements
|
2010-11-01 23:16:12 +03:00
|
|
|
------------------------------
|
|
|
|
|
2013-03-17 16:43:16 +04:00
|
|
|
For starters we need a create user entities:
|
2010-11-01 23:16:12 +03:00
|
|
|
|
2010-12-03 22:13:10 +03:00
|
|
|
.. code-block:: php
|
2010-11-01 23:16:12 +03:00
|
|
|
|
|
|
|
<?php
|
2011-08-27 14:36:37 +04:00
|
|
|
// create_user.php
|
|
|
|
require_once "bootstrap.php";
|
|
|
|
|
|
|
|
$newUsername = $argv[1];
|
2013-03-17 15:26:34 +04:00
|
|
|
|
2010-11-01 23:16:12 +03:00
|
|
|
$user = new User();
|
2011-08-27 14:36:37 +04:00
|
|
|
$user->setName($newUsername);
|
2013-03-17 15:26:34 +04:00
|
|
|
|
2010-11-01 23:16:12 +03:00
|
|
|
$entityManager->persist($user);
|
|
|
|
$entityManager->flush();
|
|
|
|
|
2011-08-27 14:36:37 +04:00
|
|
|
echo "Created User with ID " . $user->getId() . "\n";
|
|
|
|
|
|
|
|
Now call:
|
|
|
|
|
2011-10-26 00:50:29 +04:00
|
|
|
::
|
2011-08-27 14:36:37 +04:00
|
|
|
|
|
|
|
$ php create_user.php beberlei
|
2010-11-01 23:16:12 +03:00
|
|
|
|
2013-03-17 16:43:16 +04:00
|
|
|
We now have the data to create a bug and the code for this scenario may look
|
|
|
|
like this:
|
2010-11-01 23:16:12 +03:00
|
|
|
|
2010-12-03 22:13:10 +03:00
|
|
|
.. code-block:: php
|
2010-11-01 23:16:12 +03:00
|
|
|
|
|
|
|
<?php
|
2011-08-27 14:36:37 +04:00
|
|
|
// create_bug.php
|
|
|
|
require_once "bootstrap.php";
|
|
|
|
|
|
|
|
$theReporterId = $argv[1];
|
2013-09-05 00:55:06 +04:00
|
|
|
$theDefaultEngineerId = $argv[2];
|
2011-08-27 14:36:37 +04:00
|
|
|
$productIds = explode(",", $argv[3]);
|
|
|
|
|
2010-11-01 23:16:12 +03:00
|
|
|
$reporter = $entityManager->find("User", $theReporterId);
|
|
|
|
$engineer = $entityManager->find("User", $theDefaultEngineerId);
|
2011-08-27 14:36:37 +04:00
|
|
|
if (!$reporter || !$engineer) {
|
|
|
|
echo "No reporter and/or engineer found for the input.\n";
|
|
|
|
exit(1);
|
|
|
|
}
|
2013-03-17 15:26:34 +04:00
|
|
|
|
2010-11-01 23:16:12 +03:00
|
|
|
$bug = new Bug();
|
2011-08-27 14:36:37 +04:00
|
|
|
$bug->setDescription("Something does not work!");
|
|
|
|
$bug->setCreated(new DateTime("now"));
|
|
|
|
$bug->setStatus("OPEN");
|
2013-03-17 15:26:34 +04:00
|
|
|
|
2010-11-01 23:16:12 +03:00
|
|
|
foreach ($productIds AS $productId) {
|
|
|
|
$product = $entityManager->find("Product", $productId);
|
|
|
|
$bug->assignToProduct($product);
|
|
|
|
}
|
2013-03-17 15:26:34 +04:00
|
|
|
|
2010-11-01 23:16:12 +03:00
|
|
|
$bug->setReporter($reporter);
|
|
|
|
$bug->setEngineer($engineer);
|
2013-03-17 15:26:34 +04:00
|
|
|
|
2010-11-01 23:16:12 +03:00
|
|
|
$entityManager->persist($bug);
|
|
|
|
$entityManager->flush();
|
2013-03-17 15:26:34 +04:00
|
|
|
|
2011-08-27 14:36:37 +04:00
|
|
|
echo "Your new Bug Id: ".$bug->getId()."\n";
|
|
|
|
|
|
|
|
Since we only have one user and product, probably with the ID of 1, we can call this script with:
|
|
|
|
|
2011-10-26 00:50:29 +04:00
|
|
|
::
|
2011-08-27 14:36:37 +04:00
|
|
|
|
|
|
|
php create_bug.php 1 1 1
|
2010-11-01 23:16:12 +03:00
|
|
|
|
|
|
|
This is the first contact with the read API of the EntityManager,
|
|
|
|
showing that a call to ``EntityManager#find($name, $id)`` returns a
|
|
|
|
single instance of an entity queried by primary key. Besides this
|
|
|
|
we see the persist + flush pattern again to save the Bug into the
|
|
|
|
database.
|
|
|
|
|
|
|
|
See how simple relating Bug, Reporter, Engineer and Products is
|
|
|
|
done by using the discussed methods in the "A first prototype"
|
|
|
|
section. The UnitOfWork will detect this relations when flush is
|
|
|
|
called and relate them in the database appropriately.
|
|
|
|
|
|
|
|
Queries for Application Use-Cases
|
|
|
|
---------------------------------
|
|
|
|
|
|
|
|
List of Bugs
|
|
|
|
~~~~~~~~~~~~
|
|
|
|
|
|
|
|
Using the previous examples we can fill up the database quite a
|
|
|
|
bit, however we now need to discuss how to query the underlying
|
|
|
|
mapper for the required view representations. When opening the
|
|
|
|
application, bugs can be paginated through a list-view, which is
|
|
|
|
the first read-only use-case:
|
|
|
|
|
2010-12-03 22:13:10 +03:00
|
|
|
.. code-block:: php
|
2010-11-01 23:16:12 +03:00
|
|
|
|
|
|
|
<?php
|
2011-08-27 14:36:37 +04:00
|
|
|
// list_bugs.php
|
|
|
|
require_once "bootstrap.php";
|
|
|
|
|
2010-11-01 23:16:12 +03:00
|
|
|
$dql = "SELECT b, e, r FROM Bug b JOIN b.engineer e JOIN b.reporter r ORDER BY b.created DESC";
|
2013-03-17 15:26:34 +04:00
|
|
|
|
2010-11-01 23:16:12 +03:00
|
|
|
$query = $entityManager->createQuery($dql);
|
|
|
|
$query->setMaxResults(30);
|
|
|
|
$bugs = $query->getResult();
|
2013-03-17 15:26:34 +04:00
|
|
|
|
2010-11-01 23:16:12 +03:00
|
|
|
foreach($bugs AS $bug) {
|
2012-01-06 00:40:15 +04:00
|
|
|
echo $bug->getDescription()." - ".$bug->getCreated()->format('d.m.Y')."\n";
|
2013-06-17 13:36:09 +04:00
|
|
|
echo " Reported by: ".$bug->getReporter()->getName()."\n";
|
|
|
|
echo " Assigned to: ".$bug->getEngineer()->getName()."\n";
|
2010-11-01 23:16:12 +03:00
|
|
|
foreach($bug->getProducts() AS $product) {
|
2013-06-17 13:36:09 +04:00
|
|
|
echo " Platform: ".$product->getName()."\n";
|
2010-11-01 23:16:12 +03:00
|
|
|
}
|
|
|
|
echo "\n";
|
|
|
|
}
|
|
|
|
|
|
|
|
The DQL Query in this example fetches the 30 most recent bugs with
|
|
|
|
their respective engineer and reporter in one single SQL statement.
|
|
|
|
The console output of this script is then:
|
|
|
|
|
|
|
|
::
|
|
|
|
|
|
|
|
Something does not work! - 02.04.2010
|
|
|
|
Reported by: beberlei
|
|
|
|
Assigned to: beberlei
|
|
|
|
Platform: My Product
|
|
|
|
|
|
|
|
.. note::
|
|
|
|
|
|
|
|
**Dql is not Sql**
|
|
|
|
|
|
|
|
You may wonder why we start writing SQL at the beginning of this
|
|
|
|
use-case. Don't we use an ORM to get rid of all the endless
|
|
|
|
hand-writing of SQL? Doctrine introduces DQL which is best
|
|
|
|
described as **object-query-language** and is a dialect of
|
|
|
|
`OQL <http://en.wikipedia.org/wiki/Object_Query_Language>`_ and
|
|
|
|
similar to `HQL <http://www.hibernate.org>`_ or
|
|
|
|
`JPQL <http://en.wikipedia.org/wiki/Java_Persistence_Query_Language>`_.
|
|
|
|
It does not know the concept of columns and tables, but only those
|
|
|
|
of Entity-Class and property. Using the Metadata we defined before
|
|
|
|
it allows for very short distinctive and powerful queries.
|
|
|
|
|
|
|
|
An important reason why DQL is favourable to the Query API of most
|
|
|
|
ORMs is its similarity to SQL. The DQL language allows query
|
|
|
|
constructs that most ORMs don't, GROUP BY even with HAVING,
|
|
|
|
Sub-selects, Fetch-Joins of nested classes, mixed results with
|
|
|
|
entities and scalar data such as COUNT() results and much more.
|
|
|
|
Using DQL you should seldom come to the point where you want to
|
|
|
|
throw your ORM into the dumpster, because it doesn't support some
|
|
|
|
the more powerful SQL concepts.
|
|
|
|
|
|
|
|
Besides handwriting DQL you can however also use the
|
|
|
|
``QueryBuilder`` retrieved by calling
|
|
|
|
``$entityManager->createQueryBuilder()`` which is a Query Object
|
|
|
|
around the DQL language.
|
|
|
|
|
|
|
|
As a last resort you can however also use Native SQL and a
|
|
|
|
description of the result set to retrieve entities from the
|
|
|
|
database. DQL boils down to a Native SQL statement and a
|
|
|
|
``ResultSetMapping`` instance itself. Using Native SQL you could
|
|
|
|
even use stored procedures for data retrieval, or make use of
|
|
|
|
advanced non-portable database queries like PostgreSql's recursive
|
|
|
|
queries.
|
|
|
|
|
|
|
|
|
|
|
|
Array Hydration of the Bug List
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
|
|
|
In the previous use-case we retrieved the result as their
|
|
|
|
respective object instances. We are not limited to retrieving
|
|
|
|
objects only from Doctrine however. For a simple list view like the
|
|
|
|
previous one we only need read access to our entities and can
|
|
|
|
switch the hydration from objects to simple PHP arrays instead.
|
|
|
|
This can obviously yield considerable performance benefits for
|
|
|
|
read-only requests.
|
|
|
|
|
|
|
|
Implementing the same list view as before using array hydration we
|
|
|
|
can rewrite our code:
|
|
|
|
|
2010-12-03 22:13:10 +03:00
|
|
|
.. code-block:: php
|
2010-11-01 23:16:12 +03:00
|
|
|
|
|
|
|
<?php
|
2011-08-27 14:36:37 +04:00
|
|
|
// list_bugs_array.php
|
|
|
|
require_once "bootstrap.php";
|
|
|
|
|
2010-11-01 23:16:12 +03:00
|
|
|
$dql = "SELECT b, e, r, p FROM Bug b JOIN b.engineer e ".
|
|
|
|
"JOIN b.reporter r JOIN b.products p ORDER BY b.created DESC";
|
2011-04-24 09:21:34 +04:00
|
|
|
$query = $entityManager->createQuery($dql);
|
2010-11-01 23:16:12 +03:00
|
|
|
$bugs = $query->getArrayResult();
|
2013-03-17 15:26:34 +04:00
|
|
|
|
2010-11-01 23:16:12 +03:00
|
|
|
foreach ($bugs AS $bug) {
|
|
|
|
echo $bug['description'] . " - " . $bug['created']->format('d.m.Y')."\n";
|
|
|
|
echo " Reported by: ".$bug['reporter']['name']."\n";
|
|
|
|
echo " Assigned to: ".$bug['engineer']['name']."\n";
|
|
|
|
foreach($bug['products'] AS $product) {
|
|
|
|
echo " Platform: ".$product['name']."\n";
|
|
|
|
}
|
|
|
|
echo "\n";
|
|
|
|
}
|
|
|
|
|
|
|
|
There is one significant difference in the DQL query however, we
|
|
|
|
have to add an additional fetch-join for the products connected to
|
|
|
|
a bug. The resulting SQL query for this single select statement is
|
|
|
|
pretty large, however still more efficient to retrieve compared to
|
|
|
|
hydrating objects.
|
|
|
|
|
|
|
|
Find by Primary Key
|
|
|
|
~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
|
|
|
The next Use-Case is displaying a Bug by primary key. This could be
|
|
|
|
done using DQL as in the previous example with a where clause,
|
2013-03-17 02:36:36 +04:00
|
|
|
however there is a convenience method on the ``EntityManager`` that
|
2010-11-01 23:16:12 +03:00
|
|
|
handles loading by primary key, which we have already seen in the
|
|
|
|
write scenarios:
|
|
|
|
|
2010-12-03 22:13:10 +03:00
|
|
|
.. code-block:: php
|
2010-11-01 23:16:12 +03:00
|
|
|
|
|
|
|
<?php
|
2011-08-27 14:36:37 +04:00
|
|
|
// show_bug.php
|
|
|
|
require_once "bootstrap.php";
|
|
|
|
|
|
|
|
$theBugId = $argv[1];
|
|
|
|
|
|
|
|
$bug = $entityManager->find("Bug", (int)$theBugId);
|
|
|
|
|
|
|
|
echo "Bug: ".$bug->getDescription()."\n";
|
2013-03-17 02:36:36 +04:00
|
|
|
echo "Engineer: ".$bug->getEngineer()->getName()."\n";
|
|
|
|
|
|
|
|
The output of the engineers name is fetched from the database! What is happening?
|
2010-11-01 23:16:12 +03:00
|
|
|
|
2013-03-17 02:36:36 +04:00
|
|
|
Since we only retrieved the bug by primary key both the engineer and reporter
|
|
|
|
are not immediately loaded from the database but are replaced by LazyLoading
|
|
|
|
proxies. These proxies will load behind the scenes, when the first method
|
|
|
|
is called on them.
|
2010-11-01 23:16:12 +03:00
|
|
|
|
2013-03-17 02:36:36 +04:00
|
|
|
Sample code of this proxy generated code can be found in the specified Proxy
|
|
|
|
Directory, it looks like:
|
2010-11-01 23:16:12 +03:00
|
|
|
|
2010-12-03 22:13:10 +03:00
|
|
|
.. code-block:: php
|
2010-11-01 23:16:12 +03:00
|
|
|
|
|
|
|
<?php
|
|
|
|
namespace MyProject\Proxies;
|
2013-03-17 15:26:34 +04:00
|
|
|
|
2010-11-01 23:16:12 +03:00
|
|
|
/**
|
|
|
|
* THIS CLASS WAS GENERATED BY THE DOCTRINE ORM. DO NOT EDIT THIS FILE.
|
2012-01-29 22:48:09 +04:00
|
|
|
**/
|
2010-11-01 23:16:12 +03:00
|
|
|
class UserProxy extends \User implements \Doctrine\ORM\Proxy\Proxy
|
|
|
|
{
|
|
|
|
// .. lazy load code here
|
2013-03-17 15:26:34 +04:00
|
|
|
|
2010-11-01 23:16:12 +03:00
|
|
|
public function addReportedBug($bug)
|
|
|
|
{
|
|
|
|
$this->_load();
|
|
|
|
return parent::addReportedBug($bug);
|
|
|
|
}
|
2013-03-17 15:26:34 +04:00
|
|
|
|
2010-11-01 23:16:12 +03:00
|
|
|
public function assignedToBug($bug)
|
|
|
|
{
|
|
|
|
$this->_load();
|
|
|
|
return parent::assignedToBug($bug);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
See how upon each method call the proxy is lazily loaded from the
|
2013-03-17 02:36:36 +04:00
|
|
|
database?
|
2010-11-01 23:16:12 +03:00
|
|
|
|
2013-03-17 02:36:36 +04:00
|
|
|
The call prints:
|
2011-08-27 14:36:37 +04:00
|
|
|
|
|
|
|
::
|
|
|
|
|
|
|
|
$ php show_bug.php 1
|
2010-11-01 23:16:12 +03:00
|
|
|
Bug: Something does not work!
|
|
|
|
Engineer: beberlei
|
|
|
|
|
|
|
|
Dashboard of the User
|
|
|
|
---------------------
|
|
|
|
|
|
|
|
For the next use-case we want to retrieve the dashboard view, a
|
|
|
|
list of all open bugs the user reported or was assigned to. This
|
|
|
|
will be achieved using DQL again, this time with some WHERE clauses
|
|
|
|
and usage of bound parameters:
|
|
|
|
|
2010-12-03 22:13:10 +03:00
|
|
|
.. code-block:: php
|
2010-11-01 23:16:12 +03:00
|
|
|
|
|
|
|
<?php
|
2011-08-27 14:36:37 +04:00
|
|
|
// dashboard.php
|
|
|
|
require_once "bootstrap.php";
|
|
|
|
|
|
|
|
$theUserId = $argv[1];
|
|
|
|
|
2010-11-01 23:16:12 +03:00
|
|
|
$dql = "SELECT b, e, r FROM Bug b JOIN b.engineer e JOIN b.reporter r ".
|
2011-08-27 14:36:37 +04:00
|
|
|
"WHERE b.status = 'OPEN' AND (e.id = ?1 OR r.id = ?1) ORDER BY b.created DESC";
|
2013-03-17 15:26:34 +04:00
|
|
|
|
2010-11-01 23:16:12 +03:00
|
|
|
$myBugs = $entityManager->createQuery($dql)
|
|
|
|
->setParameter(1, $theUserId)
|
|
|
|
->setMaxResults(15)
|
|
|
|
->getResult();
|
2013-03-17 15:26:34 +04:00
|
|
|
|
2011-08-27 14:36:37 +04:00
|
|
|
echo "You have created or assigned to " . count($myBugs) . " open bugs:\n\n";
|
|
|
|
|
2010-11-01 23:16:12 +03:00
|
|
|
foreach ($myBugs AS $bug) {
|
2011-08-27 14:36:37 +04:00
|
|
|
echo $bug->getId() . " - " . $bug->getDescription()."\n";
|
2010-11-01 23:16:12 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
Number of Bugs
|
|
|
|
--------------
|
|
|
|
|
|
|
|
Until now we only retrieved entities or their array representation.
|
|
|
|
Doctrine also supports the retrieval of non-entities through DQL.
|
|
|
|
These values are called "scalar result values" and may even be
|
|
|
|
aggregate values using COUNT, SUM, MIN, MAX or AVG functions.
|
|
|
|
|
|
|
|
We will need this knowledge to retrieve the number of open bugs
|
|
|
|
grouped by product:
|
|
|
|
|
2010-12-03 22:13:10 +03:00
|
|
|
.. code-block:: php
|
2010-11-01 23:16:12 +03:00
|
|
|
|
|
|
|
<?php
|
2011-08-27 14:36:37 +04:00
|
|
|
// products.php
|
|
|
|
require_once "bootstrap.php";
|
|
|
|
|
2010-11-01 23:16:12 +03:00
|
|
|
$dql = "SELECT p.id, p.name, count(b.id) AS openBugs FROM Bug b ".
|
|
|
|
"JOIN b.products p WHERE b.status = 'OPEN' GROUP BY p.id";
|
2011-04-24 09:21:34 +04:00
|
|
|
$productBugs = $entityManager->createQuery($dql)->getScalarResult();
|
2013-03-17 15:26:34 +04:00
|
|
|
|
2010-11-01 23:16:12 +03:00
|
|
|
foreach($productBugs as $productBug) {
|
|
|
|
echo $productBug['name']." has " . $productBug['openBugs'] . " open bugs!\n";
|
|
|
|
}
|
|
|
|
|
|
|
|
Updating Entities
|
|
|
|
-----------------
|
|
|
|
|
|
|
|
There is a single use-case missing from the requirements, Engineers
|
|
|
|
should be able to close a bug. This looks like:
|
|
|
|
|
2010-12-03 22:13:10 +03:00
|
|
|
.. code-block:: php
|
2010-11-01 23:16:12 +03:00
|
|
|
|
|
|
|
<?php
|
2013-03-17 15:45:49 +04:00
|
|
|
// src/Bug.php
|
2011-08-27 14:36:37 +04:00
|
|
|
|
|
|
|
class Bug
|
|
|
|
{
|
|
|
|
public function close()
|
|
|
|
{
|
|
|
|
$this->status = "CLOSE";
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
.. code-block:: php
|
|
|
|
|
|
|
|
<?php
|
|
|
|
// close_bug.php
|
|
|
|
require_once "bootstrap.php";
|
|
|
|
|
|
|
|
$theBugId = $argv[1];
|
|
|
|
|
2010-11-01 23:16:12 +03:00
|
|
|
$bug = $entityManager->find("Bug", (int)$theBugId);
|
|
|
|
$bug->close();
|
2013-03-17 15:26:34 +04:00
|
|
|
|
2010-11-01 23:16:12 +03:00
|
|
|
$entityManager->flush();
|
|
|
|
|
|
|
|
When retrieving the Bug from the database it is inserted into the
|
|
|
|
IdentityMap inside the UnitOfWork of Doctrine. This means your Bug
|
|
|
|
with exactly this id can only exist once during the whole request
|
|
|
|
no matter how often you call ``EntityManager#find()``. It even
|
|
|
|
detects entities that are hydrated using DQL and are already
|
|
|
|
present in the Identity Map.
|
|
|
|
|
|
|
|
When flush is called the EntityManager loops over all the entities
|
|
|
|
in the identity map and performs a comparison between the values
|
|
|
|
originally retrieved from the database and those values the entity
|
|
|
|
currently has. If at least one of these properties is different the
|
|
|
|
entity is scheduled for an UPDATE against the database. Only the
|
|
|
|
changed columns are updated, which offers a pretty good performance
|
|
|
|
improvement compared to updating all the properties.
|
|
|
|
|
2011-02-26 13:51:30 +03:00
|
|
|
Entity Repositories
|
|
|
|
-------------------
|
|
|
|
|
|
|
|
For now we have not discussed how to separate the Doctrine query logic from your model.
|
|
|
|
In Doctrine 1 there was the concept of ``Doctrine_Table`` instances for this
|
2012-12-02 21:58:15 +04:00
|
|
|
separation. The similar concept in Doctrine2 is called Entity Repositories, integrating
|
2011-02-26 13:51:30 +03:00
|
|
|
the `repository pattern <http://martinfowler.com/eaaCatalog/repository.html>`_ at the heart of Doctrine.
|
|
|
|
|
|
|
|
Every Entity uses a default repository by default and offers a bunch of convenience
|
|
|
|
methods that you can use to query for instances of that Entity. Take for example
|
|
|
|
our Product entity. If we wanted to Query by name, we can use:
|
|
|
|
|
|
|
|
.. code-block:: php
|
|
|
|
|
|
|
|
<?php
|
|
|
|
$product = $entityManager->getRepository('Product')
|
|
|
|
->findOneBy(array('name' => $productName));
|
|
|
|
|
|
|
|
The method ``findOneBy()`` takes an array of fields or association keys and the values to match against.
|
|
|
|
|
|
|
|
If you want to find all entities matching a condition you can use ``findBy()``, for
|
|
|
|
example querying for all closed bugs:
|
|
|
|
|
|
|
|
.. code-block:: php
|
|
|
|
|
|
|
|
<?php
|
|
|
|
$bugs = $entityManager->getRepository('Bug')
|
|
|
|
->findBy(array('status' => 'CLOSED'));
|
|
|
|
|
|
|
|
foreach ($bugs AS $bug) {
|
|
|
|
// do stuff
|
|
|
|
}
|
|
|
|
|
|
|
|
Compared to DQL these query methods are falling short of functionality very fast.
|
|
|
|
Doctrine offers you a convenient way to extend the functionalities of the default ``EntityRepository``
|
|
|
|
and put all the specialized DQL query logic on it. For this you have to create a subclass
|
|
|
|
of ``Doctrine\ORM\EntityRepository``, in our case a ``BugRepository`` and group all
|
2012-12-02 21:58:15 +04:00
|
|
|
the previously discussed query functionality in it:
|
2011-02-26 13:51:30 +03:00
|
|
|
|
|
|
|
.. code-block:: php
|
|
|
|
|
|
|
|
<?php
|
2013-03-17 15:45:49 +04:00
|
|
|
// src/BugRepository.php
|
2011-02-26 13:51:30 +03:00
|
|
|
|
|
|
|
use Doctrine\ORM\EntityRepository;
|
|
|
|
|
|
|
|
class BugRepository extends EntityRepository
|
|
|
|
{
|
|
|
|
public function getRecentBugs($number = 30)
|
|
|
|
{
|
|
|
|
$dql = "SELECT b, e, r FROM Bug b JOIN b.engineer e JOIN b.reporter r ORDER BY b.created DESC";
|
|
|
|
|
2011-03-31 10:57:27 +04:00
|
|
|
$query = $this->getEntityManager()->createQuery($dql);
|
2011-02-26 13:51:30 +03:00
|
|
|
$query->setMaxResults($number);
|
|
|
|
return $query->getResult();
|
|
|
|
}
|
|
|
|
|
|
|
|
public function getRecentBugsArray($number = 30)
|
|
|
|
{
|
|
|
|
$dql = "SELECT b, e, r, p FROM Bug b JOIN b.engineer e ".
|
|
|
|
"JOIN b.reporter r JOIN b.products p ORDER BY b.created DESC";
|
2011-03-31 10:57:27 +04:00
|
|
|
$query = $this->getEntityManager()->createQuery($dql);
|
2011-02-26 13:51:30 +03:00
|
|
|
$query->setMaxResults($number);
|
|
|
|
return $query->getArrayResult();
|
|
|
|
}
|
|
|
|
|
|
|
|
public function getUsersBugs($userId, $number = 15)
|
|
|
|
{
|
|
|
|
$dql = "SELECT b, e, r FROM Bug b JOIN b.engineer e JOIN b.reporter r ".
|
|
|
|
"WHERE b.status = 'OPEN' AND e.id = ?1 OR r.id = ?1 ORDER BY b.created DESC";
|
|
|
|
|
2011-03-31 10:57:27 +04:00
|
|
|
return $this->getEntityManager()->createQuery($dql)
|
2011-02-26 13:51:30 +03:00
|
|
|
->setParameter(1, $userId)
|
|
|
|
->setMaxResults($number)
|
|
|
|
->getResult();
|
|
|
|
}
|
|
|
|
|
|
|
|
public function getOpenBugsByProduct()
|
|
|
|
{
|
|
|
|
$dql = "SELECT p.id, p.name, count(b.id) AS openBugs FROM Bug b ".
|
|
|
|
"JOIN b.products p WHERE b.status = 'OPEN' GROUP BY p.id";
|
2011-03-31 10:57:27 +04:00
|
|
|
return $this->getEntityManager()->createQuery($dql)->getScalarResult();
|
2011-02-26 13:51:30 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2012-12-02 21:58:15 +04:00
|
|
|
Don't forget to add a `require_once` call for this class to the bootstrap.php
|
2011-08-27 14:36:37 +04:00
|
|
|
|
2011-03-31 10:57:27 +04:00
|
|
|
To be able to use this query logic through ``$this->getEntityManager()->getRepository('Bug')``
|
2011-02-26 13:51:30 +03:00
|
|
|
we have to adjust the metadata slightly.
|
|
|
|
|
|
|
|
.. configuration-block::
|
|
|
|
|
|
|
|
.. code-block:: php
|
|
|
|
|
|
|
|
<?php
|
|
|
|
/**
|
2011-04-24 09:24:54 +04:00
|
|
|
* @Entity(repositoryClass="BugRepository")
|
|
|
|
* @Table(name="bugs")
|
2012-01-29 22:48:09 +04:00
|
|
|
**/
|
2011-02-26 13:51:30 +03:00
|
|
|
class Bug
|
|
|
|
{
|
|
|
|
//...
|
|
|
|
}
|
|
|
|
|
|
|
|
.. code-block:: xml
|
|
|
|
|
|
|
|
<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
|
2012-06-16 14:44:00 +04:00
|
|
|
http://raw.github.com/doctrine/doctrine2/master/doctrine-mapping.xsd">
|
2011-02-26 13:51:30 +03:00
|
|
|
|
2011-08-27 14:36:37 +04:00
|
|
|
<entity name="Bug" table="bugs" repository-class="BugRepository">
|
2011-02-26 13:51:30 +03:00
|
|
|
|
|
|
|
</entity>
|
|
|
|
</doctrine-mapping>
|
|
|
|
|
|
|
|
.. code-block:: yaml
|
|
|
|
|
2011-08-27 14:36:37 +04:00
|
|
|
Bug:
|
2011-02-26 13:51:30 +03:00
|
|
|
type: entity
|
|
|
|
repositoryClass: BugRepository
|
|
|
|
|
|
|
|
Now we can remove our query logic in all the places and instead use them through the EntityRepository.
|
|
|
|
As an example here is the code of the first use case "List of Bugs":
|
|
|
|
|
|
|
|
.. code-block:: php
|
|
|
|
|
|
|
|
<?php
|
2011-08-27 14:36:37 +04:00
|
|
|
// list_bugs_repository.php
|
|
|
|
require_once "bootstrap.php";
|
|
|
|
|
2011-02-26 13:51:30 +03:00
|
|
|
$bugs = $entityManager->getRepository('Bug')->getRecentBugs();
|
|
|
|
|
|
|
|
foreach($bugs AS $bug) {
|
2011-08-27 14:36:37 +04:00
|
|
|
echo $bug->getDescription()." - ".$bug->getCreated()->format('d.m.Y')."\n";
|
|
|
|
echo " Reported by: ".$bug->getReporter()->getName()."\n";
|
|
|
|
echo " Assigned to: ".$bug->getEngineer()->getName()."\n";
|
2011-02-26 13:51:30 +03:00
|
|
|
foreach($bug->getProducts() AS $product) {
|
2011-08-27 14:36:37 +04:00
|
|
|
echo " Platform: ".$product->getName()."\n";
|
2011-02-26 13:51:30 +03:00
|
|
|
}
|
|
|
|
echo "\n";
|
|
|
|
}
|
|
|
|
|
|
|
|
Using EntityRepositories you can avoid coupling your model with specific query logic.
|
|
|
|
You can also re-use query logic easily throughout your application.
|
|
|
|
|
|
|
|
Conclusion
|
|
|
|
----------
|
|
|
|
|
2010-11-01 23:16:12 +03:00
|
|
|
This tutorial is over here, I hope you had fun. Additional content
|
|
|
|
will be added to this tutorial incrementally, topics will include:
|
|
|
|
|
2011-02-26 13:51:30 +03:00
|
|
|
- More on Association Mappings
|
|
|
|
- Lifecycle Events triggered in the UnitOfWork
|
|
|
|
- Ordering of Collections
|
2010-11-01 23:16:12 +03:00
|
|
|
|
|
|
|
Additional details on all the topics discussed here can be found in
|
|
|
|
the respective manual chapters.
|
|
|
|
|