Integration into Frameworks/Libraries CodeIgniter ... This guide is designed for
beginners that haven't worked with Doctrine ORM before. ...... As of v2.4 they.
Doctrine 2 ORM Documentation Release 2
Doctrine Project Team
Oct 09, 2017
Contents
1
Getting Help
3
2
Getting Started
5
3
Mapping Objects onto a Database
7
4
Working with Objects
9
5
Advanced Topics
11
6
Tutorials
13
7
Changelogs
15
8
Cookbook
17
9
Welcome to Doctrine 2 ORM’s documentation!
19
i
ii
Doctrine 2 ORM Documentation, Release 2
The Doctrine documentation is comprised of tutorials, a reference section and cookbook articles that explain different parts of the Object Relational mapper. Doctrine DBAL and Doctrine Common both have their own documentation.
Contents
1
Doctrine 2 ORM Documentation, Release 2
2
Contents
CHAPTER
1
Getting Help
If this documentation is not helping to answer questions you have about Doctrine ORM don’t panic. You can get help from different sources: • There is a FAQ with answers to frequent questions. • The Doctrine Mailing List • Internet Relay Chat (IRC) in #doctrine on Freenode • Report a bug on JIRA. • On Twitter with #doctrine2 • On StackOverflow If you need more structure over the different topics you can browse the table of contents.
3
Doctrine 2 ORM Documentation, Release 2
4
Chapter 1. Getting Help
CHAPTER
2
Getting Started
• Tutorial: Getting Started with Doctrine • Setup: Installation & Configuration
5
Doctrine 2 ORM Documentation, Release 2
6
Chapter 2. Getting Started
CHAPTER
3
Mapping Objects onto a Database
• Mapping: Objects | Associations | Inheritance • Drivers: Docblock Annotations | XML | YAML | PHP
7
Doctrine 2 ORM Documentation, Release 2
8
Chapter 3. Mapping Objects onto a Database
CHAPTER
4
Working with Objects
• Basic Reference: Entities | Associations | Events • Query Reference: DQL | QueryBuilder | Native SQL • Internals: Internals explained | Associations
9
Doctrine 2 ORM Documentation, Release 2
10
Chapter 4. Working with Objects
CHAPTER
5
Advanced Topics
• Architecture • Advanced Configuration • Limitations and known issues • Commandline Tools • Transactions and Concurrency • Filters • NamingStrategy • Improving Performance • Caching • Partial Objects • Change Tracking Policies • Best Practices • Metadata Drivers • Batch Processing • Second Level Cache
11
Doctrine 2 ORM Documentation, Release 2
12
Chapter 5. Advanced Topics
CHAPTER
6
Tutorials
• Indexed associations • Extra Lazy Associations • Composite Primary Keys • Ordered associations • Pagination • Override Field/Association Mappings In Subclasses • Embeddables
13
Doctrine 2 ORM Documentation, Release 2
14
Chapter 6. Tutorials
CHAPTER
7
Changelogs
• Migration to 2.5
15
Doctrine 2 ORM Documentation, Release 2
16
Chapter 7. Changelogs
CHAPTER
8
Cookbook
• Patterns: Aggregate Fields | Decorator Pattern | Strategy Pattern • DQL Extension Points: DQL Custom Walkers | DQL User-Defined-Functions • Implementation: Array Access | Notify ChangeTracking Example | Using Wakeup Or Clone | Working with DateTime | Validation | Entities in the Session | Keeping your Modules independent • Integration into Frameworks/Libraries CodeIgniter • Hidden Gems Prefixing Table Name • Custom Datatypes MySQL Enums Advanced Field Value Conversion
17
Doctrine 2 ORM Documentation, Release 2
18
Chapter 8. Cookbook
CHAPTER
9
Welcome to Doctrine 2 ORM’s documentation!
Tutorials Getting Started with Doctrine This guide covers getting started with the Doctrine ORM. After working through the guide you should know: • 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 prerequisites for the tutorial that have to be installed: • PHP (latest stable version) • Composer Package Manager (Install Composer) The code of this tutorial is available on Github. Note: This tutorial assumes you work with Doctrine 2.4 and above. Some of the code will not work with lower versions.
What is Doctrine? Doctrine 2 is an object-relational mapper (ORM) for PHP 5.4+ 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 19
Doctrine 2 ORM Documentation, Release 2
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 object-oriented programming if persistence and entities are kept separated. 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, unless it does so safely. 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. 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 documentation. Reading their documentation we can extract the requirements: • A Bug has a description, creation date, status, reporter and engineer • A Bug can occur on different Products (platforms) • A Product has a name. • Bug reporters 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. Project Setup Create a new empty folder for this tutorial project, for example doctrine2-tutorial and create a new file composer.json with the following contents: { "require": { "doctrine/orm": "2.4.*", "symfony/yaml": "2.*" }, "autoload": { "psr-0": {"": "src/"} } }
Install Doctrine using the Composer Dependency Management tool, by calling: $ composer install
20
Chapter 9. Welcome to Doctrine 2 ORM’s documentation!
Doctrine 2 ORM Documentation, Release 2
This will install the packages Doctrine Common, Doctrine DBAL, Doctrine ORM, Symfony YAML and Symfony Console into the vendor directory. The Symfony dependencies are not required by Doctrine but will be used in this tutorial. Add the following directories: doctrine2-tutorial |-- config | |-- xml | `-- yaml `-- src
Obtaining the EntityManager Doctrine’s public interface is through the EntityManager. This class provides access points to the complete lifecycle management for 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: ˓→
• YAML Doctrine\Tests\Models\StockExchange\Market: type: entity id: id: type: integer generator: strategy: AUTO fields: name: type:string oneToMany: stocks: targetEntity: Stock mappedBy: market indexBy: symbol
Inside the addStock() method you can see how we directly set the key of the association to the symbol, so that we can work with the indexed association directly after invoking addStock(). Inside getStock($symbol) we pick a stock traded on the particular market by symbol. If this stock doesn’t exist an exception is thrown. The Stock entity doesn’t contain any special instructions that are new, but for completeness here are the code and mappings for it: • PHP
9.1. Tutorials
45
Doctrine 2 ORM Documentation, Release 2
46
Chapter 9. Welcome to Doctrine 2 ORM’s documentation!
Doctrine 2 ORM Documentation, Release 2
• YAML Doctrine\Tests\Models\StockExchange\Stock: type: entity id: id: type: integer generator: strategy: AUTO fields: symbol: type: string manyToOne: market: targetEntity: Market inversedBy: stocks
Querying indexed associations Now that we defined the stocks collection to be indexed by symbol we can take a look at some code, that makes use of the indexing. First we will populate our database with two example stocks traded on a single market:
• YAML Doctrine\Tests\Models\CMS\CmsGroup: type: entity # ... manyToMany: users: targetEntity: CmsUser mappedBy: groups fetch: EXTRA_LAZY
9.1. Tutorials
49
Doctrine 2 ORM Documentation, Release 2
Composite and Foreign Keys as Primary Key New in version 2.1. Doctrine 2 supports composite primary keys natively. Composite keys are a very powerful relational database concept and we took good care to make sure Doctrine 2 supports as many of the composite primary key use-cases. For Doctrine 2.0 composite keys of primitive data-types are supported, for Doctrine 2.1 even foreign keys as primary keys are supported. This tutorial shows how the semantics of composite primary keys work and how they map to the database. General Considerations Every entity with a composite key cannot use an id generator other than “NONE”. That means the ID fields have to have their values set before you call EntityManager#persist($entity). Primitive Types only Even in version 2.0 you can have composite keys as long as they only consist of the primitive types integer and string. Suppose you want to create a database of cars and use the model-name and year of production as primary keys: • PHP
• YAML VehicleCatalogue\Model\Car: type: entity id: name: type: string year: type: integer
Now you can use this entity:
In XML the type of the lifecycle-callback entry is the event that you are triggering on and the method is the method to call. The allowed event types are the ones listed in the previous Lifecycle Events section. When using YAML or XML you need to remember to create public methods to match the callback names you defined. E.g. in these examples doStuffOnPrePersist(), doOtherStuffOnPrePersist() and doStuffOnPostPersist() methods need to be defined on your User model.