Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
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.

eBook
€17.98 €19.99
Paperback
€24.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.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 2. Entities and Mapping Information

In the previous chapter, we discovered the concepts behind Doctrine, we learned how to use Composer to install it, we set up the Doctrine Command Line Tools and we dived into the Entity Manager.

In this chapter, we will cover the following topics:

  • Creating our first entity class

  • Mapping it to its related database table and columns with annotations

  • Using a command helper provided by Doctrine to automatically generate the database schema

  • Creating some fixtures data and dealing with the Entity Manager to display our data in a web user interface

Because we are building a blog, our main entity class will be called Post, as shown in the following figure:

Our Post entity class has the following four properties:

  • id: The unique identifier of the post across the database table (and the blog)

  • title: The post's title

  • body: The post's body

  • publicationDate: The date of publication of the post

Creating the Entity class


As explained in Chapter 1, Getting Started with Doctrine 2, a Doctrine entity is just a PHP object that will be saved in the database. Doctrine annotations are added in the PHP DocBlock comments of the Entity class properties. Annotations are used by Doctrine to map the object to the related database's table and properties to columns.

Note

The original purpose of DocBlocks is integrating technical documentation directly in the source code. The most popular documentation generator that parses DocBlocks is phpDocumentator which is available on this website: http://www.phpdoc.org.

Each entity, once persisted through Doctrine, will be related to a row of the database's table.

Create a new file Post.php containing our entity class in the src/Blog/Entity/ location with the following code:

  <?php

  namespace Blog\Entity;

  use Doctrine\ORM\Mapping\Entity;
  use Doctrine\ORM\Mapping\Table;
  use Doctrine\ORM\Mapping\Index;
  use Doctrine\ORM\Mapping\Id;
  use Doctrine...

Generating getters and setters


Doctrine command-line tools that we configured in Chapter 1, Getting Started with Doctrine 2, include a useful command that generates getter and setter methods of an Entity class for us. We will use it to save us from having to write those of the Post class.

Run the following command to generate getters and setters of all entity classes of the application:

  php vendor/bin/doctrine.php orm:generate:entities src/

Note

If you have several entities and don't want to generate getters and setters for all of them, use the filter option with the orm:generate:entities command.

Mapping with Doctrine annotations


Post is a simple class with four properties. The setter for $id isn't actually generated. Doctrine populates the $id instance variable directly in the entity hydration phase. We will see later how we delegate the ID generation to the DBMS.

Doctrine annotations are imported from the \Doctrine\ORM\Mapping namespace with use statements. They are used in DocBlocks to add mapping information to the class and its properties. DocBlocks are just a special kind of comment starting with /**.

Knowing about the @Entity annotation

The @Entity annotation is used in the class-level DocBlock to specify that this class is an entity class.

The most important attribute of this annotation is repositoryClass. It allows specifying a custom entity repository class. We will learn about entity repositories, including how to make a custom one, in Chapter 4, Building Queries.

Understanding the @Table, @Index, and @UniqueConstraint annotations

The @Table annotation is optional. It can be...

Understanding Doctrine Mapping Types


Doctrine Mapping Types used in the @Column annotation are neither SQL types nor PHP types but they are mapped to both. For instance, the Doctrine text type will be casted to the string PHP type in the entity and stored in a database column with the CLOB type.

The following is a correspondence table for Doctrine Mapping Type of PHP type and SQL type:

Doctrine Mapping Type

PHP Type

SQL Type

string

string

VARCHAR

integer

integer

INT

smallint

integer

SMALLINT

bigint

string

BIGINT

boolean

boolean

BOOLEAN

decimal

double

DECIMAL

date

\DateTime

DATETIME

time

\DateTime

TIME

datetime

\DateTime

DATETIME or TIMESTAMP

text

string

CLOB

object

object using the serialize() and unserialize() methods

CLOB

array

array using serialize() and unserialize() methods

CLOB

float

double

FLOAT (double precision)

simple_array

array using implode() and explode()

...

Creating the database schema


Doctrine is smart enough to generate the database schema corresponding to the entity mapping information.

Note

It's a good practice to always design entities first and to generate the related database schema after that.

To do this, we will again use Command-Line Tools installed in the first chapter. Type this command in the root directory of our project:

  php vendor/bin/doctrine.php orm:schema-tool:create

The following text must be printed in the terminal:

ATTENTION: This operation should not be executed in a production environment.

Creating database schema...

Database schema created successfully!

A new table called Post has been created in the database. You can use the SQLite client to show the structure of the generated table:

  sqlite3 data/blog.db ".schema Post"

It should return the following query:

  CREATE TABLE Post (id INTEGER NOT NULL, title VARCHAR(255) NOT NULL, body CLOB NOT NULL, publicationDate DATETIME NOT NULL, PRIMARY KEY(id));
  CREATE INDEX...

Installing Data fixtures


Fixtures are fake data that allow testing of an app without having to do the tedious task of manually creating data after each install. They are useful for automated testing processes and make it easier for a new developer to start working on our projects.

Note

Any application should be covered with automated tests. The blog app we are building is covered by Behat (http://behat.org/) tests. They are provided in downloads available on the Packt website.

Doctrine has an extension called Data Fixtures that ease fixtures creation. We will install it and use it to create some fake blog posts.

Type this command in the root of the project to install Doctrine Data Fixtures through Composer:

  php composer.phar require doctrine/data-fixtures:1.0.*

The first step to using Doctrine Data Fixtures is to create a fixture class. Create a file called LoadPostData.php in the src/Blog/DataFixtures directory as shown in the following code:

  <?php

  namespace Blog\DataFixtures;

  use...

Creating a simple UI


We will create a simple UI to deal with our posts. This interface will let us create, retrieve, update, and delete a blog post. You may have already guessed that we will use the Entity Manager to do that.

For concision and to focus on the Doctrine part, this UI will have many drawbacks. It should not be used in any kind of production or public server. The primary concerns are as follows:

  • Not secure at all: Everyone can access everything, as there is no authentication system, no data validation, and no CSRF protection

  • Badly designed: There is no separation of concerns, no use of an MVC-like pattern, no REST architecture, no object-oriented code, and so on.

And of course this will be… graphically minimalistic!

Summary


We now have a minimal but working blog app! Thanks to Doctrine, persisting, retrieving, and removing data to a database has never been so easy.

We have learned how to use annotations to map entity classes to database tables and rows, we generated a database schema without typing a line of SQL, we created fixtures and we used the Entity Manager to synchronize data with the database.

In the next chapter, we will learn how to map and manage One-To-One, One-To-Many/Many-To-One, and Many-To-Many associations between entities.

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. $19.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
$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 €5 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 €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


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

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.