Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Persistence in PHP with Doctrine ORM
Persistence in PHP with Doctrine ORM

Persistence in PHP with Doctrine ORM: This book is designed for PHP developers and architects who want to modernize their skills through better understanding of Persistence and ORM. You'll learn through explanations and code samples, all tied to the full development of a web application.

Arrow left icon
Profile Icon Kevin Dunglas
Arrow right icon
€18.99 per month
Full star icon Full star icon Full star icon Full star icon Full star icon 5 (5 Ratings)
Paperback Dec 2013 114 pages 1st Edition
eBook
€8.99 €19.99
Paperback
€24.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Kevin Dunglas
Arrow right icon
€18.99 per month
Full star icon Full star icon Full star icon Full star icon Full star icon 5 (5 Ratings)
Paperback Dec 2013 114 pages 1st Edition
eBook
€8.99 €19.99
Paperback
€24.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€8.99 €19.99
Paperback
€24.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. €18.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Persistence in PHP with Doctrine ORM

Chapter 1. Getting Started with Doctrine 2

The Doctrine project is a collection of libraries providing utilities to ease data persistence in PHP applications. It makes it possible to create complex model layers in no time that will be compatible with popular DBMS, including SQLite, MySQL, and PostgreSQL. To discover and understand Doctrine, we will create a small blog from scratch throughout this book that will mainly use the following Doctrine components:

  • Common provides utilities that are not in the PHP standard library including a class autoloader, an annotations parser, collections structures, and a cache system.

  • Database Abstraction Layer (DBAL) exposes a unique interface to access popular DBMS. Its API is similar to PDO (and PDO is used when possible). The DBAL component is also able to execute the same SQL query on different DBMS by internally rewriting the query to use specific constructs and emulate missing features.

  • Object Relational Mapper (ORM) allows accessing and managing relational database tables and rows through an object-oriented API. Thanks to it, we will directly manipulate PHP objects, and it will transparently generate SQL queries to populate, persist, update, and delete them. It is built on top of DBAL and will be the main topic of this book.

Note

For more information on PHP Data Objects and the data-access abstraction layer provided by PHP, refer to the following link: http://php.net/manual/en/book.pdo.php

To learn Doctrine, we will build together a tiny blog engine with advanced features such as the following:

  • Posts list, creation, editing, and deletion

  • Comments

  • Tag filtering

  • Profiles for author of posts and comments

  • Statistics

  • Data fixtures

The following is a screenshot of the blog:

In this chapter, we will learn about the following topics:

  • Understanding concepts behind Doctrine

  • Creating the project's structure

  • Installing Composer

  • Installing Doctrine ORM, DBAL, and Common through Compose

  • Bootstrapping the app

  • Using Doctrine's Entity Manager

  • Configuring Doctrine command-line tools

Prerequisites


To follow this tutorial, we need a proper CLI installation of PHP 5.4 or superior. We will also use the curl command to download the Composer archive and the SQLite 3 client.

Note

For further information about PHP CLI, curl, and SQLite, refer to the following links: http://www.php.net/manual/en/features.commandline.php, http://curl.haxx.se, and http://www.sqlite.org

In the examples, we will use the PHP built-in web server and SQLite as DBMS. Doctrine is a pure PHP library. It is compatible with any web server supporting PHP, but is not limited to Apache and Nginx. Of course, it can also be used in applications that are not intended to run on web servers, such as command-line tools. On the database side, SQLite, MySQL, PostgreSQL, Oracle, and Microsoft SQL Server are officially supported.

Thanks to the DBAL component, our blog should work fine with all these DBMS. It has been tested with SQLite and MySQL.

The Doctrine project also provides Object Document Mappers (ODM) for NoSQL databases including MongoDB, CouchDB, PHPCR, and OrientDB. These topics are not covered in this book.

Note

Do not hesitate to consult the Doctrine documentation specified in the following link while reading this book: http://www.doctrine-project.org

Understanding the concepts behind Doctrine


Doctrine ORM implements Data Mapper and Unit of Work design patterns.

The Data Mapper is a layer designed to synchronize data stored in database with their related objects of the domain layer. In other words, it does the following:

  • Inserts and updates rows in the database from data held by object properties

  • Deletes rows in the database when related entities are marked for deletion

  • Hydrates in-memory objects with data retrieved from the database

Note

For more information about the Data Mapper and Unit of Work design patterns, you can refer to the following links: http://martinfowler.com/eaaCatalog/dataMapper.html and http://martinfowler.com/eaaCatalog/unitOfWork.html

In the Doctrine terminology, a Data Mapper is called an Entity Manager. Entities are plain old PHP objects of the domain layer.

Thanks to the Entity Manager, they don't have to be aware that they will be stored in a database. In fact, they don't need to be aware of the existence of the Entity Manager itself. This design pattern allows reusing entity classes regardless of the persistence system.

