#! code: Drupal 11: Using Data Transfer Objects With The Queue API

When writing data to the queue database system Drupal will convert the information to a string using the PHP serialize() function. When the information is pulled out of the database the queue system will unserialize() the data to convert it back into the original information.

When you first start using the queue system you will probably use an array or the PHP stdClass object to store the information on your queue. Whilst this works, the information they contain is pretty free form and makes testing or working with the data a little cumbersome.

A much better way of storing data is by creating an object of a known type and using that as the storage medium for the queue.

This technique of using an object to pass data around different parts of your system is known as Data Transfer Objects (DTO). This allows you to present data in a unified way across your application. This is a design pattern that standardizes how a particular bit of data is passed around, without having to resort to using arrays to accomplish the same job.

In this article we will look at creating a DTO for use in the queue API in Drupal, and how the use of DTOs can protect our queue processing from errors by rejecting items from the queue.

All of the code seen in this article is available on the accompanying GitHub repository that shows a few examples of running the Queue API in Drupal.

Creating A DTO

A DTO in PHP is just a normal class, the key difference is that we use the readonly class (since PHP 8.2) syntax, which means that all properties can only be written once (in the constructor). We do this to prevent the data in the object from being altered after it is created.

It is generally a good idea to create interfaces for our objects so that we can check to make sure that

Read more

PubDate

Tags