A successful website is an organic thing. There are always new pieces of content to add and new ways to present information, so client updates and new features are a common request. Drupal site builders have thousands of modules to tap into to add features and functionality without having to build them from scratch. If a thorough search for an existing module to fulfill a client request turns up empty, developers have to start thinking about how to build it themselves. But, where should they begin?
Drupal Architecture
One of the most important concepts in Drupal 8 development is the API ecosystem. This should be the primary place for developers to go to learn about Drupal’s underlying architecture and how to build successful components, or modules, that fit within it. In most cases, the structure of what a developer has in mind may already have an architectural consideration. Need a form? Use the Form API. Need to develop a plugin to extend existing entities? Use the Plugin API. And the list goes on.
The Drupal Core team has provided deep documentation for each API in Drupal 8, which has been greatly improved over previous versions. There are also numerous links to existing modules that implement the same APIs. So developers have a lot of resources to draw on to get started. But even with all the documentation and samples, actually creating files based on the the APIs can be cumbersome to code by hand. That’s where a code generator could come in handy.
Enter the Drupal Console
The Drupal Console Project provides command line tools to generate components based on API requirements. Built on the Symfony Framework Console, the Drupal Console generates boilerplate code for developers to use to take advantage of most APIs. One example of a complex API that the Console helps with a great deal is the Entity API, when building a new Content Entity. By starting with one command ..
drupal generate:entity:content
.. and entering information for each prompt, the console generates all the code you need to get started, including
- The content entity class
- CRUD forms
- A page to list all existing content
- A page to view content detail
- Permissions to access content
- Routes to access content and forms
- Action menu items
- Views integration
After further development and when you install your module, the Entity API generates the necessary database tables for you, and you’re ready to go. Drupal Console has an extensive list of code generation commands, for example for generating modules, themes and forms.
The Drupal Console is an indispensable tool for Drupal developers, and its extensive list of features and commands goes beyond code generation. When developing a new module, and after you’ve decided what APIs you need to implement, it should really be the next place to go.