For performance and data consistency, the Entity Manager does not sync entities with the database each time they are modified. The Unit of Work design pattern is used to keep the states of objects managed by the Data Mapper. Database synchronization happens only when requested by a call to the flush() method of the Entity Manager and is done in a transaction (if something goes wrong while synchronizing entities to the database, the database will be rolled back to its state prior to the synchronization attempt).

Imagine an entity with a public $name property. Imagine the following code being executed:

  $myEntity->name = 'My name';
  $myEntity->name = 'Kévin';
  $entityManager->flush($myEntity);

Thanks to the implementation of the Unit of Work design pattern, only one SQL query similar to the following will be issued by Doctrine:

      UPDATE MyEntity SET name='Kévin' WHERE id=1312;

Note

The query is similar because, for performance reasons, Doctrine uses prepared statements.

We will finish the theory part with a short overview of the Entity Manager methods and their related entity states.

The following is an extract of a class diagram representing an entity and its Entity Manager:

  • The find() method hydrates and returns an entity of the type passed in the first parameter having the second parameter as an identifier. Data is retrieved from the database through a SELECT query. The state of this returned entity is managed. It means that when the flush() method is called, changes made to it will be synced to the database. The find() method is a convenience method that internally uses an entity repository to retrieve data from the database and hydrate the entity. The state of the managed entities can be changed to detached by calling the detach() method. Modifications made to the detached entity will not be synced to the database (even when the flush() method is called) until its state is set back to managed with a call to the merge() method.

    Note

    The start of Chapter 3, Associations, will be dedicated to entity repositories.

  • The persist() method tells Doctrine to set the state of the entity passed in parameter as managed. This is only useful for entities that have not been synced at least one time to the database (the default state of a newly created object is new) because entities hydrated from existing data automatically have the managed state.

  • The remove() method sets the state of the passed in entity to removed. Data related to this entity will be effectively removed from the database with a DELETE SQL query the next time the flush() method is called.

  • The flush() method syncs data of entities with managed and removed states to the database. Doctrine will issue INSERT, UPDATE, and DELETE SQL queries for the sync. Before that call, all changes are only in-memory and are never synchronized to the database.

Note

Doctrine's Entity Manager has a lot of other useful methods documented on the Doctrine website, http://www.doctrine-project.org/api/orm/2.4/class-Doctrine.ORM.EntityManager.html.

This is abstract for now, but we will understand better how the Entity Manager works with numerous examples throughout the book.

Creating a project structure


The following is the folder structure of our app:

  • blog/: App root created earlier

  • bin/: Specific command line tools of our blog app

  • config/: Configuration files of our app

  • data/: The SQLite database will be stored here

  • src/: All PHP classes we write will be here

  • vendor/: This is where Composer (see the following section) stores all downloaded dependencies including the source code of Doctrine

  • bin/: This is a command-line tool provided by dependencies installed with Composer

  • web/: This is the public directory that contains PHP pages and assets such as images, CSS, and JavaScript files

We must create all these directories except the vendor/ one that will be automatically generated later.

Installing Composer


As with most modern PHP libraries, Doctrine is available through Composer, a powerful dependency manager. A PEAR channel is also available.

Note

For more information on Composer and Pear packages, please refer to the respective links as follows: http://getcomposer.org and http://pear.doctrine-project.org

The following steps should be performed to install Composer:

  1. The first step to install Doctrine ORM is to grab a copy of the latest Composer version.

  2. Open your preferred terminal, go to the blog/ directory (the root of our project), and type the following command to install Composer:

      curl -sS https://getcomposer.org/installer | php
    

    A new file called composer.phar has been downloaded in the directory. This is a self-contained archive of Composer.

  3. Now type the following command:

      php composer.phar
    

    If everything is OK, all available commands are listed. Your Composer installation is up and running!

Left arrow icon Right arrow icon

Key benefits

  • Develop a fully functional Doctrine-backed web application
  • Demonstrate aspects of Doctrine using code samples
  • Generate a database schema from your PHP classes

Description

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.

Who is this book for?

This book is primarily intended for PHP developers and architects who want to increase their skills in the field of Persistence and ORM to map the data they are working on to objects they are using in programming. Basic knowledge of databases and PDO and working knowledge of PHP namespaces is a prerequisite.

What you will learn

  • Install Doctrine through the Composer dependency manager
  • Configure Doctrine Command Line Tools
  • Learn to manage relations between entities with different association types
  • Create data fixtures, a custom entity repository, and native SQL queries
  • Master the query builder to generate DQL queries
  • Get started with inheritance and lifecycle events

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Dec 18, 2013
Length: 114 pages
Edition : 1st
Language : English
ISBN-13 : 9781782164104
Languages :

What do you get with a Packt Subscription?

Free for first 7 days. €18.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Dec 18, 2013
Length: 114 pages
Edition : 1st
Language : English
ISBN-13 : 9781782164104
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 95.97
Persistence in PHP with Doctrine ORM
€24.99
Zend Framework 2 Cookbook
€41.99
Extending Symfony2 Web Application Framework
€28.99
Total 95.97 Stars icon
Banner background image

