Drupal at your Fingertips

repository·gh-pages·Indexed 42 days ago

https://github.com/selwynpolit/d9book

A modern quick reference book for Drupal developers providing accessible documentation for common development tasks. Topics include the Batch and Queue API, Blocks, Caching, Composer, Config, Cron, Entities, Forms, Hooks, Migration, Render Arrays, Routes, Services, and Testing with PHPUnit.

Tokens
239.2K
Snippets
750
Records
919
Agent score
53%

What's inside Drupal at your Fingertips

  1. Overview of AI Providers for Drupal

    gh-pages

    Drupal can interface with various AI providers to deliver services like text generation, semantic search, and image analysis.

    Key Providers:

    • amazee.ai: A private AI infrastructure provider focused on data sovereignty and GDPR compliance. Setup is straightforward using only a valid email; no manual API key management is required between the provider and Drupal.
    • OpenAI: Requires a preloaded account with funds. You can verify access via the OpenAI playground.
    • Ollama: Allows running Large Language Models (LLMs) locally on macOS, Windows, Linux, or Docker. This is an excellent way to test prompts without incurring API costs.
    • Other Providers: Anthropic, Groq, Huggingface, Imstudio, Mistral, AWS Bedrock, Google Gemini, and more.
  2. Overview of Drush

    gh-pages

    Drush is the command-line shell and Unix scripting interface for Drupal. It provides a wide range of core commands and generators to manage Drupal sites.

    Key capabilities include:

    • Running update.php and cron.
    • Executing SQL queries.
    • Running content migrations.
    • Extending functionality via 3rd party commandfiles, custom Drush commands, and Drush scripts.
  3. Explore the d9book reference topics

    gh-pages

    This book serves as a quick reference for Drupal developers. The following topics are covered in the repository:

    • Batch and Queue: Batch API
    • Blocks: Generating code for blocks, dependency injection, config forms, and permissions
    • Caching: Cache tags, disabling caching, REST resource caching, and development setup
    • Composer: Updates and patches
    • Config: Creating, loading, overriding, and Drush config commands
    • Cron: hook_cron, crontab files, and stopping cron
    • Dates: Date fields, arithmetic, expiration, and the Smart date module
    • Debugging: PhpStorm, DDEV, and Xdebug
    • Development: Local setup, DDEV, PHPStorm, Xdebug, and Twig debugging
    • Drush: Command line usage
    • Email: Sending emails in Drupal
    • Entities: Primary building blocks of Drupal
    • Forms: Form API, AJAX forms, and modals
    • Hooks: The Drupal hook system
    • Migration: Automated data ingestion
    • Nodes and Fields: Loading/saving nodes, field types (multivalue, link, entity reference, URL), and storing JSON in text fields
    • Queries: entityQueries, SQL queries, and content CRUD
    • Render Arrays: Working with Drupal's render system
    • Routes and Controllers: Routing and controller logic
    • Services: Dependency injection and services
    • Testing: PHPUnit and Drupal Test Traits
  4. Twig Templating Engine in Drupal

    gh-pages

    Drupal uses the Twig templating engine to provide a fast, secure, and flexible way to build templates. Twig allows developers to manipulate Drupal themes without needing deep PHP knowledge.

    Version Compatibility:

    • Drupal 10: Uses Twig 3
    • Drupal 9: Uses Twig 2
    • Drupal 8: Used Twig 1
  5. Overview of Services and Dependency Injection

    gh-pages

    In Drupal, services provide a decoupled way to access classes and members. They are pluggable and replaceable by registering them with a service container, which makes them ideal for unit testing with PHPUnit. There are two primary ways to access services:

    1. Static access: Using shorthand methods (e.g., //Drupal::serviceName()) or ControllerBase shortcuts.
    2. Dependency Injection (DI): Injecting the service into a class via its constructor, which is the preferred method for better testability and decoupling.
  6. What is Drupal Test Traits (DTT)?

    gh-pages

    Drupal Test Traits (DTT) is a testing framework designed for testing Drupal sites that already have content.

    Unlike standard PHPUnit tests that bootstrap an empty database (which is slow), DTT allows you to run tests against your existing database using features from Drupal's BrowserTestBase. This makes it ideal for testing existing sites without the need to wipe the database after every test run.

    Key features include:

    • HTML Snapshots: DTT can save HTML snapshots for every URL navigated to, which is useful for debugging failures.
    • JavaScript/AJAX Testing: Supports testing client-side interactions (autocomplete, #states, drag-and-drop) via headless Chrome or Selenium.
    • Fast Bootstrapping: Uses a specialized bootstrap process inspired by Drush.
  7. Overview of Drupal Batch API

    gh-pages

    The Batch API allows you to perform large-scale tasks by breaking them into smaller chunks. This prevents PHP timeouts and memory exhaustion. It leverages the Drupal Queue system, allowing processes to pick up where they left off if interrupted.

    Key features include:

    • Chunking: Breaking large datasets (e.g., node IDs) into smaller arrays using array_chunk().
    • Progress Tracking: Using the $context variable to track progress and display messages.
    • Completion Handlers: Defining a finished function to run after all operations complete.
    • Versatility: Can be used in Forms, Controllers, hook_update_N, and Drush commands.
  8. What are Render Arrays in Drupal?

    gh-pages

    Render Arrays are the fundamental building blocks of a Drupal page. They are associative arrays that follow the standards of Drupal's Render API and are integrated with the Theme API.

    Key characteristics:

    • Structured Data: Data is kept as structured arrays until the final stage of response generation, allowing for easy extension or overriding.
    • Tree Structure: Render arrays are nested, forming a "render tree" similar to the DOM.
    • Form API Relationship: While they share structure, Form API arrays are specifically transformed into render arrays by FormBuilder. You should avoid passing unprocessed Form API arrays directly to the Render API to prevent unexpected results.
    • Forms as Render Arrays: All forms in Drupal are render arrays.
    $my_render_array['some_item'] = [
      '#type' => 'markup',
      '#markup' => "This is a test",
    ];
  9. Generate module scaffolding with Module Builder

    gh-pages

    The Module Builder module auto-generates a skeleton/scaffolding for Drupal modules. Unlike standard code generators, it analyzes your site's code to detect existing plugin types, hooks, and services.

    It can generate:

    • Content and config entity types
    • Plugins (with injected services)
    • Forms (with injected services)
    • Routes and controllers
    • Permissions and Services
    • PHPUnit test case classes
    • api.php files for hook documentation
    • Admin settings forms and README files
    https://www.drupal.org/project/module_builder
  10. Understand the DTT bootstrap-fast.php file

    gh-pages

    The bootstrap-fast.php file provided by Drupal Test Traits is a customizable bootstrap file designed for speed.

    Key features:

    • Uses weitzman\DrupalTestTraits\AddPsr4 to register namespaces.
    • Handles PHPUnit compatibility for different major versions.
    • Allows manual registration of additional namespaces.

    Usage Tip: If you encounter 'class not found' errors, copy this file to your codebase (e.g., /scripts), add any missing namespaces to the bottom of the file, and point your phpunit.xml to this local copy.

    <?php
    use Drupal\TestTools\PhpUnitCompatibility\PhpUnit8\ClassWriter;
    use weitzman\DrupalTestTraits\AddPsr4;
    
    list($finder, $class_loader) = AddPsr4::add();
    $root = $finder->getDrupalRoot();
    
    $class_loader->addPsr4('Drupal\TestTools\', "$root/core/tests");
    if (class_exists('Drupal\TestTools\PhpUnitCompatibility\PhpUnit8\ClassWriter')) {
      ClassWriter::mutateTestBase($class_loader);
    }
    
    // Register more namespaces, as needed.
    # $class_loader->addPsr4('Drupal\Tests\my_module\', "$root/modules/custom/my_module/tests/src");
  11. Understand ChainedFastBackend for multi-server caching

    gh-pages

    The ChainedFastBackend is a specialized cache backend designed to combine a fast, inconsistent local cache with a slower, consistent shared cache.

    How it works:

    1. Fast Backend (e.g., APCu): Stored on the local web node. It is extremely fast but inconsistent (changes on one node aren't immediately seen by others).
    2. Slow Backend (e.g., MySQL, Redis, Memcached): Shared across all web nodes. It is consistent but requires a network round-trip.
    3. The Chain: When reading (get()), Drupal checks the fast backend. If the entry was created before the last write to the chained cache, it is considered outdated. Drupal then fetches the fresh data from the slow backend and updates the fast backend to ensure subsequent reads are fast.

    When to use it:

    • In multi-server environments to reduce network latency for cache hits.
    • In single-node environments where the fast backend (like APCu) is not shared between the web server and CLI processes (like Drush).

    Note: This backend is best suited for cache bins that do not change extremely frequently, as it marks all entries in a bin as outdated upon a write to that bin.