Book Image

Persistence in PHP with Doctrine ORM

By : Kevin Dunglas
Book Image

Persistence in PHP with Doctrine ORM

By: Kevin Dunglas

Overview of this book

Doctrine 2 has become the most popular modern persistence system for PHP. It can either be used as a standalone system or can be distributed with Symfony 2, and it also integrates very well with popular frameworks. It allows you to easily retrieve PHP object graphs, provides a powerful object-oriented query language called DQL, a database schema generator tool, and supports database migration. It is efficient, abstracts popular DBMS, and supports PHP 5.3 features. Doctrine is a must-have for modern PHP applications. Persistence in PHP with Doctrine ORM is a practical, hands-on guide that describes the full creation process of a web application powered by Doctrine. Core features of the ORM are explained in depth and illustrated by useful, explicit, and reusable code samples. Persistence in PHP with Doctrine ORM explains everything you need to know to get started with Doctrine in a clear and detailed manner. From installing the ORM through Composer to mastering advanced features such as native queries, this book is a full overview of the power of Doctrine. You will also learn a bunch of mapping annotations, create associations, and generate database schemas from PHP classes. You will also see how to write data fixtures, create custom entity repositories, and issue advanced DQL queries. Finally it will teach you to play with inheritance, write native queries, and use built-in lifecycle events. If you want to use a powerful persistence system for your PHP application, Persistence in PHP with Doctrine ORM is the book you.
Table of Contents (12 chapters)

Writing native queries


In the previous chapter, we learned how to create DQL queries through the QueryBuilder. But DQL has some limitations (that is, queries cannot contain subqueries in FROM and JOIN clauses), and sometimes you want to use specific features of your DBMS (that is, MySQL full-text search). In such cases you need to write native SQL queries.

The NativeQuery class

The NativeQuery class allows you to execute native SQL queries and to get their results as Doctrine entities. Only SELECT queries are supported.

To experiment with this feature, we will create a new command that displays the 100 most recent comments. This can be useful to moderate them.

Create a file containing this new command called last-comments.php in the bin/ directory of the app.

<?php

require_once __DIR__.'/../src/bootstrap.php';

use Doctrine\ORM\Query\ResultSetMappingBuilder;

const NUMBER_OF_RESULTS = 100;

  $resultSetMappingBuilder = new ResultSetMappingBuilder($entityManager);
  $resultSetMappingBuilder...