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 now! 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
Conferences
Free Learning
Arrow right icon
Drupal 8 Module Development
Drupal 8 Module Development

Drupal 8 Module Development: Build and customize Drupal 8 modules and extensions efficiently

eBook
$27.98 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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
Table of content icon View table of contents Preview book icon Preview Book

Drupal 8 Module Development

Developing for Drupal 8

Drupal is a web-based Content Management System (CMS). While it is useful out of the box, it is designed with developers in mind. The purpose of this book is to explain how Drupal can be extended in many ways and for many purposes. To this end, the version we will use will be the latest one at the time of writing this book--Drupal 8.2. In this book, we will cover a wide range of development topics. We'll discuss how to create a Drupal 8 module, and as we go through the chapters, many concepts and tips that will help you build what you need will be introduced. The goal is not only to explain how things work but also to go through some examples to demonstrate them. Since no book can contain everything, I hope that after reading this book, you'll be able to expand on this knowledge on your own using the resources I reference and by looking into the Drupal code yourself. As helpful as such a book can be for learning any kind of software development, if you really want to progress, you will need to apply the knowledge you learned and explore the source code yourself. Only by doing this you will be able to understand complex systems with many dependencies and layers.

This chapter introduces the terminology, tools, and processes for developing Drupal 8. While subsequent chapters focus on code, this chapter focuses on concepts. We'll talk about the architecture of Drupal and how you can hook into Drupal at strategic places to extend it for accomplishing new tasks.

The following are the major topics we will be covering in this chapter:

  • An introduction to Drupal development
  • Drupal 8 architecture
  • The major subsystems
  • Tools for developing in Drupal

By the end of this chapter, you will understand the architectural aspects of Drupal and be ready to start writing code.

Introducing Drupal (for developers)

Out of the box, Drupal performs all of the standard functions of a web-based content management system:

  • Visitors can view published information on the site; navigate through menus, view listings, and individual pages; and so on
  • Users can create accounts and leave comments
  • Administrators can manage the site configuration and control the permissions levels of users
  • Editors can create, preview, and then publish content when it is ready
  • Content can be syndicated to RSS, where feed readers can pick up new articles as they are published
  • With several built-in themes, even the look and feel of the site can be changed easily

With Drupal 8, the scope of what a site builder can do has greatly increased. Core multilingual capabilities make it much easier to configure the site to use multiple languages, creating content listings a few clicks away out of the box, and content management, in general, has greatly improved.

Developing for Drupal 8

