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
Mex$179.99 Mex$541.99
Full star icon Full star icon Full star icon Full star icon Full star icon 5 (5 Ratings)
eBook Dec 2013 114 pages 1st Edition
eBook
Mex$179.99 Mex$541.99
Paperback
Mex$676.99
Subscription
Free Trial
Arrow left icon
Profile Icon Kevin Dunglas
Arrow right icon
Mex$179.99 Mex$541.99
Full star icon Full star icon Full star icon Full star icon Full star icon 5 (5 Ratings)
eBook Dec 2013 114 pages 1st Edition
eBook
Mex$179.99 Mex$541.99
Paperback
Mex$676.99
Subscription
Free Trial
eBook
Mex$179.99 Mex$541.99
Paperback
Mex$676.99
Subscription
Free Trial

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

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 : 9781782164111
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

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

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.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
$199.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 Mex$85 each
Feature tick icon Exclusive print discounts
$279.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 Mex$85 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total Mex$ 2,605.97
Persistence in PHP with Doctrine ORM
Mex$676.99
Zend Framework 2 Cookbook
Mex$1128.99
Extending Symfony2 Web Application Framework
Mex$799.99
Total Mex$ 2,605.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

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.