# Debugging & Performance ## Documentation - Element queries: https://craftcms.com/docs/5.x/development/element-queries.html - Eager loading: https://craftcms.com/docs/5.x/development/eager-loading.html - Query batching: https://craftcms.com/knowledge-base/query-batching-batch-each - Template caching: https://craftcms.com/docs/5.x/reference/twig/tags.html#cache - Deprecation warnings: https://craftcms.com/docs/5.x/system/deprecation-warnings.html ## Common Pitfalls - Element query inside a loop without eager loading -- classic N+1. - Using `->all()` when you only need `->count()`, `->ids()`, or `->exists()`. - Choosing ElementQuery when ActiveRecord or direct Query builder would be more appropriate. - Forgetting `->status(null)` on cached element queries -- status changes over time create different cache keys. - Using Yii's `$query->batch()` instead of `Db::each()` -- Yii's version doesn't handle unbuffered MySQL properly. - Not disabling Xdebug when not debugging -- significant overhead even when idle. - Transform generation during page load -- push to queue or pre-generate. - Wrapping dynamic content in `{% cache %}` tags -- stale output for logged-in users, CSRF tokens, live dates. - Using `entry.relatedEntries.all()` inside a loop instead of eager loading on the parent query. - Calling `craft.entries.section('x').all()|length` to count -- loads all element objects into memory just to count them. ## Contents - [Query Strategy: When to Use What](#query-strategy-when-to-use-what) - [Eager Loading (Plugin-Side)](#eager-loading-plugin-side) - [Indexes and Foreign Keys](#indexes-and-foreign-keys) - [Batch Processing](#batch-processing) - [Logging](#logging) - [Profiling](#profiling) - [Debug Toolbar](#debug-toolbar) - [Template Debugging](#template-debugging) - [Twig Cache Tag](#twig-cache-tag) - [N+1 Detection and Fixes](#n1-detection-and-fixes) - [Query Logging and Analysis](#query-logging-and-analysis) - [Error Handling Patterns](#error-handling-patterns) - [Deprecation Tracking](#deprecation-tracking) - [Common Anti-Patterns](#common-anti-patterns) - [Xdebug with DDEV](#xdebug-with-ddev) - [Caching](#caching) ## Query Strategy: When to Use What Three query approaches, each with different tradeoffs: ### Element Queries -- for element data you'll display or manipulate The full Craft element system: field values, statuses, drafts, permissions, eager loading. Use when you need elements as objects with their full behavior: ```php $entries = MyElement::find() ->status('live') ->categoryId($categoryId) ->orderBy('postDate DESC') ->limit(10) ->all(); ``` **Performance shortcuts on element queries:** ```php ->count() // SELECT COUNT(*) -- don't load objects just to count them ->ids() // SELECT id only -- when you just need IDs ->exists() // SELECT 1 LIMIT 1 -- existence check ->pairs() // Key-value pairs from two columns ->asArray() // Skip Element model hydration, return plain arrays ``` ### ActiveRecord -- for plugin config tables (non-element data) Thin table mapping for your plugin's own config/settings tables (instances, match fields, site settings). Not for element data: ```php /** @var MyRecord[] $records */ $records = MyRecord::find() ->where(['categoryId' => $categoryId]) ->orderBy(['sortOrder' => SORT_ASC]) ->all(); ``` ActiveRecord gives you model objects with `save()`, `delete()`, and relation definitions, but no element lifecycle. Use for the `handleChangedItem()` pattern in project config handlers. ### Direct Query Builder -- for performance-critical joins and aggregates When you need complex JOINs, aggregations, subqueries, or bulk operations where neither ElementQuery nor ActiveRecord is appropriate: ```php $stats = (new Query()) ->select([ 'categoryId', 'COUNT(*) as total', 'SUM(CASE WHEN [[status]] = :live THEN 1 ELSE 0 END) as liveCount', ]) ->from(Table::MY_ELEMENTS) ->groupBy('categoryId') ->addParams([':live' => 'live']) ->all(); ``` Also use for `eagerLoadingMap()` implementations -- these need raw source-to-target ID mappings, not full element objects: ```php $map = (new Query()) ->select(['source' => 'id', 'target' => 'relatedItemId']) ->from(Table::MY_ELEMENTS) ->where(['id' => $sourceIds]) ->all(); ``` ### Decision Guide | Need | Use | |------|-----| | Elements with field values, statuses, permissions | Element Query | | Plugin config/settings records (non-element tables) | ActiveRecord | | Aggregations, complex JOINs, bulk reads | Query builder | | Eager loading maps, raw ID lookups | Query builder | | Project config handlers (`handleChanged`) | ActiveRecord | | Element counts, ID lists, existence checks | Element Query with `->count()` / `->ids()` / `->exists()` | ## Eager Loading (Plugin-Side) ### Custom Eager Loading Map For custom elements with relations to other elements, implement `eagerLoadingMap()`: ```php public static function eagerLoadingMap(array $sourceElements, string $handle): array|null|false { if ($handle === 'relatedItems') { $sourceIds = array_map(fn($el) => $el->id, $sourceElements); $map = (new Query()) ->select(['source' => 'id', 'target' => 'relatedItemId']) ->from(Table::MY_ELEMENTS) ->where(['id' => $sourceIds]) ->all(); return ['elementType' => RelatedItem::class, 'map' => $map]; } return parent::eagerLoadingMap($sourceElements, $handle); } ``` ### Pre-loading in Services When your service returns elements that consumers will iterate over, pre-load relations: ```php public function getItemsWithRelations(int $categoryId): array { return MyElement::find() ->categoryId($categoryId) ->with(['relatedItems', 'relatedItems.thumbnail']) ->all(); } ``` ### Twig-Side (Front-End Templates) Craft 5 introduced lazy eager loading via `.eagerly()` -- automatically batches relation loading in template loops. `.with()` supports nested dot notation for manual pre-declaration. These are template patterns, not plugin-side, but worth knowing when your element type is consumed in Twig. ## Indexes and Foreign Keys Design your migration indexes around how your element queries filter: ```php // Compound index for the most common query pattern $this->createIndex(null, Table::MY_ELEMENTS, ['categoryId', 'externalId'], true); // Single-column indexes for date-based filtering and sorting $this->createIndex(null, Table::MY_ELEMENTS, ['postDate']); $this->createIndex(null, Table::MY_ELEMENTS, ['expiryDate']); ``` Foreign keys with appropriate ON DELETE behavior: ```php // Element ownership -- cascade delete when element is hard-deleted $this->addForeignKey(null, Table::MY_ELEMENTS, ['id'], CraftTable::ELEMENTS, ['id'], 'CASCADE', null); // Reference to config entity -- null out when config entity deleted $this->addForeignKey(null, Table::MY_ELEMENTS, ['categoryId'], Table::CATEGORIES, ['id'], 'SET NULL', null); ``` ## Batch Processing ### `Db::each()` for Large Datasets Craft's wrapper handles unbuffered MySQL connections: ```php use craft\helpers\Db; $query = MyElement::find()->categoryId($categoryId)->site('*')->status(null); foreach (Db::each($query) as $element) { // Process one at a time, constant memory } // Or in batches of 100 foreach (Db::batch($query, 100) as $batch) { foreach ($batch as $element) { // Process batch } } ``` ### Memory Management ```php App::maxPowerCaptain(); // Raises memory_limit, removes max_execution_time ``` Craft calls this automatically for queue jobs. For console commands, call explicitly at the start of long-running actions. ## Logging ```php Craft::debug('Trace-level, devMode only', __METHOD__); Craft::info('Info level, devMode only', 'my-plugin'); Craft::warning('Always logged', 'my-plugin'); Craft::error('Always logged', 'my-plugin'); ``` **In production, only `warning` and above are logged.** Use the plugin handle as the category for easy filtering. Log files: `storage/logs/web-{date}.log`, `console-{date}.log`, `queue-{date}.log`. For containers: `CRAFT_STREAM_LOG=true`. **Forwarding logs over syslog-TLS: frame with octet counting.** RFC 5425 §4.3.1 requires octet-counted framing for syslog over TLS — each frame is `MSG-LEN SP SYSLOG-MSG`, where `MSG-LEN` is the message's byte length. Newline-delimited frames are RFC 6587 *non-transparent* framing, a different (legacy) scheme. The trap: rsyslog's `imtcp` accepts newline framing by default, so a newline-framed sender **appears to work** against the most common test receiver, then a strict RFC 5425 receiver (or a SIEM ingest endpoint) rejects or corrupts the stream. If a plugin ships a log-forwarding feature, emit octet-counted frames and say so in the docs. ## Profiling ```php Craft::beginProfile('expensiveOperation', __METHOD__); // ... code to profile ... Craft::endProfile('expensiveOperation', __METHOD__); ``` Shows in the Debug Toolbar's Time panel. ## Debug Toolbar Enabled when `devMode` is `true`. Users enable it under My Account > Preferences. **Most useful panels:** - **DB panel**: All queries, sortable by duration -- fastest way to find N+1. - **Profiling panel**: Custom `beginProfile`/`endProfile` blocks and per-template render times. - **Logs panel**: All log messages for the request. - **Deprecation panel**: Deprecation warnings triggered during the request. - **Mail panel**: Emails sent during the request (useful for verifying queue notifications). ## Template Debugging ### `dump()` and `dd()` Both require `devMode` to be enabled: ```twig {{ dump(entry) }} {# Dumps to debug bar, does not halt #} {{ dd(entry) }} {# Dump and die -- halts execution #} {{ dump(entry, category, currentUser) }} {# Multiple variables #} {{ dump() }} {# All variables in current scope #} ``` ### Quick JSON inspection Lightweight alternative to `dump()` for raw field values: ```twig
{{ entry.myMatrixField|json_encode(constant('JSON_PRETTY_PRINT')) }}
{{ craft.entries.section('blog').limit(3).ids()|json_encode }}
```
### devMode error display
When `devMode` is `true`, Craft shows verbose Yii error pages with full stack traces, query logs, and environment details. When `false`, Craft renders custom error templates (see [Error Handling Patterns](#error-handling-patterns)). Never leave `devMode` enabled in production -- stack traces expose file paths, database queries, and environment variables.
### Template profiling
The Profiling panel in the debug toolbar breaks down render time per template. Look for templates with high self-render time, templates called many times per request (unoptimized loops), and compilation overhead on first load.
## Twig Cache Tag
The `{% cache %}` tag caches rendered HTML. Craft tracks element queries inside the block and invalidates when those elements change.
### Basic usage
```twig
{% cache %}
{% set entries = craft.entries.section('blog').limit(10).all() %}
{% for entry in entries %}