As fantastic as these features are, they will certainly not satisfy the needs of all users. To that end, Drupal's capabilities can be easily extended with modules, themes, and installation profiles. Take a look at Drupal's main website, (http://drupal.org), and you will find thousands of modules that provide new features and thousands of themes that transform the look and feel of the site.

The fact that almost all aspects of Drupal's behavior can be intercepted and transformed through the module and theme mechanisms has led many to claim that Drupal isn't just a CMS, but a Content Management Framework (CMF) capable of being re-tooled to specific needs and functional requirements. This is particularly the case with Drupal 8--the latest version of Drupal and the focus of this book--as great progress has been made on the extensibility front too.

Establishing whether Drupal is rightly called a CMS or CMF is beyond our purpose here, but it is certain that Drupal's most tremendous asset is its extensibility. Want to use a directory server for authentication? There's a Drupal module for that. Want to export data to Comma-Separated Version (CSV) files? There are several modules for that (depending on what data you want to export). Interested in Facebook support, integration with Twitter, or adding a Share This button? Yup, there are modules for all of these too--all of which are available at Drupal.org and provided by developers like you.

Want to integrate Drupal with that custom tool you wrote to solve your special business needs? There may not be a module for that, but with a little bit of code, you can write your own. In fact, that is the subject of this book--providing you with the knowledge and tools to achieve your own goals.

In summary, the purpose of this book is to get you ramped up (as quickly as possible) for Drupal 8 module development. As we move chapter by chapter, we will cover the APIs and tools that you will use to build custom Drupal sites, and we won't stick to theory. Most chapters provide working, practically oriented example code designed to show you how to implement the concepts we talk about. We will follow Drupal coding conventions and utilize Drupal design patterns in an effort to illustrate the correct way to write code within the Drupal development context.

While I certainly can't write the exact code to meet your needs, my hope is that the code mentioned in these chapters can serve as a foundation for your bigger and better applications.

So let's get started with a few preliminary matters.

Technologies that drive Drupal

Installing Drupal 8 in the traditional way is documented both on Drupal.org and in the INSTALL.txt file found inside the /core folder of the installation, so I won't go into it here. I will, however, mention that a better way of installing Drupal 8, especially for developers, is using the accepted Composer template for Drupal 8 projects found on GitHub (https://github.com/drupal-composer/drupal-project). However, the instructions for setting up your site are well covered there as well.

Instead, let's talk a bit about the technologies that power (or are needed by) Drupal 8.

PHP

Drupal is written in the PHP programming language. PHP is a widely supported, multiplatform, and web-centric scripting language. Since Drupal is written in PHP, this book will largely feature code written in PHP, albeit with Drupal standard practices being kept in mind.

It is very important to note that the minimum version of PHP required for Drupal 8 to run (and install via Composer) is 5.5.9. Moreover, since the current version of PHP (at the time of writing this book) is PHP 7, I personally recommend that you run Drupal 8. It's best to start off right.

Regarding the style of PHP, a very important change compared to Drupal 7 is the heavy use of object-oriented code and design patterns. Granted, many procedural style approaches remain throughout the Drupal 8 code base, but the use of a good number of popular external libraries (such as Symfony components) has pushed the overall Drupal code to be more modern. For this reason, it is also quite important that you have at least some basic understanding of object-oriented programming (OOP), especially PHP related, if you want to do Drupal 8 development.

Databases and MySQL

In the past, Drupal has supported two databases--MySQL and PostgreSQL. Drupal 7 and 8 have moved beyond this. Drupal now uses the powerful PHP Data Objects (PDO) library that is standard in PHP 5/7. This library is an abstraction layer that allows developers to support numerous databases, including MySQL, PostgreSQL, SQLite, and MariaDB.

The minimum database versions for Drupal 8 are as follows:

  • MySQL 5.5.3/MariaDB 5.5.20/Percona Server 5.5.8 or higher with PDO and an InnoDB-compatible primary storage engine
  • PostgreSQL 9.1.2 or higher with PDO
  • SQLite 3.7.11 or higher

Additionally, Drupal provides a powerful database API along with some SQL coding conventions that make it easy to interact with your database--both combined allow you to write safe and portable SQL. However, more and more abstractions have been made at different levels, removing the need for SQL writing almost completely. However, we will still see some examples just so your toolbox does not miss anything, as well as cover all the tools at your disposal for querying your database.

The web server

Apache has long been the predominant web server, but it is by no means the only server. While Drupal was originally written with Apache in mind, many other web servers (including IIS, Lighttpd, and NGINX) can run Drupal.

We do not explicitly cover the web server layer anywhere in this book, primarily because development rarely requires working at that low level. However, Drupal expects a fair amount of processing from the web server layer, including handling of URL rewriting. For more information on what you can expect, you can consult the relevant documentation page on https://www.drupal.org/docs/8/system-requirements/web-server.

HTML, CSS, and JavaScript

The de facto web data format is HTML (Hypertext Markup Language) styled with CSS (Cascading Style Sheets). Client-side interactive components are scripted with JavaScript. As Drupal developers, we will encounter all three of these technologies in this book. Although you don't need to be a JavaScript ninja to understand the code here, you will get the most from this book if you are comfortable with these three technologies.

Drupal architecture

In the preceding section, we introduced the technologies that drive Drupal. However, how do they all fit together? How is Drupal code organized? In this section, we provide an overview of Drupal's architecture, with a focus on Drupal 8.

Drupal core, modules, and themes

From an architectural standpoint, we can break up Drupal into three pieces--its core, modules, and themes.

When we discuss Drupal 8 core, we can interpret it in two ways. A more restrictive interpretation sees it as a functionality covered in all the code it ships with, without modules and themes. The more widespread interpretation sees it as the total code base it ships with (out of the box).

Although the most widespread interpretation is the latter (not least because it differentiates all the functionalities its standard installation contains versus all others provided by contributed modules and themes), it is interesting to consider the first one as well, even if just for a minute. In this way, we can distinguish, architecturally, the base code from the modules and themes that provide various functionalities and layouts (both from the core installation and from external modules and themes). Along these lines will be also the hooks and events that glue everything together, allowing us to intercept and inject ties to our own functionality.

The core libraries are made up of code belonging to the Drupal project and those from the wider PHP community, which Drupal borrows under open source licensing. This latter approach is new in Drupal 8 and has been regarded by many as a positive shift toward getting off the Drupal island and embracing outside libraries, frameworks, and communities.

Essentially, the core libraries provide the functions and services used throughout Drupal. Facilities for interacting with the database, translating between languages, sanitizing user data, building forms, encoding data, and many such utilities are found in Drupal's core libraries.

The modules (both core and contributed) are where most of the actual functionality and business logic is. If enabled, they can provide functionality or extend the existing functionality. Most of the core modules are needed and cannot be disabled due to their importance in the standard Drupal installation. However, contributed ones can be installed and uninstalled as needed.

The themes (both core and contributed) are an important part of the theme system and are used in the presentation logic. They provide HTML templates within which content and data can be rendered to the user, as well as CSS styling and even client-side scripting for some nice visual interactions. Themes can extend other themes and can also contain some PHP logic to process the data before being rendered.

Hooks, plugins, and events

Now that we have seen what the core libraries, modules, and themes do, let's talk briefly about hooks and events to understand how they are all connected.

Hooks are a very typical Drupal procedural concept that allows Drupal core and modules to basically ask for data from other modules and themes (or expose it). By doing this, the latter can provide a new functionality or alter the existing ones. It is the responsibility of the code that calls the hook to make use of whatever the hook implementations return. The format and interface for what the latter need to return is usually documented in the hook documentation.

Concretely, hooks work by scanning installed modules and themes and looking for a function that follows a specific naming pattern (in other words, a hook implementation). This is, in most cases, in the following format--module_name_hook_name. Additionally, there are also alter hooks, which have the word alter tacked on the end of the function name and are used to change data passed as a reference to the hook implementation. We will see examples of hooks later in the book.

Developers with a background in OOP or with a strong knowledge of design patterns might recognize this as being similar to the event handling paradigm captured in the Passive Observer pattern. When some particular event occurs, Drupal allows modules the opportunity to respond to that event.

In previous versions of Drupal, hooks were KING. Yes, I wrote this with capital letters, my Caps Lock did not get stuck. This is because they were the way to add or extend a functionality in modules. As such, they were the single most important aspect of Drupal programming. In Drupal 8, however, although still important, they took a backseat to new concepts, such as plugins and events.

In Drupal 8, I dare to say that plugins are king. Much of the functionalities that used to be tied to Drupal via hooks is now added in through another Drupal typical concept--plugins (not to be confused with WordPress plugins). Drupal 8 plugins are discoverable bits of the functionality centralized by a manager and that are used for certain tasks and features. We will see more about plugins and provide many examples later in the book.

A third extension point introduced in Drupal 8 is the event system. Unlike the first two, however, this is not specific to Drupal, but is, in fact, the actual Symfony EventDispatcher component (http://symfony.com/doc/current/components/event_dispatcher.html). Events are primarily used in Drupal to intercept certain actions or flows in order to either stop or modify them. Many request to response tasks that were handled via hooks in the past are now being handled by dispatching events to check whether any modules are interested in, for example, delivering the response to the user.

Services and the dependency injection container

Another architecturally important element of Drupal 8 is the Symfony dependency injection component (http://symfony.com/doc/current/components/dependency_injection.html), concretely represented by the service container.

This component is a staple of modern OOP PHP programming and as such has become foundational to Drupal 8. It allows us to create services that can be injected in various places (and receive themselves services as dependencies). They are then used for the heavy business logic of our functionality. Additionally, they are at times also used as an extension point because the service container is able to collect certain services that are marked as serving a specific purpose and use them automatically. In other words, simply by defining a simple service, we can provide our own functionality or even change the existing logic.

We will encounter many services, and we will see how we can declare our own later in this book.

From request to response

Now that we have listed the most important architectural pieces of Drupal, let's briefly see how these are used in delivering responses to the requests a user makes on a Drupal 8 website. To this end, we will analyze a very simplified example of a typical request as it is handled on a Drupal 8 website:

  • A user enters the http://example.com/node/123 URL in a web browser and presses Enter.
  • The browser contacts the web server at example.com and requests the resource at /node/123.
  • The web server recognizes that the request must be handled by PHP and starts up (or contacts) a PHP environment to handle the request.
  • PHP executes Drupal's front controller file (index.php), which then creates a new Request object from the resource that was requested.
  • Symfony's HTTPKernel handles this request object by dispatching a number of events, such as kernel.request, kernel.controller, kernel.response, and kernel.view.
  • The route that maps to that request is identified through the kernel.request event.
  • The route controller is identified, and the kernel.controller event is used to perform any alterations on the used controller and to resolve the arguments that need to be passed to it. In our case, this route is registered by the Node module through the main Entity system, which identifies the entity ID, loads it, and builds the markup to be returned as part of Response.
  • If the respective controller (or handler) returns something other than a Response object, the kernel.view event is dispatched to check whether there is any code that can transform that into a Response object. In most cases, in Drupal 8, we typically return render arrays, which are transformed into Response objects.
  • Once a Response is created, the front controller returns it to the browser and terminates the request.

In this context, as Drupal 8 module developers, we spend most of our times inside controllers and services, trying to figure out what we need to return to the page. We then rely on Drupal to transform our render array into a proper response to the user, but we can also return one ourselves directly. Moreover, the theme system comes into play here, as well as the block system, because our content gets to be wrapped into a block that is placed in a region surrounded by other regions that contain blocks. However, if it sounds complicated now, don't worry, we will cover in detail all these aspects with examples, and it will become clear in no time.

However, as a quick conclusion, we can see that events are mostly used (but not only) at the highest levels of a request, whereas plugins and hooks are mostly used at lower levels, within the process of calculating, building a page, or handling a specific business logic.

Drupal's major subsystems

In the preceding section, we took a bird's-eye view of Drupal's architecture. Now, we will refine our perspective a bit. We will walk through the major subsystems that Drupal 8 has to offer.

Routing

It all starts with a route, doesn't it? Any interaction with a Drupal 8 website has its beginning in a user (or system) accessing a certain path (or resource). This translates into a route, which maps that resource to a flow that (hopefully) returns a successful response back or at least a graceful failure.

The Drupal 8 routing system is a major shift away from how it was in its previous versions. In Drupal 7 and earlier versions, the routing system was a very Drupal-specific thing (a drupalism, if you will). Many of us remember hook_menu as a staple hook each Drupal developer had to know very well. All of that has been abandoned in Drupal 8 in favor of the Symfony Routing component (http://symfony.com/doc/current/components/routing.html). Also, since I mentioned hook_menu, I will also mention that its other main functions have also been taken over in Drupal 8 by other subsystems, such as plugins.

In this book, we will see how we can define our own route and map it to a controller that will render our page. We will cover a few of the more important route options and take a look at how we can control access to these routes.

Entities

Progressively, entities have become a very powerful way of modeling data and content in Drupal. The most famous type of entity has always been the Node, and it has been historically the cornerstone of content storage and display. In Drupal 8, the entire entity system has been revamped to make other entity types potentially just as important. They have been brought to the forefront and have been properly connected with other systems.

All entity types can have multiple bundles, which are different variations of the same entity type and can have different fields on them (while sharing some fields).

Drupal core still ships with the Node entity type, with a few bundles such as Basic Page and Article. In addition, it comes with a few other entity types, such as User, Comment, and File. However, creating your own entity type in Drupal 8 has become much more standardized compared to Drupal 7 where contributed modules had to be brought into play.

These are not the only types of entities we have in Drupal 8. The examples mentioned previously are all content entity types. Drupal 8 introduced a new type, configuration entity types. The former are oriented toward content, but in reality, they are for anything that holds data that can be input into the database and is specific to that environment. They are not used for storing configuration, though. Users and content are great examples, as they do not need to be (usually) deployable from one environment to other. The latter, on the other hand, are exportable items of the configuration of which there can be more than one. For example, a content entity bundle is a great example because there can be more than one bundle for a certain entity type; they have some metadata and information stored that can differ from bundle to bundle, and they need to be deployed on all environments. That is, they are fundamental to the correct functioning of the site.

Understanding the entity system is indispensable for doing development in Drupal 8 because it provides a powerful way of modeling custom data and content that goes past the traditional nodes that previously were used and is, in my opinion, too much way past their purpose.

Fields

Now that we have an idea of what entities are, let's take a look at how data is actually stored on these entities.

I have alluded in the preceding section to how certain entity bundles can have various fields. This means that each entity type bundle can have any number of fields that are responsible for holding data. Additionally, each entity type itself can have fields for storing data. Okay, but what? Let's break this down.

There are two types of Fields in Drupal 8--base fields and configurable fields. The former are fields that are defined in the code for each entity type you define (or alter), whereas the latter are usually created and configured in the UI and attached to a bundle of that entity type and exported via configuration. So, essentially, both types can end up in the code to be deployed.

Fields can also be of multiples types, depending on the data they store. For example, you can have string (or text) fields, numeric fields, date fields, email fields, and so on. As developers, we can create our own field types if the existing ones are not good enough for our data.

In this book, we will take a look at how we can define base fields on a certain entity type and create our own field type with its own data input widget and output formatter. Site builders can then use this field type on any entity type.

Menus

Any site needs some sort of navigation, right? Drupal not only maintains content, but also provides details about how the site itself is organized, that is, it structures how content is related.

The principle way that it does this is through the menu subsystem. The latter provides APIs to generate, retrieve, and modify elements that describe the site structure. Put in common parlance, it handles the system's navigational menus.

Menus are hierarchical, that is, they have a tree-like structure. A menu item can have multiple children, each of which may have their own children, and so on. In this way, we can use the menu system to structure our site into sections and subsections.

In this book, we will see how we can work programmatically with menus and menu links.

Views

Listing of content and data is always an important capability content management systems covet; this is what Views provides in Drupal 8, and it does so well.

If you've been building (not even necessarily developing) sites in previous versions of Drupal, you'll understand everything with this simple phrase--Views is now in Drupal core. If you haven't, Views has always been a staple Drupal contributed module used on probably all Drupal installations to a certain extent and is an indispensable tool for site builders and even developers.

The purpose of the Views module is to expose data and content in a way that allows the creation of configurable listings. It includes things such as filters, sorts, display options, and many other features. As developers, we often find a need to write our own field or filter plugin to work with Views or expose data from our custom entities or external data sources.

Views is a core Drupal 8 module tied to the general architecture and used for most list pages (especially, admin pages) provided by Drupal core. Although it's a very site building-oriented tool, in this book, we will take a look at how we can create plugins that extend its capabilities to offer site builders even more.

Forms

Unless your site has three pages and five paragraphs of text, the likelihood that you will need to capture user input via some type of form is very high. Also, if you've been coding PHP applications, you know how forms have always been a pain from the point of view of securely and efficiently rendering and processing the submitted data. As soon as you use a PHP framework such as Symfony, you will note that an API is in place to take much of that load off your shoulders.

The same goes with Drupal 8 and its powerful Form API. Historically, it has been a great abstraction over having to output your own form elements and deal with posted values. It allows you to define your own form definition in OOP and handle validation and submission in a logical way. Its render and processing is taken care of by Drupal securely, so you don't have to worry about any of that. In Drupal 8, theming form elements have become much easier than in previous versions.

In this book, we will encounter some forms and see how they actually work in practice.

Configuration

One of the major pet-peeves of Drupal developers (and developers of other popular CMSes for that matter) has always been the way configuration is handled and deployed from one environment to the next. Drupal 7 stored most of its configuration in the database, so various solutions had to be concocted by developers to get that moved up the latter as development progressed.

In Drupal 8, great advancements have been made in this respect with the introduction of a centralized configuration system that although stores all configuration in the database, allows it all to be exported into YML files (and then reimported). So, from a development point of view, we have it much easier now if certain features depend on configuration (for example, a new Field).

Configuration is also of two kinds--simple and complex (configuration entities we noted in the Entities section). The difference between the two is that the former is always singular in that it stores just a value (or multiple values together), once--the site name and email address, for example. You only have one site name. The latter, on the other hand, represents multiple instances of the same configuration type, for example, multiple View definitions or multiple entity bundles. In this book, we will see a bit of both.

Plugins

Plugins are new to Drupal in its latest version and are an elegant solution to an important problem--the encapsulating and reusing functionalities. Right off the bat, you should not confuse them with things such as the WordPress plugins, which are more akin to Drupal modules. Instead, you should think of plugins as components of reusable code that can be used and managed by a central system. They are typically used to allow others to contribute their own distinct functionality within your own system. Looking at it from the other direction, Drupal core, for example, handles many things in a certain way, but allows you to provide your own plugins to handle those things in a different way.

An interesting way of looking at plugins is also as being opposite to entities, not for data storage, but for functionality. Instead of creating a type of data that gets stored, you create a type of functionality that is used. The two usually work hand in hand, especially when it comes to manipulating the data in different ways.

Plugins are a great new extension point for developers to add their own functionality and are a critical subsystem for Drupal 8 developers to know. An important aspect of how they work is their discoverability. Most plugin types (but definitely not all) are discovered via something called Annotations. Annotations are a form of DocBlock comments, borrowed from the Doctrine library (http://docs.doctrine-project.org/projects/doctrine-common/en/latest/reference/annotations.html), by which we can describe classes, methods, and even properties with certain metadata. This metadata is then read to determine what that item is without the need for instantiating the class. In Drupal 8, we use annotations only at a class level to denote that it is a plugin implementation with certain characteristics. That is how most plugins are discovered in Drupal 8.

The second most common discoverability method for plugins is via a YAML file, and a popular example of these are menu links (as we will see later in the book). However, for now, you should know that plugins are very widely used, and we will create quite a few plugins in this book.

The theme system

The responsibility of theming a given piece of data is spread out over the Drupal core, modules, and the themes themselves. So, as a module developer, it is important to know that both modules and themes can theme data or content.

In this book, we will focus on the aspects that happen at the module level. We will not concern ourselves with styling or layouts, but work primarily with theming definitions and templates that are needed within the module. Typically, it is the best practice to ensure that modules are able to theme their data. If done right, themes can then come into play and override that theming to change the presentation.

A major shift in Drupal 8 compared to older versions is the move to the open source Twig templating system (https://twig.sensiolabs.org/). This makes the separation of logic from a presentation that much clearer and makes fronted developers' job much easier, not to mention more secure.

Caching

The last major subsystem that I will include here is the caching layer. Drupal 8 has gone to great lengths to improve the performance of building pages and rendering data. To this end, the caching system has become an important part to consider whenever we either do complex or heavy calculations or render content.

From a module developer's perspective, there are two main pillars of the caching system. The first one provides developers a cache backend to store the result of complex data calculations. This data can be read in the next requests to avoid the need for redoing those calculations. This goes hand in hand with cache invalidation when something in the system changes that would require the calculations to be redone. The second pillar is the render cache, which allows developers to wrap their data output with metadata that describe in what context and when that data output needs to be invalidated or changed. The entire markup of that bit gets cached and invalidated based on the rules of the metadata.

We will see these in action in a later chapter dedicated to caching.

Other subsystems

There are other subsystems in Drupal 8 of varying importance. I chose to include the preceding ones because I deemed them to be the most important to be introduced up front and especially from the point of view of a module developer. However, as we progress through the book, we will definitely encounter others.

Tools for developing in Drupal

Drupal is a sophisticated platform, and from the glimpse provided in this chapter, we can already see that there are numerous systems and structures to keep track of. In this section, I will provide tools that simplify or streamline the development process.

Going forward, I assume that you have your own web server stack and your own PHP development tools. However, if you are just getting started, you may want to look at Acquia Dev Desktop from Acquia (http://acquia.com). It offers entire application stacks to get you started on Windows, Linux, or macOS X. Alternatively, if you are even just a bit more advanced, you can consider the Drupal VM (https://www.drupalvm.com/), a Vagrant and Ansible-based local development environment ready for Drupal.

As for a code editor, I personally use PhpStorm (as many others do), but you are free to use whatever IDE you want because Drupal itself doesn't require anything special. Also, while running a PHP debugger is certainly not necessary, you may find running Xdebug or the Zend Debugger to be useful. I personally recommend a PHP debugger wholeheartedly, not only for debugging itself, but also for understanding the processes that happens under the hood.

Version control

Any software development needs to happen through a version controlled environment. By now, Drupal is universally using Git. So, you should make sure that you have Git installed locally, even if just to be able to check out the code examples we write in this book, which will be hosted on GitHub.

Composer

As I alluded to earlier, installing Drupal 8 is best done via a Composer template project. However, you may also install it straight from Git by checking out the latest tag or commit in the Drupal.org Git repository (https://www.drupal.org/project/drupal/git-instructions). If you do this, you will need to install its dependencies via Composer, and Drupal has many.

To this end, you will need to have Composer available on your development environment and have a basic understanding of how to use it.

The API site and coding standards

A lot of background knowledge is required for writing good Drupal code. Of course, the aim of a book such as this is to try to provide as much of that background knowledge as possible. However, self-documentation and research still remain key, and there are a number of resources that a Drupal developer should have on-hand.

The first is the official online API documentation. Just about every function in Drupal is documented using in-line code documentation. The Doxygen program is then used to extract that documentation and format it. You can access the full API documentation online at http://api.drupal.org.

Along with using the Drupal APIs, we strive to comply with Drupal's coding conventions. Best practices in software development include keeping code clean, consistent, and readable. One aspect of this is removing nuances in code formatting by following a fixed standard.

This is particularly important on a platform such as Drupal, where thousands of developers all contribute to the code. Without coding standards, the code would become a cluttered mishmash of styles, and valuable development time will be spent merely deciphering code instead of working on it.

The Drupal site has a manual on coding standards that each Drupal developer needs to become familiar with (https://www.drupal.org/docs/develop/standards/coding-standards). It won't happen overnight; you will get better with experience, but you can also configure your IDE to, for instance, flag any issues with your code formatting.

A third resource for developers new to Drupal 8 but who have experience with Drupal 7 is the change records database (https://www.drupal.org/list-changes/drupal). On this page, you'll find an inventory of the most important API and usage changes with some handy explanations that will be extremely helpful for Drupal 7 developers looking up how certain functions have been changed.

The developer (Devel) module

On your development environment, you can install a handy module called Devel (http://drupal.org/project/devel), which provides several sophisticated tools designed to help developers create and debug Drupal code.

The following are a few of the features of this module:

  • Functions used for dumping objects and arrays into formatted Drupal output
  • Tools for analyzing database usage and performance
  • A content generator for quickly populating your site with testing content

Drush (the Drupal shell)

Sometimes, it is much easier to run some tasks with a single command in a console. Drush (http://drupal.org/project/drush) provides a command-line Drupal interface. It can be used to execute tasks with a few keystrokes at the console.

When developing, we often have to clear caches, run specific tasks, or deploy data to a remote server. Drush can help accomplish tasks like this. Additionally, we can write our own Drush commands that perform various custom tasks, for example, to be used in cron jobs. So having Drush installed is a must for any serious Drupal developer.

Drupal Console

If Drush is a tool that has been around for many years, the Drupal Console (https://drupalconsole.com/) project is new to Drupal 8. Its purpose is similar to that of Drush, and in this way, it complements it, if at times even overlaps with it. However, one thing is clear--its scope is much broader, especially in its handy commands that generate boilerplate code, which can get quite lengthy.

Although in this book we won't be using this tool, it's recommended that you install it as you progress with learning Drupal 8 module development and start generating certain code structures faster. That being said, I advise caution in using it at the expense of actually understanding what the code it generates actually does. Always strive to understand what you are doing, and never give in to blindly copying and pasting code from Stack Overflow or any other resource without grasping fully what it does.

Developer settings

While doing local development, it's beneficial to (sometimes) disable things such as caching in order to be quicker. Drupal 8 takes caching to a whole new level, so many hook implementations, for example, get cached. To circumvent this, we can use some local settings that disable caching, prevent CSS and JavaScript file aggregation, and do similar things.

These settings are found inside the example.settings.local.php file in the /sites folder of the installation. To benefit from these, you will need to make sure that they are included in your main settings.php file (either by copying them inside or including a file such as this).

A word of caution--do keep in mind that by developing with caching disabled at all times, you run the risk of overlooking certain aspects that won't work properly with caching enabled (such as invalidations). So, do try to toggle on/off these settings to ensure a production-like environment will work just as well as under your development conditions.

Summary

This chapter has been an overview of Drupal 8 for developers. We saw what technologies Drupal uses. We took a look at Drupal's architecture. We took a cursory glance at several prominent subsystems of Drupal. We also got a feel of which developer-oriented tools are to be used while working with Drupal.

Starting with the next chapter, we will be working with code. In fact, each of the subsequent chapters will focus on practical aspects of working with Drupal.

In the next chapter, we will create our first Drupal 8 module with the obligatory Hello World example.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Unleash the power of Drupal 8 programming by creating efficient modules and extensions
  • Explore a plethora of Drupal 8 APIs and get the best out of them using the power of PHP coding
  • Learn to implement efficient data management and data security by creating dedicated modules for it.

Description

Drupal is an open source web-based content management system (CMS) that can be used for building anything from simple websites to complex applications. It enables individuals and organizations to build platforms that engage users and deliver the right content at the right time. Drupal 8 is an exciting new development in the Drupal community. However, the differences from the previous version are substantial and this can put quite some pressure on Drupal 7 developers that need to catch up. This book aims to help such developers in getting up to speed with Drupal 8 module development. The book first introduces you to the Drupal 8 architecture and its subsystems before diving into creating your first module with basic functionality. Building upon that, you will cover many core APIs and functionalities available to module developers. You will work with the Drupal logging and mailing systems, learn how to output data using the theme layer and work with menus and links programmatically. Then, you will learn how to work with different kinds of data storages, create custom entities, field types and leverage the Database API for lower level database queries. Moreover, you will learn about the Drupal 8 access system and caching layer as well as the APIs used for data processing (queues and batches). You will further see how to introduce javascript into your module, work with the various file systems and ensure the code you write works on multilingual sites. Finally, you will learn how to programmatically work with Views, write automated tests for your functionality and also write secure code in general. By the end of the book, you will have learned how to develop your own custom module from scratch that can help solve a small problem or even provide complex functionality. And who knows, maybe you’ll even contribute it back to the Drupal community.

Who is this book for?

The primary target of this book is Drupal developers who want to learn how to write modules and carry out development in Drupal 8. It is also intended for Drupal site builders and PHP developers who have basic Object Oriented Programming skills. A little bit of Symfony experience is helpful but not mandatory.

What you will learn

  • Write a Drupal 8 module with custom functionality and hook into various extension points
  • Master numerous Drupal 8 sub-systems and APIs
  • Model, store, and manipulate data in various ways and for various purposes
  • Display data and content in a presentable and secure way
  • Learn about the theme system and render arrays
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Oct 27, 2017
Length: 566 pages
Edition : 1st
Language : English
ISBN-13 : 9781782168775
Languages :
Concepts :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Publication date : Oct 27, 2017
Length: 566 pages
Edition : 1st
Language : English
ISBN-13 : 9781782168775
Languages :
Concepts :
Tools :

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 $ 141.97
Drupal 8 Module Development
$48.99
Drupal 8 Development Cookbook
$48.99
Drupal 8 Blueprints
$43.99
Total $ 141.97 Stars icon

Table of Contents

18 Chapters
Developing for Drupal 8 Chevron down icon Chevron up icon
Creating Your First Module Chevron down icon Chevron up icon
Logging and Mailing Chevron down icon Chevron up icon
Theming Chevron down icon Chevron up icon
Menus and Menu Links Chevron down icon Chevron up icon
Data Modeling and Storage Chevron down icon Chevron up icon
Your Own Custom Entity and Plugin Types Chevron down icon Chevron up icon
The Database API Chevron down icon Chevron up icon
Custom Fields Chevron down icon Chevron up icon
Access Control Chevron down icon Chevron up icon
Caching Chevron down icon Chevron up icon
JavaScript and the Ajax API Chevron down icon Chevron up icon
Internationalization and Languages Chevron down icon Chevron up icon
Batches, Queues, and Cron Chevron down icon Chevron up icon
Views Chevron down icon Chevron up icon
Working with Files and Images Chevron down icon Chevron up icon
Automated Testing Chevron down icon Chevron up icon
Drupal 8 Security Chevron down icon Chevron up icon

Customer reviews

Most Recent
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.3
(8 Ratings)
5 star 62.5%
4 star 12.5%
3 star 12.5%
2 star 12.5%
1 star 0%
Filter icon Filter
Most Recent

Filter reviews by




M.G. Aug 14, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Throughly conceived, and brilliantly executed. A really good resource for an in-depth look at Drupal 8's many aspects. Use it for reference all the time.
Amazon Verified review Amazon
Asiq Apr 24, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Great book if you want to learn Drupal8.
Amazon Verified review Amazon
Hgabo Sep 07, 2018
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Le contenu de ce livre est dense, les exemples sont intéressants.Il apporte un vrai plus par rapport à la documentation disponible sur le web.
Amazon Verified review Amazon
Kindle Customer Jul 20, 2018
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
This is a very in-depth and useful book, but it is let down by some poor editing of the included code examples, leading to hard to find bugs and requiring a crash course in xdebug to track them down. A comparison of the code in the book and the code in the github repository reveals the occasional missing use statement or typo which will cause subtle bugs and much hair tearing. See ImporterForm.php in the importer plugins section for an example of a missing use statement in the book code that is present in the github version. On the plus side I learnt a lot about debugging PHP while working through the book, but I presume this wasn't the explicit intention of the author. The book has a rushed and slightly sloppy feel about it.
Amazon Verified review Amazon
Amazon Customer Jul 19, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Very good book for Drupal developers.
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 the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela