background preloader

Doctrine2 ORM

Facebook Twitter

La couche métier : les entités. Doctrine et les bases de données (master. L'une des tâches les plus courantes et difficiles pour toute application consiste à lire et à persister des informations dans une base de données. Heureusement, Symfony intègre Doctrine, une bibliothèque dont le seul but est de vous fournir des outils puissants afin de vous faciliter la tâche. Dans ce chapitre, vous apprendrez les bases de la philosophie de Doctrine et verrez à quel point il peut être facile de travailler avec une base de données. Note Doctrine est totalement découplé de Symfony et son utilisation est optionnelle. Ce chapitre est entièrement consacré à l'ORM Doctrine, dont l'objectif est de mapper vos objets avec une base de données relationnelle (comme MySQL, PostGresSQL ou Microsoft SQL).

Vous pouvez aussi persister vos données à l'aide de MongoDB en utilisant la bibliothèque ODM de Doctrine. Un simple exemple : un produit La manière la plus facile de comprendre comment Doctrine fonctionne est de le voir en action. Configurer la base de données Créer une classe entité Tip. 5. Basic Mapping. This guide explains the basic mapping of entities and properties. After working through this guide you should know: How to create PHP objects that can be saved to the database with Doctrine; How to configure the mapping between columns on tables and properties on entities; What Doctrine mapping types are; Defining primary keys and how identifiers are generated by Doctrine; How quoting of reserved symbols works in Doctrine. Mapping of associations will be covered in the next chapter on Association Mapping.

Every PHP object that you want to save in the database using Doctrine is called an Entity. The term "Entity" describes objects that have an identity over many independent requests. This identity is usually achieved by assigning a unique identifier to an entity. In this tutorial the following Message PHP class will serve as the example Entity: class Message{ private $id; private $text; private $postedAt;} Marking our Message class as an entity for Doctrine is straightforward: Manipuler ses entités avec Doctrine2. DoctrineFixturesBundle. Les fixtures sont utilisées pour charger un ensemble de données dans une base de données. Ces données peuvent être utilisées pour les tests ou peuvent être les données initiales nécessaires au bon fonctionnement de l'application. Symfony2 n'a pas été conçue pour gérer les fixtures, mais Doctrine2 possède une bibliothèque qui peut vous aider à écrire des fixtures pour l'ORM ou l'ODM Doctrine. Installation et configuration Les fixtures Doctrine pour Symfony sont maintenues dans le DoctrineFixturesBundle.

Suivez ces étapes pour installer le bundle et la bibliothèque dans l'Édition Standard de Symfony. Mettez à jour les bibliothèques vendor : Si tout s'est bien passé, le DoctrineFixturesBundle peut maintenant être trouvé dans le répertoire vendor/doctrine/doctrine-fixtures-bundle. Note DoctrineFixturesBundle installe la bibliothèque Doctrine Data Fixtures. Finalement, enregistrez le bundle DoctrineFixturesBundle dans le fichier app/AppKernel.php. Écrire des fixtures simples Exécuter des fixtures. Welcome to Doctrine 2 ORM’s documentation! Les relations entre entités avec Doctrine2. 6. Association Mapping. This chapter explains mapping associations between objects. Instead of working with foreign keys in your code, you will always work with references to objects instead and Doctrine will convert those references to foreign keys internally. A reference to a single object is represented by a foreign key.A collection of objects is represented by many foreign keys pointing to the object holding the collection This chapter is split into three different sections.

A list of all the possible association mapping use-cases is given.Mapping Defaults are explained that simplify the use-case examples.Collections are introduced that contain entities in associations. To gain a full understanding of associations you should also read about owning and inverse sides of associations 6.1. A many-to-one association is the most common association between objects. PHP<? Note The above @JoinColumn is optional as it would default to address_id and id anyways. Generated MySQL Schema: 6.2. PHP<? 6.3. PHP<? 6.4. <? 6.5. PHP<? 9. Working with Associations. Associations between entities are represented just like in regular object-oriented PHP code using references to other objects or collections of objects. Changes to associations in your code are not synchronized to the database directly, only when calling EntityManager#flush().

There are other concepts you should know about when working with associations in Doctrine: If an entity is removed from a collection, the association is removed, not the entity itself. A collection of entities always only represents the association to the containing entities, not the entity itself.When a bidirectional assocation is updated, Doctrine only checks on one of both sides for these changes. This is called the owning side of the association.A property with a reference to many entities has to be instances of the Doctrine\Common\Collections\Collection interface. 9.1. We will use a simple comment system with Users and Comments as entities to show examples of association management. <? 9.2. <?

<? <? 9.3. <? Note 9.4. Récupérer ses entités avec Doctrine2. 15. Doctrine Query Language. 15.2.1. DQL SELECT clause The select clause of a DQL query specifies what appears in the query result. The composition of all the expressions in the select clause also influences the nature of the query result. Here is an example that selects all users with an age > 20: <? Lets examine the query: u is a so called identification variable or alias that refers to the MyProject\Model\User class. The result of this query would be a list of User objects where all users are older than 20. The SELECT clause allows to specify both class identification variables that signal the hydration of a complete entity class or just fields of the entity using the syntax u.name. 15.2.2. A SELECT query can contain joins. Regular Joins: Used to limit the results and/or compute aggregate values.

Fetch Joins: In addition to the uses of regular joins: Used to fetch related entities and include them in the hydrated result of a query. There is no special DQL keyword that distinguishes a regular join from a fetch join. <? 16. The QueryBuilder. A QueryBuilder provides an API that is designed for conditionally constructing a DQL query in several steps. It provides a set of classes and methods that is able to programmatically build queries, and also provides a fluent API. This means that you can change between one methodology to the other as you want, and also pick one if you prefer. 16.1. Constructing a new QueryBuilder object The same way you build a normal Query, you build a QueryBuilder object, just providing the correct method name. Here is an example how to build a QueryBuilder object: <? Once you have created an instance of QueryBuilder, it provides a set of useful informative functions that you can use.

<? There’re currently 3 possible return values for getType(): QueryBuilder::SELECT, which returns value 0QueryBuilder::DELETE, returning value 1QueryBuilder::UPDATE, which returns value 2 <? Internally, QueryBuilder works with a DQL cache to increase performance. 16.2. 16.2.1. <? <? 16.2.2. <? <? <? <? The API of a Query Parameter is: Les évènements Doctrine. L'intérêt des évènements Doctrine Dans certains cas, vous pouvez avoir besoin d'effectuer des actions juste avant ou juste après la création, la mise à jour ou la suppression d'une entité.

Par exemple, si vous stockez la date d'édition d'un article, à chaque modification de l'entité Article il faut mettre à jour cet attribut juste avant la mise à jour dans la base de données. Ces actions, vous devez les faire à chaque fois. Cet aspect systématique a deux impacts. D'une part, cela veut dire qu'il faut être sûrs de vraiment les effectuer à chaque fois pour que votre base de données soit cohérente. D'autre part, cela veut dire qu'on est bien trop fainéants pour se répéter !

C'est ici qu'interviennent les évènements Doctrine. On parle d'évènements de « cycle de vie », car ce sont différents évènements que Doctrine lève à chaque moment de la vie d'une entité : son chargement depuis la base de données, sa modification, sa suppression, etc. Définir des callbacks de cycle de vie 1. 1<? 2. 10. Events. Doctrine 2 features a lightweight event system that is part of the Common package. Doctrine uses it to dispatch system events, mainly lifecycle events. You can also use it for your own custom events. 10.1. The Event System The event system is controlled by the EventManager. <? Now we can add some event listeners to the $evm.

Events can be dispatched by using the dispatchEvent() method. <? You can easily remove a listener with the removeEventListener() method. <? The Doctrine 2 event system also has a simple concept of event subscribers. Note The array to return in the getSubscribedEvents method is a simple array with the values being the event names. Now when you dispatch an event, any event subscribers will be notified for that event. <? Now you can test the $eventSubscriber instance to see if the preFoo() method was invoked. <? 10.1.1. It is easy to read.Simplicity.Each method within an EventSubscriber is named after the corresponding constant’s value. 10.2.

Warning <? 10.3. <? 10.4. <? 10.5. <? <? <?