Table of Contents

5 Chapters
Getting Started with Doctrine 2 Chevron down icon Chevron up icon
Entities and Mapping Information Chevron down icon Chevron up icon
Associations Chevron down icon Chevron up icon
Building Queries Chevron down icon Chevron up icon
Going Further Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Full star icon 5
(5 Ratings)
5 star 100%
4 star 0%
3 star 0%
2 star 0%
1 star 0%
M. Finnerty Jr. Nov 22, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Great book. Well written. I would recommend this book to anyone staring with ORM's
Amazon Verified review Amazon
Derek J. Lambert Mar 13, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
If you're looking for a definitive, all-encompassing API reference for the Doctrine libraries this book most likely won't meet your needs. For those discovering the power and freedom provided by the Doctrine ORM library for the first time or struggling to put all the pieces together using project documentation, Stack Overflow, and the other usual suspects - this book is for you! Throw in a little object-orientated PHP and you're well on your way to building a functional, usable, and extendable application.Dunglas begins with a brief but sufficient stop explaining the prerequisites for a modern PHP 5.4+ project, utilizing Composer to provide the Doctrine 2.4 and related dependencies. As he builds a mock application the code samples are provided in the context of a plausible real-world use scenario, and built upon while progressing through the entire object graph. This perspective provides a clear understanding of object associations and collections.Dunglas goes on to describe using entity repositories and Query Builder to access and manipulate stored entities, continuing into the Doctrine Query Language (DQL) for custom queries. He finishes off exploring some of the advanced functionality provided including object inheritance, events, and native queries.While the subject of unit tests are never touched, functional testing is covered within the scope of the ever useful data fixture. A plethora of additional advanced and tangential subjects, while beyond the extent of the text, are brought up in context with a brief summary and URL for authoritative documentation allowing further exploration into unlimited possibilities.Persistence in PHP with Doctrine ORM fills a long lacking void and provides a coherent and fluent tutorial on the current Doctrine 2 codebase. I can’t imagine where I’d be on my current projects had I started with an up to date reference a couple years ago!
Amazon Verified review Amazon
J Aug 03, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This was one of the best technical books I've read. The author did a remarkable job at keeping the depth at the just the right level where you gain understanding, but not get bored of needless details.
Amazon Verified review Amazon
proappstore Jan 20, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Straight forward. Excellent!
Amazon Verified review Amazon
A. Zubarev Feb 16, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
In short, Persistence in PHP with Doctrine ORM is a book about harnessing the power of Doctrine ORM, but also:Will let you build a working project using Doctrine involving advanced techniques;Will guard you from doing mistakes early in your getting known Doctrine, andWill advocate on appropriate technologies to use in addition in case your next creation is going to see the world.I would recommend this book to a developer who worked with PHP already, but getting ready to embark onto a more intensive data processing endeavor.The book is not terribly long, yet comprehensive enough to allow a person to become proficient in Doctrine say overnight (yes, my Kindle app estimated my reading speed at ~ 2.5 Hrs, that is without me experimenting with code). Personally, I value concise books because they give me a push and allow a relatively comfortable solo sailing with an occasional exploration of a topic I did not encounter learning but stumbled upon doing real-life work.As an aside, use of an ORM (not just Doctrine specifically) is typically being perceived as a negative phenomenon by the data people (disclaimer: I am the data person), unsurprisingly Kevin mentions performance implications under the so called Big Data scenario. This has it’s grounds, I agree, as for example tuning DML or data retrieval, so let’s not argue here, but at least one aspect on an ORM not possible to beat – is its ability to allow seamless transition from one database platform to another, relatively uncommon in the past, seems to being picking up nowadays. But do not be overly optimistic, no migration is ever smooth, it just alleviates some of the pains and minimizes the costs of engineering and maintaining your software.On the not so bright side the author does not cover executing stored procedures/packages, and apparently Doctrine (as most OSS projects) has a long list of defects, yeah, I can hear you, this is a book review, nothing else, ditto.So one last interesting discovery, the Doctrine community focuses more and more on a NoSQL, Mongo in particular, which is thrilling.You will find information in the book on how to build your own SQL, implement association, inheritance and even a not so often used many-to-many relationships.On the odd note, I saw a circular reference created in one of the book examples, while possible it is very dangerous! Also the book covers only one approach: building your app code-first: meaning the database schema is created after a class, which I (you know who am I Smile) don’t endorse, alas I am / was new to Doctrine.I suggest Kevin adds to ver. 2.0 of this book the following:Building an application the schema-up way, too, andProvide an example where Doctrine is using a Mongo database.I give this book a 5 out of 5 rating because it has achieve its objectives, however it seems that Packt could give it the “Instant” moniker due to its material coverage.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.