GitHub stars
47

Install

/plugin install nette@nette

Run it inside Claude Code after adding the marketplace with /plugin marketplace add nette/claude-code.

Contents

Discovered from source

Skills 20

Frontend Development

Technology Stack

  • Build system: Vite with TypeScript support
  • JavaScript: ES Modules (ESM) with "type": "module" in package.json
  • Styling: SCSS with modular component architecture
  • Asset integration: Nette Assets for PHP-frontend bridge
  • Admin framework: Bootstrap for rapid interface development
  • Code quality: ESLint with @nette/eslint-plugin
  • Forms: Nette Forms with progressive enhancement

Asset Architecture Strategy

Source vs Built Assets separation:

  • Development assets: assets/ directory with source files (SCSS, TypeScript, images)
  • Production assets: www/assets/ with optimized, versioned files for browsers

Coding Standards

  • Use single quotes for strings unless containing apostrophes (CSS, SCSS, JavaScript)

Nette Assets Integration Patterns

Basic asset loading

{* Loads complete bundle with all dependencies *}
{asset 'app.js'}

Configuration

assets:
	mapping:
		default:
			type: vite
			path: assets       # REQUIRED in practice - must match Vite's build.outDir

path is optional in the schema and nothing validates it, but when omitted it falls back to %wwwDir%, so the manifest is looked up in www/.vite/manifest.json instead of www/assets/.vite/manifest.json and you get RuntimeException: Failed to read Vite manifest. devServer defaults to true, so there is no need to write it.

HMR works only when the application is in debug mode and the dev server is running, which PHP learns from the file .vite/nette.json that the plugin writes into the mapper's path. The lookup is hardcoded, so renaming the file with the plugin's infoFile option silently disables the detection; then set devServer: '<url>' in NEON by hand.

type="module" is added only to Vite entry points. A script served by a file mapper renders as a plain <script>, so an import in it fails with Cannot use import statement outside a module. Write the attribute yourself, <script type="module" n:asset="app.js"></script>; the only option {asset} accepts for such a file is version, anything else throws.

Data Flow from Backend to Frontend

Passing data to JavaScript:

{* In template *}
<script>
window.appConfig = {
	apiUrl: {$baseUrl . '/api'},
	userId: {$user->isLoggedIn() ? $user->getId() : null},
	locale: {$locale},
	csrfToken: {$csrfToken}
};
</script>
{asset 'app.js'}

Latte automatically applies context-sensitive escaping – values inside <script> are JSON-encoded, so strings get quoted and null stays null.

// In JavaScript component
const { apiUrl, userId, csrfToken } = window.appConfig;

fetch(`${apiUrl}/user-data`, {
	headers: { 'X-CSRF-Token': csrfToken }
});

Naja (AJAX Library)

Naja is the standard AJAX library for Nette – it handles snippet redrawing, form submissions, and history integration:

npm install naja
import naja from 'naja';

// Initialize after DOM is ready
naja.initialize();

Naja automatically intercepts links and forms with the ajax CSS class and handles snippet updates from the server. See Naja documentation for configuration and extensions.

Nette Forms Integration

Requires nette-forms npm package:

npm install nette-forms

Standard enhancement pattern:

import netteForms from 'nette-forms';

// Initialize Nette Forms validation
netteForms.initOnLoad();

TypeScript

Vite transpiles .ts entry points out of the box but never type-checks them. For checking, install typescript, set "moduleResolution": "bundler" and "noEmit": true in tsconfig.json, and add a script "typecheck": "tsc --noEmit" to package.json.

ESLint Configuration

npm install --save-dev @nette/eslint-plugin eslint

Basic configuration with recommended rules:

// eslint.config.js
import nette from '@nette/eslint-plugin';
import { defineConfig } from 'eslint/config';

export default defineConfig([
	{
		extends: [nette.configs.recommended],
	},
]);

Linting JavaScript in Latte templates:

npm install --save-dev eslint-plugin-html
// eslint.config.js
import nette from '@nette/eslint-plugin';
import pluginHtml from 'eslint-plugin-html';
import { defineConfig } from 'eslint/config';

export default defineConfig([
	{
		extends: [nette.configs.recommended],
	},
	{
		files: ['app/**/*.latte'],
		plugins: {
			html: pluginHtml,
		},
		processor: '@nette/latte',  // Handles Latte tags in JS
	},
]);

This allows ESLint to check JavaScript inside <script> tags with Latte variables:

<script>
let name = {$name};
</script>

TypeScript support:

npm install --save-dev typescript typescript-eslint
import nette from '@nette/eslint-plugin/typescript';

export default defineConfig([
	{
		extends: [nette.configs.typescript],
	},
]);

Custom rules:

  • @nette/no-this-in-arrow-except - Prevents this binding issues in arrow functions
  • @nette/prefer-line-comments - Enforces // over /* */ for single-line comments

Tailwind CSS Integration

When using Tailwind CSS, configure it to scan Latte templates for class names:

/* assets/css/app.css */
@import 'tailwindcss';
@source '../app/**/*.latte';

Documentation

The full Nette documentation for this topic is bundled with the plugin. Read a page when you need details beyond this skill:

Naja, the AJAX library, has its own documentation at https://naja.js.org/.

Latte Templating System

Latte is a secure templating engine with context-aware escaping, intuitive syntax, and powerful template inheritance.

composer require latte/latte

Basic Syntax

{* this is a comment *}
<ul n:if="$items">                {* n:attribute *}
{foreach $items as $item}         {* tag *}
	<li>{$item|capitalize}</li>   {* variable with filter *}
{/foreach}
</ul>

Printing Variables

{$name}                    {* prints escaped variable *}
{$user->name}              {* object property *}
{$items[0]}                {* array access *}
{='hello'|upper}           {* expression with filter *}
{$html|noescape}           {* disable escaping (use carefully!) *}

Latte uses context-aware escaping — output adapts to where the variable is printed. In <script> context, arrays and objects are automatically serialized to JSON:

{* Arrays auto-serialize to JSON inside <script> *}
<script type="application/ld+json">{$schemaData}</script>

<script>
	let config = {$config};
</script>

Never use json_encode() in PHP + |noescape for this — Latte handles serialization and escaping safely on its own.

Filters

Filters modify output, written after |:

{$title|upper}                    {* HELLO *}
{$text|truncate:100}              {* shortens to 100 chars *}
{$price|number:2}                 {* formats number *}
{$date|date:'j. n. Y'}            {* formats date *}
{$name|lower|capitalize}          {* chained filters *}

Common filters: upper, lower, capitalize, truncate, number, date, noescape, escapeUrl, stripHtml, trim, replace, first, last, length, sort, reverse

The filter | applies to the entire expression before it. Parentheses around PHP operators (like ??) before a filter are unnecessary:

{$a ?? $b|texyLine|noescape}        {* correct – filter applies to result of ?? *}
{($a ?? $b)|texyLine|noescape}      {* redundant – parentheses change nothing *}

See the complete filter reference for all available filters.

n:attributes

Pair tags can be written as HTML attributes:

{* These are equivalent: *}
{if $condition}<div>...</div>{/if}
<div n:if="$condition">...</div>

{* Applies to element content only: *}
<div n:inner-foreach="$items as $item">...</div>

{* Applies to tag only (not content): *}
<a href={$url} n:tag-if="$url">Link</a>

Conditions and Loops

{if} / {elseif} / {else}, {foreach} and {for} work as expected. What is Latte-specific:

{ifset $user}...{/ifset}          {* the variable exists, unlike {if isset()} *}

{switch $type}                    {* no break, cases do not fall through *}
	{case admin}Administrator
	{case user}User
	{default}Guest
{/switch}

{foreach $items as $item}
	<li>{$item}</li>
{else}                            {* runs when the array is empty *}
	<li>No items found</li>
{/foreach}

{foreach $items as $item}
	{$iterator->counter}. {$item}   {* 1, 2, 3…; also ->first, ->last, ->odd, ->even *}
	{first}<ul>{/first}             {* rendered only in the first iteration *}
	{last}</ul>{/last}
	{sep}, {/sep}                   {* separator, skipped after the last item *}
{/foreach}

Variables

{var $name = 'John'}
{var $items = [1, 2, 3]}
{default $lang = 'en'}            {* only if not set *}

{capture $content}
	<p>Captured HTML</p>
{/capture}
{$content}

Template Inheritance

Layout template (@layout.latte):

<!DOCTYPE html>
<html>
<head>
	<title>{block title}Default{/block}</title>
</head>
<body>
	{block content}{/block}
</body>
</html>

Child template:

{layout '@layout.latte'}

{block title}My Page{/block}

{block content}
	<h1>Welcome</h1>
	<p>Content here</p>
{/block}

Including Templates

{include 'header.latte'}
{include 'item.latte', item: $item, showPrice: true}
{include $dynamicTemplate}

Blocks

{block sidebar}
	<aside>Sidebar content</aside>
{/block}

{include sidebar}                          {* print block *}
{include sidebar from 'other.latte'}       {* from another file *}

{* Reusable definitions with parameters *}
{define button, $text, $type = 'primary'}
	<button class="btn btn-{$type}">{$text}</button>
{/define}

{include button, 'Submit'}
{include button, 'Cancel', 'secondary'}

Other Common Tags

TagDescription
{do expression}Execute without output
{php expression}Obsolete alias for {do} – a single expression only. Real PHP code needs RawPhpExtension
{dump $var}Debug dump (Tracy)

See the complete tag reference for all available tags.

Smart HTML Attributes (Latte 3.1)

Applies only when the whole attribute value is one {...} expression (title={$t} or title="{$t}"). In a mixed value (title="foo {$t}") none of it applies – null becomes '', an array becomes "Array". n:attr follows the same rules, so {if} / n:attr wrappers around attributes are obsolete.

KindAttributesValue handling
boolallowfullscreen async autofocus autoplay checked controls default defer disabled formnovalidate inert ismap itemscope loop multiple muted nomodule novalidate open playsinline readonly required reversed selectedtruthy → bare name; falsey (false, null, 0, '', []) → omitted
tristatecontenteditable draggable spellcheck writingsuggestionsbool → the keywords "true" / "false"; null omits the attribute
valued boolhidden popoverflag like a bool, but a non-empty value survives (hidden="until-found"); falsy is tested first, so '0' omits it rather than rendering an invalid value
listaccesskey class headers itemprop ping rel role sandboxarray → space-separated
stylestylearray → prop: value; …
datadata-*array / stdClass → JSON; bool → "true" / "false"
ariaaria-*bool → "true" / "false"; array → space-separated
plaineverything elsestring/int/float/Stringable printed; null omits the attribute; array, bool or other object → E_USER_WARNING and the attribute is dropped

In list/aria arrays a plain item is used as-is, a keyed item yields the key only if its value is === true (active => 1 renders 1, not active); items with null, false, 0, '' are skipped, an all-skipped array omits the attribute. In style, a keyed item is skipped by the same rule, so opacity => 0 vanishes ('0px' survives).

<input type="text" disabled={$disabled} readonly={$readonly}>
{* false, true → <input type="text" readonly> *}

<div title={$title}>x</div>          {* null → <div>x</div> *}
<div title="Hi {$name}">x</div>      {* null → <div title="Hi ">x</div> (mixed value) *}
<div title={$title|upper}>x</div>    {* null → <div title="">x</div> (filter stringifies null) *}
<div title={$title?|upper}>x</div>   {* null → <div>x</div> (?| preserves the drop) *}

<button class={[btn, btn-primary, active => $isActive, disabled => $isDisabled]}>x</button>
{* true, false → <button class="btn btn-primary active">x</button> *}

<a rel={[nofollow, external => $isExternal]}>l</a>  {* true → <a rel="nofollow external">l</a> *}
<span title={[a, b]}></span>  {* warning: array is not allowed for 'title'; attribute dropped *}
<input value={$rows}>         {* array → same warning, no more value="Array" *}

<div style={[background => lightblue, opacity => 0, display => $vis ? block : null]}></div>
{* false → <div style="background: lightblue"></div> *}

<div data-config={[theme: dark, version: 2]} data-open={=true}></div>
{* → <div data-config='{"theme":"dark","version":2}' data-open="true"></div> *}

<button aria-expanded={=false} aria-labelledby={[title, desc => $has]}></button>
{* false → <button aria-expanded="false" aria-labelledby="title"></button> *}

<div data-active={$on|toggle}></div>  {* toggle = bool handling for any attribute; false → <div></div> *}
<div title={$cfg|json}></div>         {* json (must be the last filter) = JSON handling *}

A real filter defeats smart handling – it stringifies the value: class={$arr|noescape} renders class="Array". Keep smart attributes filter-free; toggle, json, nocheck and accept are compile-time hints, not filters, and are safe.

Traps:

  • URL attributes are exempt (href, src, action, formaction, <object data>): Latte appends an internal checkUrl filter, so href={$url} with null renders href="", and an array gives href="Array" with only a PHP notice. Use href={$url?|nocheck} for the drop (this also skips the URL safety check).
  • Tristate attributes distinguish three states: true and false render the keyword, null drops the attribute. That matters, because "missing" and ="false" mean different things — contenteditable="false" disables editing inside an editable region, whereas a missing attribute inherits from the parent.
Prefer class={[...]} and smart attributes over n:class / n:attr

Since 3.1 the attribute forms cover almost everything the n: ones did, so new templates should reach for them first. Neither n:class nor n:attr is deprecated in Latte, and there is one case only n:attr can express (below), so this is a preference, not a removal.

Do not rewrite existing templates mechanically — two differences change the rendered output:

<a n:class="$cnt ? open, item">      {* → *}  <a class={[$cnt ? open, item]}>  {* keep the ternary *}
<a class={[open => $cnt]}>           {* wrong – $cnt = 3 renders class="3" *}
<a class={[sel => $row]}>            {* wrong – a Stringable renders its string, a plain object throws *}
<option n:attr="selected: $sel">     {* → *}  <option selected={$sel}>
  1. A keyed item applies only when its value is === true. With any other truthy value the value is printed instead of the key, which is silent. Keep the ternary rather than moving the condition into a key.
  2. n:class de-duplicates the list (array_unique), class={[...]} does not — the same class listed twice survives after the rewrite.

n:class additionally rejects an array variable (n:class="$arr" → class="Array"; use class={$arr}) and a sibling class="…" on the same tag (CompileException); both fail loudly.

The one case n:attr still owns is a dynamic set or name of attributes, which no static attribute can express:

<tr n:attr="$attrs">          {* ['data-id' => 5, 'class' => 'row'] → data-id="5" class="row" *}
<a n:attr="[$name => $val]">  {* attribute name from a variable *}

Migration from 3.0 – changed: null used to print =""; data-/aria- bools printed "1"/""; data- arrays printed a space-separated list; on* values were JSON-encoded. $engine->setFeature(Latte\Feature::MigrationWarnings, true) warns on every affected attribute; the |accept filter silences it per value.


Latte in Nette Applications

Template Organization Strategy

Keep templates with presenters:

Product/
├── ProductPresenter.php
├── default.latte
├── edit.latte
└── detail.latte

Layout placement follows presenter organization:

Admin/
├── @layout.latte           ← Admin-wide layout
├── Auth/
│   ├── @layout.latte       ← Auth-specific layout
│   └── AuthPresenter.php
└── Catalog/
	└── Product/
		├── ProductPresenter.php
		└── edit.latte

The more specific a layout, the closer it sits to the presenters it serves; whether it extends the enclosing one is up to it. Keep such chains short: a part that only some pages share usually fits better through {include} or {define} than through another layout level.

Template Partial Patterns

Shared template parts use @ prefix:

  • @layout.latte - layout templates
  • @form.latte - reusable form structures
  • @item.latte - list item templates

Passing Variables to Templates

Templates display data; computing it (calculations, filtering, aggregation) belongs in render<View>() or a service. The standard way is assigning to $this->template:

$this->template->article = $this->articles->getById($id);

For properties that should always be available in templates, use the #[TemplateVariable] attribute (the property must be public – on a protected one it throws LogicException) instead of repeating assignments in every action:

use Nette\Application\Attributes\TemplateVariable;

class ArticlePresenter extends Nette\Application\UI\Presenter
{
	#[TemplateVariable]
	public string $siteName = 'My blog';
}

The property value is automatically passed as $siteName in every template. If you explicitly assign $this->template->siteName in an action, the explicit value wins.

Template Class Strategy

Create template classes for complex presenters:

/**
 * @property-read ProductTemplate $template
 */
class ProductPresenter extends BasePresenter
{
}

class ProductTemplate extends Nette\Bridges\ApplicationLatte\Template
{
	public ProductRow $product;
	public array $variants;
	public ?CategoryRow $category;
}

When to use template classes:

  • Presenters with 5+ template variables
  • Complex data structures passed to templates
  • When you want full IDE support in templates

Template Type Declaration:

{templateType App\Presentation\Product\ProductTemplate}

<h1>{$product->name}</h1>
{foreach $variants as $variant}
	<div class="variant">{$variant->name} - {$variant->price}</div>
{/foreach}

Nette-specific Tags

{* Links *}
<a n:href="Product:detail $id">Detail</a>
<a href={link Product:detail $id}>Detail</a>
<a href={link //Product:detail $id}>Absolute (// makes it absolute)</a>
<a href={plink Product:detail $id}>From a component template, link to a PRESENTER</a>

{* Components *}
{control productForm}
{control dataGrid}

{* AJAX Snippets *}
{snippet items}
	{foreach $items as $item}
		<div>{$item->name}</div>
	{/foreach}
{/snippet}

{* Forms *}
{form loginForm}
	{label username}{input username}
	{label password}{input password}
	{input submit}
{/form}

{* Assets (Nette Assets) *}
{asset 'admin.js'}
{asset 'front.css'}

Extension and Customization

Create single extension for entire application:

final class LatteExtension extends Latte\Extension
{
	public function getFilters(): array
	{
		return [
			'money' => fn($amount) => number_format($amount, 0, ',', ' ') . ' Kč',
		];
	}

	public function getFunctions(): array
	{
		return [
			'canEdit' => fn($entity) => $this->user->isAllowed($entity, 'edit'),
		];
	}
}

Register in config:

latte:
	strictParsing: yes
	extensions:
		- App\Presentation\Accessory\LatteExtension

Enable strictParsing to catch template errors early (missing variables, typos in tag names).

Documentation

The full Nette documentation for this topic is bundled with the plugin. Read a page when you need details beyond this skill:

NEON Format

NEON (Nette Object Notation) is a human-readable data format used for configuration files in Nette. Similar to YAML but with support for entities and tab indentation.

composer require nette/neon

Mappings

Key-value pairs with required space after colon:

street: 742 Evergreen Terrace
city: Springfield
country: USA

Inline notation with braces:

{street: 742 Evergreen Terrace, city: Springfield, country: USA}

Sequences

Indexed arrays with hyphen and space:

- Cat
- Dog
- Goldfish

Inline notation with brackets:

[Cat, Dog, Goldfish]

Nesting

Indentation defines structure:

pets:
	- Cat
	- Dog
cars:
	- Volvo
	- Skoda

Block and inline can be combined:

pets: [Cat, Dog]
cars:
	- Volvo
	- Skoda

Strings

Unquoted, single-quoted, or double-quoted:

- An unquoted string
- 'Single-quoted string'
- "Double-quoted with \t escapes"

Quote strings containing: # " ' , : = - [ ] { } ( )

Double a quote to include it: 'It''s working'

Multiline strings with triple quotes:

'''
	first line
		second line
	third line
'''

Special Values

# Numbers
count: 12
price: 12.3
scientific: +1.2e-34
binary: 0b11010
octal: 0o666
hex: 0x7A

# Null
value: null
empty:

# Booleans
enabled: true
disabled: false
active: yes
inactive: no

# Dates (auto-converted to DateTimeImmutable)
date: 2016-06-03
datetime: 2016-06-03 19:00:00
with_tz: 2016-06-03 19:00:00 +02:00

Unlike YAML: on/off are strings, 0777 is the decimal 777, and 1_000, 0X10, -0x1 and an invalid date such as 2024-02-30 stay strings.

Entities

Function-like structures for DI configuration:

Column(type: int, nulls: yes)

Chained entities:

Column(type: int) Field(id: 1)

Multiline entity:

Column(
	type: int
	nulls: yes
)

Comments

# This line is ignored
street: 742 Evergreen Terrace  # inline comment

Block vs Inline Notation

Use inline for short, simple values (up to ~3 items):

extensions: [foo, bar]
roles: {admin: true, user: false}

Use block for anything complex, nested, or long:

services:
	- App\Model\UserService
	- App\Model\OrderService

Key Rules

  • Space after : is required (key: value, not key:value)
  • Use tabs for indentation. Spaces are valid too (Neon::encode() just defaults to tabs); unlike YAML, NEON accepts either, so never "fix" space-indented NEON
  • Block notation cannot be nested inside inline notation
  • Unquoted strings cannot start/end with spaces or look like numbers/booleans/dates

PHP API

use Nette\Neon\Neon;

encode(mixed $value, bool|callable $blockMode=false, string $indentation="\t"): string

Converts PHP value to NEON. Pass true to $blockMode for multiline output, or since 4.0 a callable fn($array, $path): bool deciding per array. The constant Neon::BLOCK is deprecated.

Neon::encode($value);       // inline NEON
Neon::encode($value, true); // multiline NEON
Neon::encode($value, fn($value, $path) => !$path); // blocks on the first level only

decode(string $neon): mixed

Parses NEON string to PHP value. Dates become DateTimeImmutable, entities become Nette\Neon\Entity.

Neon::decode('hello: world'); // ['hello' => 'world']

decodeFile(string $file): mixed

Parses NEON file to PHP value (removes BOM).

Neon::decodeFile('config.neon');

All methods throw Nette\Neon\Exception on error.

Editing a File: parse()

To change a file programmatically, never decode() and encode() it: that loses comments, formatting and number styles. Since nette/neon 4.0 Neon::parse() gives a lossless tree:

$doc = Neon::parse(file_get_contents('config.neon'));
$doc->setValue(['database', 'host'], 'db.example.com'); // adds a missing last key; a missing parent throws
$doc->addItem(['services'], 'App\Model\OrderFacade');
$doc->removeItem(['database', 'debug']);
$doc->setKey(['mail'], 'mailer');
file_put_contents('config.neon', $doc->print());

Only the touched values change, written in the style of the old ones (yes becomes no).

Lint Command

Check syntax errors in .neon files or directories:

vendor/bin/neon-lint <path>

It prints file:line:column: message per problem and exits 0 when all files are valid, 1 on a finding. Since 4.0 --check also verifies the file reads back byte for byte, --json gives JSON output.

Documentation

The full Nette documentation for this topic is bundled with the plugin. Read a page when you need details beyond this skill:

For new projects, see the project skeleton reference. For the #[Requires] attribute (HTTP method/AJAX restrictions on actions), see the documentation.

Application Architecture

Presenter Lifecycle

Understanding the request flow is essential for placing logic correctly:

  1. checkRequirements() – evaluates the #[Requires] attribute
  2. startup() – use for access checks and early redirects. An override must call parent::startup(), otherwise Nette throws InvalidStateException
  3. action<Name>() – processes the request (data writes, redirects)
  4. canonicalization – the redirect to the canonical URL happens here, i.e. after the action
  5. handle<Signal>() – signals run after the action phase and after canonicalization, not inside the action phase
  6. beforeRender() – runs before every render, use for shared template variables
  7. render<Name>() – prepares data for the template (read-only, no redirects)
  8. afterRender() – after the render methods, before the template is sent
  9. template is sent, then shutdown()

Each phase also has an event: $onStartup, $onRender, $onShutdown.

The key insight: actions and signals do things (write, redirect), renders prepare views (read). Mixing these responsibilities leads to redirect-after-render bugs and untestable presenters.

Directory Structure

The application follows domain-driven organization. The reason: when code is grouped by domain (products, orders, customers), related files are close together and changes to one feature don't scatter across multiple directories.

  • App: The main application namespace (App\)
    • Bootstrap: Application initialization and configuration
    • Core: Infrastructure concerns (routing, integrations)
    • Entity: Database entities (see nette-database skill for entity design)
    • Model: Business logic services organized by domain
    • Presentation: UI layer organized by modules
    • Tasks: Command-line executable tasks

Evolution Strategy

Start minimal -> Grow organically -> Refactor when painful

Start with flat structure – create subdirectories only when you have 5+ related files or clear implementation variants. The threshold exists because below 5 files, subdirectories add navigation overhead without improving discoverability.

Don't architect for theoretical future complexity. Address actual complexity when it emerges with clear user needs driving structural decisions.

When refactoring to deeper structure: Move files one domain at a time. Create the new subdirectory, move related presenters/services into it, update namespaces, and verify. Don't reorganize everything at once.

Configuration

  • config/common.neon: Main application configuration
  • config/services.neon: Service definitions and auto-wiring configuration

For DI configuration details (service registration, autowiring, parameters), see the nette-configuration skill.

Core vs Model Decision Matrix

The distinction matters because Core/ code is reusable across projects while Model/ code is specific to your business. This affects testability, replaceability, and team ownership.

Use Core/ for:

  • Technology-agnostic infrastructure (MyExplorer, RouterFactory, QueueMailer)
  • External service integrations (SentryLogger, AI/, GoogleSearch/)
  • Framework extensions and utilities
  • Code that could be moved to another project unchanged

Use Model/ for:

  • Business domain logic (CatalogService, CustomerService, OrderService)
  • Domain-specific operations and rules
  • Entity-specific processing logic
  • Code that knows about your business concepts (products, orders, customers)

Model Layer Principles

app/Model/
├── CatalogService.php       ← Main domain services at root
├── CustomerService.php
├── OrderService.php
├── mails/                   ← Email templates (specialized assets)
├── Payment/                 ← Implementation variants
│   ├── CardOnlinePayment.php
│   ├── BankTransferPayment.php
│   └── CashPayment.php
└── exceptions.php           ← Domain exceptions

Naming convention: mails/ is lowercase because it contains non-PHP assets (email templates). Payment/ is uppercase because it contains PHP classes following PSR-4.

Service placement rules:

  1. Main domain coordinator services directly in Model/
  2. Implementation variants get subdirectories when 3+ implementations exist
  3. Specialized assets (templates, exceptions) in focused locations

Module Structure

Modules group presenters by user audience and access requirements. Admin, Front, and Api have different authentication, layouts, and URL patterns – that's why they're separate modules, not just for organization.

app/Presentation/
├── Accessory/               ← UI shared across entire application
│   ├── LatteExtension.php
│   └── TemplateFilters.php
├── Admin/
│   ├── BasePresenter.php    ← Admin-specific functionality
│   ├── Auth/                ← Authentication
│   ├── Catalog/             ← Product management
│   │   ├── Brand/
│   │   ├── List/            ← Overview/utility presenters
│   │   └── Product/
│   └── Fulfill/             ← Order processing
└── Front/
    ├── Customer/
    └── Listing/

Keep presenters flat until complexity demands structure:

# Start simple
Dashboard/DashboardPresenter.php

# Grow when needed
Admin/Catalog/Product/ProductPresenter.php
Admin/Catalog/Brand/BrandPresenter.php
Admin/Catalog/List/ListPresenter.php

Create nested structure when:

  • Single functional area has 4+ presenters
  • Clear sub-domains emerge (Product management, Order fulfillment)
  • Shared logic between related presenters

Presenter Directory Contents

Each presenter directory contains the presenter class, its templates, and its local components:

Product/
├── ProductPresenter.php
├── default.latte
├── edit.latte
└── ProductFormFactory.php   ← Form factory used only by this presenter

For template organization details (layouts, partials, @-prefixed files), see the latte-templates skill.

Base Presenter Strategy

Create BasePresenter for each major module only when needed:

  • Admin\BasePresenter – authentication checks, admin-specific setup
  • Contains common startup() checks, beforeRender() template variables

Avoid deep inheritance – prefer composition over inheritance chains deeper than BasePresenter -> SpecificPresenter. Deep chains make it hard to understand which method runs when and create fragile coupling between unrelated presenters.

Component, Factory, and Accessory Placement

Where to place components, form factories, Latte extensions, and other shared code follows a proximity principle – keep code close to where it's used:

In the presenter directory – used by one presenter only:

Product/
├── ProductPresenter.php
├── ProductFormFactory.php   ← Only ProductPresenter uses this
└── edit.latte

In Module/Accessory/ – shared across presenters within one module:

Admin/
├── Accessory/
│   ├── DataGridFactory.php  ← Used by multiple Admin presenters
│   └── AdminFilters.php     ← Admin-specific template helpers
├── Product/
└── Order/

In Presentation/Accessory/ – shared across modules:

Presentation/
├── Accessory/
│   ├── LatteExtension.php     ← App-wide Latte filters/functions
│   ├── NavigationFactory.php  ← Used in Admin and Front
│   └── TemplateFilters.php

Form factories that encapsulate form creation with validation and callbacks are preferred over building forms directly in presenters when the same form appears in multiple places. For form factory implementation patterns, see the nette-forms skill.

When to Create New Module

Create module when:

  • You have 5+ related presenters
  • Functionality has distinct user base (Admin vs Front vs Api)
  • Different authentication/authorization requirements
  • Separate URL structure patterns

Avoid modules for:

  • Single presenter with single purpose
  • Artificial separation without clear user/functional boundaries

Tasks and Command Organization

app/Tasks/
├── Maintenance/           ← Cleanup, optimization
├── Integration/           ← External data sync
└── Scheduled/             ← Recurring operations

Task responsibility boundaries:

  • Tasks handle execution context (CLI arguments, error handling, scheduling)
  • Business logic stays in Model services
  • Tasks coordinate, services execute

This separation means business logic is testable without CLI context and reusable from presenters or other entry points.

Anti-Patterns to Avoid

Don't separate by technical layer – Services/, Repositories/, Controllers/ separation forces you to jump between directories for every feature change. Domain organization keeps related code together.

Don't create deep hierarchies – prefer descriptive names over nested structure (OrderFulfillmentService vs Fulfill/Order/Service). Deep nesting increases cognitive load and makes imports longer without adding clarity.

Documentation

The full Nette documentation for this topic is bundled with the plugin. Read a page when you need details beyond this skill:

Nette Caching

composer require nette/caching

Version 4.0 requires PHP 8.4. What differs from 3.x is in Upgrading; check the installed version before relying on Dependencies or named arguments of clean().

Dependencies

Since 4.0 dependencies are the object Nette\Caching\Dependencies with the properties expire, sliding, tags, priority, files, items, constants and callbacks. A generator whose parameter is typed Dependencies gets the object; an untyped one gets the array by reference.

use Nette\Caching\Cache;
use Nette\Caching\Dependencies;

$cache = new Cache($storage, 'articles'); // Nette\Caching\Storage is autowired
$sub = $cache->derive('previews');        // nested namespace
$html = $cache->load("article/$id", function (Dependencies $dp) use ($id) {
	$dp->expire = '20 minutes';
	$dp->tags = ["article/$id"];
	return renderArticle($id);
});
$cache->save($key, $value, new Dependencies(expire: '1 hour', tags: ['articles']));

The array form with Cache::* keys still works. Since 4.0 an unknown key or a wrong type throws, typically a priority written as the string '50'. The constants are PascalCase:

Cache::Expire      // 'expire'   – NOT Cache::Expiration (that constant does not exist)
Cache::Sliding     // 'sliding'
Cache::Tags        // 'tags'
Cache::Files       // 'files'     – resolved with filemtime(), so a relative path depends on the CWD; use absolute
Cache::Items       // 'items'     – other cache keys
Cache::Constants   // 'consts'
Cache::Callbacks   // 'callbacks' – [callable, ...args], must return true to stay valid.
                   //               The callable is SERIALIZED with the entry, so a closure is
                   //               a fatal ("Serialization of 'Closure' is not allowed") –
                   //               use a function name or [Class::class, 'method'].
Cache::Priority    // 'priority'  – int

Cache::EXPIRATION and the other UPPER_CASE names are deprecated aliases (E_USER_DEPRECATED since 4.0); Cache::Expiration does not exist and is a fatal Undefined constant. There is likewise no forget(), no delete() and no has() – removal is remove($key).

Reading and Writing

  • Prefer load() with a generator to save(): only with a generator do FileStorage and RedisStorage protect against cache stampede. If the generator throws, nothing is stored. A generator must not load() its own key: FileStorage throws InvalidStateException.
  • load($key) without a generator returns null on a miss, so null is not storable: save($key, null) removes the entry, as does an expire resolving to <= 0.
  • expire accepts seconds, a UNIX timestamp, a DateTimeInterface or any DateTime::from() string. Keys may be any serializable value, not just strings; save() returns the value.
  • save() with a closure as the data is deprecated; use load().

Cleaning

$cache->clean(tags: ["article/$id"]);  // in every namespace of the storage
$cache->clean(priority: 50);           // priority <= 50; items without priority stay
$cache->clean(namespaces: ['articles']);
$cache->clean(all: true);              // only this namespace and those derived from it

Since 4.0 clean() takes named arguments (3.x: clean([Cache::Tags => [...]]), which still works). clean() with no condition throws; expired items are removed by $storage->clean([]). all on a cache with a namespace no longer wipes the storage, only a cache without one does.

Storages and the Journal

A storage throws Nette\NotSupportedException for a dependency or condition it cannot honor (3.x silently ignored them):

StorageTags, priorityFiles, constants, callbacksItemsSlidingClean namespacesStampede
FileStorage (default)journalyesyesyesyesyes
RedisStorageyesyesnoyesyesyes
MemcachedStoragejournalyesnoyesnono
SQLiteStoragetags onlynonoyesyesno
MemoryStorageyesignoredignoredyesyesno
Psr16Storagejournalyesnononono

"journal": without one, a write with tags or priority throws Nette\InvalidStateException: CacheJournal has not been provided. The default journal is SQLiteJournal, and the DI extension registers it only if pdo_sqlite is loaded – without that extension every tagged save() blows up at runtime. MemoryStorage silently ignores what it cannot do, so in tests an item that would expire in production stays.

Nette\Bridges\Psr\PsrCacheAdapter exposes a storage as PSR-16 and since 4.0 rejects keys containing {}()/\@: such as user:1; Psr16Storage is the opposite direction.

$values = $cache->bulkLoad($keys, fn($key, Dependencies $dp) => compute($key)); // scalar keys only
$cache->bulkSave([$k1 => $v1, $k2 => $v2], new Dependencies(expire: '20 minutes'));

if ($capture = $cache->capture($key)) {   // start() is the deprecated old name
	echo $renderedHtml;
	$capture->end();
}

{cache} in Latte

{cache $id, expire: '20 minutes', tags: [tag1, tag2], if: !$form->isSubmitted()}

All arguments are optional, but the tag defaults to a 7-day expiration, unlike the PHP API which caches indefinitely. The block is invalidated automatically when the template file changes, and invalidating a nested block invalidates its parents. nette/caching 4.0 requires Latte 3.1 for the tag.

Configuration

There is no caching: NEON section; the extension is named cache and takes no options at all. Everything is plain services:

services:
	cache.storage: Nette\Caching\Storages\DevNullStorage       # disables caching, e.g. in tests
	cache.journal: MyJournal
	- ClassTwo( Nette\Caching\Cache(namespace: 'my-namespace') )   # to inject Cache directly

The aliases cacheStorage and nette.cacheJournal are gone in 4.0. Swapping in DevNullStorage does not disable the Latte or DI container caches – they do not use nette/caching.

Documentation

The full Nette documentation for this topic is bundled with the plugin. Read a page when you need details beyond this skill:

Nette Command-Line

composer require nette/command-line

Version 2.0, PHP 8.2 to 8.5, no dependencies. Four classes, each doing one thing: Command describes what the script accepts, Parser reads a command line against it, HelpRenderer draws the help from it, Console writes to the terminal.

Code written for 1.x does not run on 2.0, and some of it fails silently (new Parser($help) drops its arguments). To upgrade, follow the upgrade guide step by step.

Defining

use Nette\CommandLine\Command;
use Nette\CommandLine\Console;
use Nette\CommandLine\HelpRenderer;
use Nette\CommandLine\Normalizers;
use Nette\CommandLine\ParseException;
use Nette\CommandLine\Parser;

$command = new Command('convert', 'Converts files between formats.');
$command->addFlag('--help', 'Print this help', alias: '-h', standalone: true);
$command->addFlag('--verbose', 'Verbose output', alias: '-v');
$command->addOption('--output', 'Output file', alias: '-o', valueName: 'file');
$command->addOption('--jobs', 'Parallel jobs', normalizer: Normalizers::int(min: 1), default: 4);
$command->addArgument('input', 'File to convert');

$args = (new Parser)->parse($command);   // $_SERVER['argv'], or pass the tokens without the script name
  • The second positional argument of add*() is the description; everything else is named. addOption('--output', '-o') makes -o the description, not the alias.
  • There are no setters: a parameter is checked when added and cannot be changed. Definition mistakes (a name without a dash, a duplicate, a required argument with a default, an argument after a repeatable one) throw InvalidArgumentException at once.
  • addFlag() takes neither enum nor normalizer; those belong to options and arguments.

Reading the ParseResult

parse() returns a read-only ParseResult read like an array, keyed by the names as defined, dashes included: $args['--output'], $args['input']. A name that was never defined throws InvalidArgumentException, so a typo does not pass as a missing value; isset() is false for both an unknown name and null. Anything needing a real array (count(), array_*(), json_encode(), a parameter typed array) needs $args->toArray().

DefinitionAbsentGiven bareGiven with a value
flagnulltruerefused
negatable: true, default: truetruetrue, --no-x gives falserefused
optionnull or defaultthrows, value requiredthe string
valueOptional: truenull or defaulttrueonly as --x=value
argumentthrows unless optional: true–the string
  • An optional value is attached with =. --format xml is the option without a value followed by the argument xml – or, in a program with commands, Unknown command 'xml'. With enum: [...] the next token is taken when it is one of the allowed values.
  • default is what the parameter is worth when absent and is returned as given, never normalized nor checked against enum.
  • enum: Format::class (a backed enum) parses straight into the case.
  • repeatable: true collects an array, [] when absent. Without it the last value wins.
  • wasProvided('--x') tells a value equal to the default from the default itself; isEmpty() means nothing followed the script name.
  • A normalizer (Normalizers::int(), float(), realPath(), or any closure) runs only on values from the line. Its exception reaches you as a ParseException naming the parameter.

Standalone Flags and Commands

A standalone: true flag answers on its own: the parser returns it as true, the other flags as given and every other parameter at its default, checking or converting nothing and without requiring a missing argument or command. An unknown option is still refused.

$cli = new Command('tool');
$cli->addFlag('--help', alias: '-h', standalone: true);
$check = $cli->addCommand('check', 'Report violations');
$check->addArgument('paths', optional: true, repeatable: true);

$result = (new Parser)->parse($cli);
if ($result['--help']) {
	(new HelpRenderer)->render($result->command);   // the help of the command the user asked about
	exit(0);
}

exit(match ($result->command) {
	$check => $app->check($result['paths']),
	$cli => $app->usage(),
});

$result->command is the Command object selected by the first positional word, the program itself when there is none (new Command(..., commandRequired: true) refuses that). A command accepts its own options and those of the commands above it. match without a default arm throws when a command is left unhandled.

Errors and Help

try {
	$result = (new Parser)->parse($cli);
} catch (ParseException $e) {
	$stderr = new Console(STDERR);
	$stderr->writeLine("Error: {$e->getMessage()}", 'red');
	(new HelpRenderer($stderr))->render($e->command);
	exit(2);
}

$e->reason is a ParseFailure case (UnknownOption, MissingArgument, ...), $e->parameter the parameter concerned and $e->token the part of the line as given. The help is generated from the definition; addSection() and addText() add headings and paragraphs, hidden: true, valueName: and defaultDescription: shape it. renderToString() returns it, new HelpRenderer(width: 100) fixes the width.

Console

  • $console->color('red', $text): the color comes first. An unknown color name throws even with colors off; null means no color. Colors are 'fg' or 'fg/bg' from black, gray, silver, white, navy, blue, green, lime, teal, aqua, maroon, red, purple, fuchsia, olive, yellow, drawn in the colors of the terminal theme; a color independent of the theme is '#87D7FF', '#8DF' or a palette number such as '117'.
  • One console per stream: new Console(STDOUT) and new Console(STDERR) decide colors each for itself. How many is a ColorDepth (None, Ansi16, Ansi256, TrueColor), detected from the stream, NO_COLOR, FORCE_COLOR and COLORTERM; new Console(STDOUT, colorDepth: ColorDepth::None) or setColorDepth(ColorDepth::None) (a --no-color option) wins over all of them. There is no useColors().
  • Gate colors on hasColors(), and progress bars or prompts on isTerminal() – colors may be off at a real terminal.
  • $console->link($url, $text) makes a clickable link; in a pipe or without colors the URL follows the text in parentheses.
  • setStatus($lines) draws one line or a list of them in place; the next output erases them and the next setStatus() redraws them below; clearStatus() at the end. It does nothing when the stream is not a terminal.
  • Measure with Ansi::measure(), Ansi::pad(), Ansi::truncate($s, $width, keepEnd: true), never strlen(); Ansi::strip() removes foreign escape sequences.

Documentation

The full Nette documentation for this topic is bundled with the plugin. Read a page when you need details beyond this skill:

Nette Components, Signals and Snippets

A component is a descendant of Nette\Application\UI\Control, and the presenter is itself a Control (ComponentModel\Component -> Container -> UI\Component -> UI\Control -> UI\Presenter), so everything below applies to both. Related skills: nette-forms (controls, validation, onSuccess), nette-architecture (where components live), latte-templates ({control}/{snippet} syntax), nette-configuration (generated factories), frontend-development (Naja on the JS side).

Component Factories

Any container (presenter or control) creates children lazily through createComponent<Name>():

protected function createComponentPoll(): PollControl
{
	return new PollControl($this->items);
}

The factory is never called directly. It fires on first access – $this->getComponent('poll') or the equivalent $this['poll'] (the ComponentModel\ArrayAccess trait), which is what {control poll} does. An untouched component is never built.

  • The name starts with a lowercase letter. Container::createComponent() requires ucfirst($name) !== $name, so asking for Poll never reaches createComponentPoll().
  • The factory receives the name as its first argument, and may either return the component or add it itself with addComponent(); doing neither throws Nette\UnexpectedValueException.
  • Names match #^[a-zA-Z0-9_]+$#D – no hyphen in a name, - is the tree separator: $this['cart-form'] means "child form of child cart", nesting to any depth.
  • Not presenter-only: a Control defines createComponent<Name>() for its own children the same way.
  • For components with dependencies, inject a factory (a class or a DI-generated interface) and call it from createComponent<Name>() – see nette-configuration for implement:.

Signals

A signal performs an action on the current page. It calls handle<Signal>() on the component addressed by the do query parameter (?do=cart-remove); matching is case-insensitive.

public function handleDelete(int $id): void   // ?do=delete&id=…
{
	$this->facade->delete($id);
	$this->redirect('this');
}

Where signals run – after the action phase and canonicalization, before any render method, not "in the action phase" (the full lifecycle order is in nette-architecture). Consequence: a handler can prepare data that render<View>() then respects (if (!isset($this->template->articles)) …).

  • A signal cannot target another presenter or action; it re-runs the current request plus the handler. A missing handler throws BadSignalException (403 page).
  • Signal parameters come from the URL and from the POST body, but a URL parameter of the same name wins. They share one namespace with action and persistent parameters.
  • A form submit is not a signal. UI\Form::signalReceived() accepts only the signal submit and turns it into onSubmit/onSuccess; any other signal name on a form throws BadSignalException. Never write handleSubmit() for a form – put the logic in an onSuccess handler (see nette-forms).

Links Inside a Component

In a component template, n:href, {link} and $this->link()/$this->redirect() always mean a signal of that component, with or without ! – LinkGenerator switches to signal mode as soon as the link source is not a Presenter.

{* inside a component template *}
<a n:href="click!">signal</a>          {* the ! is optional here *}
<a n:href="subcomponent:click!">signal of a child</a>
<a href={plink Home:default}>presenter link</a>

{plink} = presenter link: it compiles to $this->global->uiPresenter->link(...), where {link} and n:href compile to $this->global->uiControl->link(...). It is not "absolute" and not "persistent" – an absolute URL comes from the // prefix, which works with {link} too. In PHP the equivalent is $this->getPresenter()->link('Home:default').

The only non-signal destination inside a component is 'this' (current presenter + action): $this->redirect('this'). Arguments cannot be passed to this!.

Persistent Parameters

A persistent parameter survives across requests in the URL, automatically, including links generated by other components on the page.

use Nette\Application\Attributes\Persistent;

class ItemList extends Control
{
	#[Persistent]
	public int $page = 1;   // must be public, non-static, typed
}

loadState() writes the URL value into the property and answers a type mismatch with a 404 – override it for range checks; saveState() is the reverse direction. In links, <a n:href="this page: $page + 1"> changes the value and page: null resets it to the default (drops it from the URL).

Persistent components use the same attribute on the presenter class, listing component names; their persistent parameters then survive across actions and presenters, subcomponents included:

#[Persistent('calendar', 'poll')]
class DefaultPresenter extends Nette\Application\UI\Presenter
{
}

The annotation form /** @persistent */ still works but triggers E_USER_DEPRECATED – always use the attribute.

AJAX and Snippets

public function handleLike(int $id): void
{
	$this->service->like($id);
	if ($this->isAjax()) {
		$this->redrawControl('articles');   // NOT invalidateControl()
	} else {
		$this->redirect('this');
	}
}
  • The method is redrawControl(?string $snippet = null, bool $redraw = true). invalidateControl() does not exist any more – calling it dies with Nette\MemberAccessException. Pass redraw: false to cancel a pending invalidation. No argument invalidates the whole control.
  • If nothing is invalidated, an AJAX request returns the whole page instead of snippets; isControlInvalid() is what the presenter checks, and it walks into child controls.
  • redirect() during AJAX does not send a 302. It writes the URL into payload.redirect and sends the JSON payload; the browser side (Naja) performs the redirect. Therefore a handler that redirects ends the request – redraw or redirect, not both.
  • Extra data for the client goes into the payload: $this->payload->message = 'ok';. The snippet's HTML id is snippet-<uniqueId>-<name> (getSnippetId()).

A snippet redraw calls render() with no arguments – Nette re-renders an invalidated child with a plain $child->render(), so parameterized rendering is incompatible with snippets. Pass such values through the factory, a setter or a persistent parameter instead.

{control productGrid}                  {* OK *}
{control productGrid $arg}             {* breaks on AJAX redraw *}
{control productGrid:paginator}        {* breaks on AJAX redraw *}

Dynamic snippets (a variable in the name) must sit inside a static {snippet} or {snippetArea}, otherwise you get E_USER_WARNING: Dynamic snippets are allowed only inside static snippet/snippetArea. Invalidate the wrapper – invalidating item-5 alone redraws nothing, because that name only exists once the surrounding loop runs.

<ul n:snippetArea="itemsContainer">
	{foreach $items as $id => $item}
		<li n:snippet="item-{$id}">{$item}</li>
	{/foreach}
</ul>
$this->redrawControl('itemsContainer');

A redrawn area still renders every item and throws the rest away, so narrow the data in the handler ($this->template->items = [$one]). The dynamic-snippet-free alternative is one Control per row plus Multiplier, where only the affected instance renders.

The Component Tree

$this->getComponents();      // immediate children only, array, NO arguments
$this->getComponentTree();   // all descendants, depth-first, list
array_filter($this->getComponentTree(), fn($c) => $c instanceof Control);
  • getComponents() takes no arguments. The old $deep/$filterType arguments left the signature in 3.1 and throw Nette\DeprecatedException in 4.0, so getComponents(true) or getComponents(recursive: true) is always wrong. getComponentTree() has existed since 3.1 – it is not a new 4.0 API.
  • monitor($type, $attached, $detached) reacts to (de)attachment; the overridable attached() / detached() methods were removed in 4.0, and monitor() with no handler throws InvalidStateException. In 4.0 attach callbacks fire top-down, detach callbacks bottom-up.
  • lookup($type) returns the nearest ancestor of that type, lookupPath($type) the --joined path from it – the basis of getUniqueId() and of the do parameter.
  • A component has no presenter in its constructor: no links, no persistent parameter values there. Use $onAnchor[] (or monitor(Presenter::class, ...)) for setup that needs the presenter.
  • ComponentModel\Component dropped the SmartObject trait in 4.0 (UI\Component still adds it).

Multiplier

Creates a variable number of children on demand; the callback gets the child name and the multiplier.

protected function createComponentLikeControl(): Multiplier
{
	return new Multiplier(fn(string $articleId) => new LikeControl($this->articles->get($articleId)));
}
{control "likeControl-$article->id"}

Documentation

The full Nette documentation for this topic is bundled with the plugin. Read a page when you need details beyond this skill:

Nette DI & Services Guidelines

  • Primary services: services.neon – all service definitions
  • Framework config: common.neon – parameters, extensions, framework settings, includes
  • Project scaling: Create additional files for larger projects (api.neon, tasks.neon)
  • Environment-specific settings: env.local.neon for development, env.prod.neon for production

Config File Includes

common.neon includes other files. Later files override earlier ones, so environment-specific files go last:

includes:
	- services.neon
	- env.local.neon   # Gitignored, overrides for local dev

Extensions

Register DI extensions for third-party packages or custom container builders:

extensions:
	console: Contributte\Console\DI\ConsoleExtension
	translation: Contributte\Translation\DI\TranslationExtension

Service Definition Syntax

Use - for services that don't need references. Nette DI automatically resolves all constructor dependencies by type, so most services need just their class name:

services:
	- App\Model\BlogFacade
	- App\Model\CustomerService
	- App\Presentation\Accessory\TemplateFilters

Give names only when needed for @serviceName references elsewhere in NEON. Unnecessary names add clutter and create a maintenance burden when classes are renamed:

services:
	# Named because referenced as @pohoda
	pohoda:
		create: Nette\Database\Connection('odbc:Driver={...}')
		autowired: false

	# Using the reference
	- App\Model\PohodaImporter(pohoda: @pohoda)

When manually specifying arguments, pass them by name; only a single argument that is the constructor's first may stay positional. Positional arguments break when the constructor signature changes:

services:
	# Good - first parameter, clear order
	- App\Model\ImageService(%rootDir%/storage)

	# Good - named parameter when mixing with autowiring
	- App\Model\CustomerService(ip: %ip%)
	- App\Model\BlogFacade(blogPath: %blog%)
Factory Method Services
services:
	- App\Core\RouterFactory::createRouter
	- Symfony\Component\HttpClient\HttpClient::create()
Complex Service Configuration
services:
	- App\Model\MailImporter(
		DG\Imap\Mailbox(
			mailbox: %imap.mailbox%
			username: %imap.username%
			password: %imap.password%
		)
		debugMode: %debugMode%
	)
Setup Methods
services:
	database:
		create: PDO(%dsn%, %user%, %password%)
		setup:
			- setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION)
Overriding Services by Type

When you need to alter an existing service (e.g. replace a framework service with your own implementation), you can refer to it by type using @ClassName: instead of guessing internal service names. The alteration: true is implicit:

services:
	# Override the framework's Application with a custom one
	@Nette\Application\Application:
		create: MyApplication
Disabled Autowiring

Use autowired: false when you have multiple services of the same type and need to prevent ambiguity (e.g. two database connections):

services:
	specialDb:
		create: Nette\Database\Connection(...)
		autowired: false  # Must reference explicitly via @specialDb

Automatic Service Registration

Use search section to avoid manually registering services that follow naming conventions. This keeps services.neon short and ensures new services are picked up automatically:

search:
	model:
		in: %appDir%
		classes:          # Classes ending with Factory, Facade, or Service
			- *Factory
			- *Facade
			- *Service

Generated Factories and Accessors

Instead of injecting the container or writing factory boilerplate, declare an interface and let DI generate the implementation. The interface must have exactly one method named create with a declared return type:

interface ArticleFactory
{
	function create(int $authorId): Article;
}
services:
	- ArticleFactory        # short form: implement: is inferred from the interface

Parameters of create() are matched to the constructor by name, so $authorId above lands in Article::__construct(int $authorId). The long form adds fixed arguments or setup:

services:
	articleFactory:
		implement: ArticleFactory
		arguments:
			authorId: 123        # create() does not take it, the constructor does
		setup:
			- setAuthorId($authorId)   # create() takes it, a setter consumes it

An accessor is the lazy variant – one get() method returning an existing service, so the service is only created on first get():

interface DatabaseAccessor
{
	function get(): Database;
}

This is the mechanism behind component factories in presenters, so use it instead of passing the container around.

Decorator Section

Apply configuration to all services of a specific type without listing them individually. Useful for injecting common dependencies or calling setup methods on multiple services:

decorator:
	App\Presentation\BasePresenter:
		setup:
			- setTranslator

Parameter Usage

Reference configuration parameters with %parameterName%. Parameters are defined in the parameters section of common.neon and can be overridden per environment:

services:
	- App\Model\TexyProcessor('', %wwwDir%, %tempDir%/texy)
	- App\Tasks\ImportTask(path: %rootDir%/../data/import)
	- App\Model\CustomerService(ip: %ip%)

Passing Settings to Services and Presenters

Via service arguments (recommended) – explicit, type-safe, visible in constructor:

# config/services.neon
services:
	- App\Presentation\Admin\Product\ProductPresenter(itemsPerPage: 20)
class ProductPresenter extends BasePresenter
{
	public function __construct(
		private int $itemsPerPage,
		private ProductFacade $facade,
	) {}
}

Via parameters – useful when the same value is used in multiple places:

# config/common.neon
parameters:
	pagination:
		itemsPerPage: 20
		maxItems: 1000
# config/services.neon
services:
	- App\Presentation\Admin\Product\ProductPresenter(
		itemsPerPage: %pagination.itemsPerPage%
	)

Core Framework Configuration

Add sections to common.neon only when you need specific functionality.

Application Layer

Add when: Setting up error handling or custom URL mapping

application:
	mapping: App\Presentation\*\**Presenter
	errorPresenter:
		4xx: Error:Error4xx     # When you have custom error pages
		5xx: Error:Error5xx
	aliases:                    # When you have frequently used links in n:href or $presenter->link()
		home: 'Front:Home:'
		admin: 'Admin:Dashboard:'
HTTP and Session

Add when: You need custom cookie settings, proxy support, or session configuration

http:
	proxy: 10.0.0.0/8      # When behind a reverse proxy

session:
	expiration: 14 days
	cookieSamesite: Lax
Authentication

Add when: You need simple file-based authentication for development or prototyping. For production, implement a custom authenticator class instead.

security:
	users:                     # Development only - NOT for production
		username: password

What Needs Registering

Only classes that need injection or are injected elsewhere. Presenters are registered automatically (Nette scans them by IPresenter); component factory interfaces are not: list them in services:, or let a search: section find them (it picks up interfaces with a single create() or get() method).

Secrets

Credentials do not belong in committed config files, but where they live is the project's decision. Follow the convention the project already has; when it has none, offer the user the options instead of picking one:

  • a gitignored NEON file holding them as parameters (secrets.neon, or one file per environment such as env.local.neon), included from common.neon and referenced as %dbPassword%
  • environment variables, exposed in Bootstrap by $this->configurator->addDynamicParameters(['env' => getenv()]) and referenced as %env.DB_PASSWORD%; as dynamic parameters they are read at runtime, not frozen into the compiled container

Documentation

The full Nette documentation for this topic is bundled with the plugin. Read a page when you need details beyond this skill:

Database

Uses Nette Database, typically with MySQL, PostgreSQL or SQLite as the backend.

composer require nette/database

See the Explorer documentation for the full ActiveRow/Selection API. See the SQL way documentation for direct SQL queries.

Database Conventions

  • Table names use singular form (e.g., user not users)
  • Use TINYINT(1) for booleans
  • Use id for primary keys
  • Character encoding: utf8mb4 with appropriate collation (e.g. utf8mb4_0900_ai_ci, or utf8mb4_cs_0900_ai_ci for Czech)
  • Standard timestamp fields:
    • created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    • never use TIMESTAMP for date/time fields

Entity Mapping

Nette Database has a built-in EntityMapping interface (since 3.2) that the Explorer uses to resolve an ActiveRow subclass for each table and (optionally) translate between column names and PHP property names. The default implementation (DefaultEntityMapping) supports:

  • Table-to-class map with wildcards. Keys may be exact names (special_table), wildcard patterns (forum_*) or a bare * catch-all. Class names may contain *, which is replaced with the PascalCase of the captured portion: forum_post + App\Forum\*Row → App\Forum\PostRow. A class without * is a fixed class (log_*: App\Logging\LogRow maps every log_* table to the same LogRow). Schema prefixes like public. are stripped before PascalCase conversion. Exact keys take precedence; wildcard entries are tried in declaration order, so put more specific patterns first and the bare * last.
  • camelCase column ↔ property translation — when enabled, column author_id is exposed as property authorId everywhere: property access, iteration, toArray(), insert(), update(), and column references in where() / order().

Activate via the mapping config option (see Database Configuration below).

Entity Design Strategy

All entities in App\Entity with consistent Row suffix (matches the App\Entity\*Row convention):

  • product table → ProductRow
  • order_item table → OrderItemRow
  • variant_expiration table → VariantExpirationRow

Why flat: Entities are data structures that cross domain boundaries. A ProductRow might be used in catalog, orders, inventory, and reporting contexts. Subdividing entities by domain forces you to either pick one arbitrary "home" domain or duplicate references.

Entity Organization

All entities in single App\Entity namespace - avoid domain subdivision:

app/Entity/
├── ProductRow.php          ← Core business entities
├── OrderItemRow.php        ← Relationship entities
└── StockTransferRow.php    ← Operational entities
Entity Documentation Patterns
use Nette\Database\Table;

/**
 * @property-read int $id
 * @property-read string $title
 * @property-read bool $active
 * @property-read ?CategoryRow $category        ← nullable relationship
 * @property-read UserRow $author               ← required relationship
 */
final class ProductRow extends Table\ActiveRow
{
}

Documentation rules:

  1. Document ALL accessible properties (including inherited id)
  2. Use nullable types for optional foreign keys
  3. Include relationship properties for IDE navigation
  4. Match database schema exactly
Entity Relationships in phpDoc

Foreign key patterns:

  • @property-read ?CategoryRow $category for optional relationships
  • @property-read UserRow $author for required relationships
  • @property-read Selection<OrderItemRow> $order_items for back-references

Naming convention: Follow Nette Database relationship naming (foreign key without _id suffix).

With camelCase: true mapping: scalar columns map to camelCase properties ($firstName, $createdAt). Relationship property names ($author, $category) are resolved by Conventions against database columns, so they aren't affected by the camelCase setting.

When to Use Selection API

Use for:

  • Simple filtering and sorting
  • Standard CRUD operations
  • Queries that benefit from lazy loading
  • When you need to chain conditions dynamically
return $this->db->table('product')
	->where('active', true)
	->where('category_id', $categoryId)
	->order('name');

When to Use Raw SQL

Use for:

  • Complex analytics and reporting
  • Recursive queries (WITH RECURSIVE)
  • Performance-critical queries
  • Complex joins that are awkward in Selection API
return $this->db->query('
	WITH RECURSIVE category_tree AS (...)
	SELECT ...
', $params)->fetchAll();

Query Building Patterns

Build queries by progressive refinement – start with a base method, then add conditions. Always use generic types for Selection returns:

/** @return Selection<ProductRow> */
public function getProducts(): Selection
{
	return $this->db->table('product');
}

/** @return Selection<ProductRow> */
public function getActiveProducts(): Selection
{
	return $this->getProducts()->where('active', true);
}

/** @return Selection<ProductRow> */
public function getProductsInCategory(int $categoryId): Selection
{
	return $this->getActiveProducts()
		->where(':product_category.category_id', $categoryId);
}

Relationship Navigation

Use colon notation for efficient joins:

// Forward relationship (via foreign key)
->where('category.slug', $categorySlug)

// Back-reference (reverse relationship)
->where(':order_item.quantity >', 1)

// Deep relationships
->where('category.parent.name', 'Root Category')

Traps in where() and SQL Fragments

The array KEY is SQL, the value is a bound parameter. where() splits the key on the first space into a column and an operator and emits both into the query, so a key built from user input is an injection hole – and mass-assigning a request array into where() or insert() lets the client choose columns and operators:

$db->table('user')->where(['id >' => 5]);        // fine: key is yours, value is bound
$db->table('user')->where($_GET['filter']);      // NEVER: keys come from the client

Write SQL keywords in UPPERCASE inside fragments. Explorer quotes lowercase words as identifiers, so where('name like ?', $x) compiles to `name` `like` ? and fails; uppercase words are left alone:

->where('name LIKE ?', "%$q%")      // correct
->where('name like ?', "%$q%")      // `like` gets quoted as a column name

An empty array flips the meaning of a condition. where('id', []) becomes IS NULL AND FALSE (matches nothing), while where('id NOT', []) becomes IS NULL OR TRUE (matches everything). Guard empty filter lists explicitly. Mixing operators without parentheses raises Possible SQL query corruption. Add parentheses around operators.

Fetching Strategies by Use Case

Single optional result: ->fetch() All results as array: ->fetchAll() Key-value pairs: ->fetchPairs('key_column', 'value_column') Single scalar value: ->fetchField() (first column of first row) Count only: ->count('*')

Structured data with fetchAssoc:

// Key by column value
$byId = $db->table('product')->fetchAssoc('id');
// [1 => ProductRow, 2 => ProductRow, ...]

// Group by column
$byCategory = $db->table('product')->fetchAssoc('category_id[]');
// [5 => [ProductRow, ProductRow], 8 => [ProductRow, ...]]

// Nested grouping
$nested = $db->table('product')->fetchAssoc('category_id|active');
// [5 => [true => ProductRow, false => ProductRow], ...]

The path string uses [] for array grouping, | for nested keys, and = to extract a single value.

Schema and Constraints

Use direct SQL migrations rather than ORM-style migrations – store schema in sql/db.sql with manual migration scripts. Rely on database constraints (foreign keys, unique, check) for data integrity and handle constraint violations in services with meaningful business exceptions.

Transactions

Wrap multi-step writes in transactions to ensure consistency:

$this->db->transaction(function () use ($data, $items) {
	$order = $this->db->table('order')->insert($data);
	foreach ($items as $item) {
		$order->related('order_item')->insert($item);
	}
});

The callback approach automatically commits on success and rolls back on exception, and it returns whatever the callback returns, so you can produce a value out of it.

Nested transaction() calls are counted, and only the outermost one actually commits. Calling beginTransaction(), commit() or rollBack() manually inside the callback throws LogicException – pick one style per code path and stay with it.

Anti-Patterns to Avoid

Don't create separate Repository classes – in Nette, services combine data access with business logic. A separate repository layer adds indirection without benefit because Nette Database Explorer already provides a clean query API. The service IS the repository.

Error Handling

Transform database errors to business exceptions:

try {
	$customer->update(['email' => $newEmail]);
} catch (Nette\Database\UniqueConstraintViolationException) {
	throw new EmailAlreadyExistsException();
}

Handle at service boundary – presenters should receive business exceptions, not database exceptions. This keeps the UI layer independent of the storage layer and produces meaningful error messages.

Database Configuration

database:
	dsn: 'mysql:host=127.0.0.1;dbname=myapp'
	user: root
	password: secret

	# Entity mapping (table → ActiveRow subclass, optional column ↔ property)
	mapping:
		tables: App\Entity\*Row    # string shortcut: equivalent to { '*': 'App\Entity\*Row' }

	options:
		lazy: true              # Connect on first query
		charset: utf8mb4        # Default
		convertBoolean: true    # TINYINT(1) to bool
		newDateTime: true       # Return DateTimeImmutable

Full mapping form when you need explicit overrides or camelCase properties:

database:
	dsn: 'mysql:host=127.0.0.1;dbname=myapp'
	mapping:
		tables:
			special_table: App\Entity\SpecialRow    # exact match wins over wildcards
			forum_*: App\Forum\*Row                 # wildcard in key (* captured as PascalCase)
			"*": App\Entity\*Row                    # catch-all fallback (must be last)
		camelCase: true         # column author_id ↔ property authorId

Multiple connections:

database:
	main:
		dsn: 'mysql:host=127.0.0.1;dbname=app'
		user: root
		password: secret

	logs:
		dsn: 'mysql:host=127.0.0.1;dbname=logs'
		user: logs
		password: secret
		autowired: false  # Must reference explicitly

Reference non-autowired connection:

services:
	- LogService(@database.logs.connection)

Documentation

The full Nette documentation for this topic is bundled with the plugin. Read a page when you need details beyond this skill:

Nette Forms

Nette Forms provides secure, reusable forms with automatic validation on both client and server side.

composer require nette/forms

Forms in Presenters

Use Nette\Application\UI\Form, not Nette\Forms\Form. The former extends the latter and adds SignalReceiver, so it can pick up the submit signal and reach the presenter; Nette\Forms\Form is the standalone variant and will not receive submitted data as a presenter component.

Forms are created in factory methods named createComponent<Name>:

protected function createComponentRegistrationForm(): Form
{
	$form = new Form;
	$form->addText('name', 'Name:')
		->setRequired('Please enter your name.');

	$form->addEmail('email', 'Email:')
		->setRequired('Please enter your email.');

	$form->addPassword('password', 'Password:')
		->setRequired('Please enter password.')
		->addRule($form::MinLength, 'Password must be at least %d characters', 8);

	$form->addSubmit('send', 'Register');

	$form->onSuccess[] = $this->registrationFormSucceeded(...);
	return $form;
}

private function registrationFormSucceeded(Form $form, \stdClass $data): void
{
	// $data->name, $data->email, $data->password
	$this->flashMessage('Registration successful.');
	$this->redirect('Home:');
}

Render in template:

{control registrationForm}

Create and Edit Pattern

Unified form for both creating and editing records:

class ProductPresenter extends BasePresenter
{
	public function __construct(
		private ProductFacade $facade,
	) {}

	public function actionEdit(?int $id = null): void
	{
		if ($id) {
			$product = $this->facade->getProduct($id);
			$this->template->product = $product;
			$this['productForm']->setDefaults($product->toArray());
		}
	}

	protected function createComponentProductForm(): Form
	{
		$form = new Form;
		$form->addText('name', 'Name:')
			->setRequired();
		$form->addTextArea('description', 'Description:');
		$form->addInteger('price', 'Price:')
			->setRequired()
			->addRule($form::Min, 'Price must be positive', 1);
		$form->addSubmit('send', 'Save');
		$form->onSuccess[] = $this->productFormSucceeded(...);
		return $form;
	}

	private function productFormSucceeded(Form $form, \stdClass $data): void
	{
		$id = $this->getParameter('id');
		if ($id) {
			$this->facade->update($id, (array) $data);
			$this->flashMessage('Product updated.');
		} else {
			$this->facade->create((array) $data);
			$this->flashMessage('Product created.');
		}
		$this->redirect('default');
	}
}

Template:

{block content}
<h1>{if $product}Edit: {$product->name}{else}New Product{/if}</h1>

{form productForm}
	<table>
		<tr><td>{label name}{input name}</td></tr>
		<tr><td>{label description}{input description}</td></tr>
		<tr><td>{label price}{input price}</td></tr>
	</table>
	{input send}
{/form}
{/block}

Defaults are set in actionEdit() via $form->setDefaults() – never set defaults in the template.

Form Reuse with Factory

A common base FormFactory creates Form instances with shared configuration (CSRF, renderer, translation). Changing it in one place affects all forms in the application – no need to hunt through individual presenters:

final class FormFactory
{
	public function create(): Form
	{
		$form = new Form;
		// Shared setup for all forms: renderer, translator, default classes, etc.
		return $form;
	}
}

CSRF protection is built in and needs no hidden token. A form that must accept a cross-origin POST calls $form->allowCrossOrigin(); there is no setCrossOrigin().

For specific forms used in multiple places, create a dedicated factory:

final class ProductFormFactory
{
	public function __construct(
		private FormFactory $formFactory,
	) {}

	public function create(callable $onSuccess): Form
	{
		$form = $this->formFactory->create();
		$form->addText('name', 'Name:')
			->setRequired();
		$form->addTextArea('description', 'Description:');
		$form->addInteger('price', 'Price:')
			->setRequired();
		$form->addSubmit('send');
		$form->onSuccess[] = function (Form $form, \stdClass $data) use ($onSuccess) {
			$onSuccess($data);
		};
		return $form;
	}
}

Use in presenter:

public function __construct(
	private ProductFormFactory $productFormFactory,
) {}

protected function createComponentProductForm(): Form
{
	return $this->productFormFactory->create(
		function (\stdClass $data): void {
			$this->facade->save($data);
			$this->redirect('default');
		},
	);
}

Common Form Controls

MethodCreates
addText($name, $label)Text input
addPassword($name, $label)Password input
addTextArea($name, $label)Multi-line text
addEmail($name, $label)Email with validation
addInteger($name, $label)Integer input
addFloat($name, $label)Decimal input
addCheckbox($name, $caption)Checkbox
addCheckboxList($name, $label, $items)Multiple checkboxes
addRadioList($name, $label, $items)Radio buttons
addSelect($name, $label, $items)Dropdown
addMultiSelect($name, $label, $items)Multi-select
addUpload($name, $label)File upload
addMultiUpload($name, $label)Multiple files
addDate($name, $label)Date picker
addTime($name, $label)Time picker
addDateTime($name, $label)Combined date+time picker
addHidden($name)Hidden field
addSubmit($name, $caption)Submit button
addButton($name, $caption)Button

See the complete control reference for all form controls.

Basic Validation

$form->addText('name')
	->setRequired('Name is required.')
	->addRule($form::MinLength, 'At least %d characters', 3)
	->addRule($form::MaxLength, 'Maximum %d characters', 100);

$form->addEmail('email')
	->setRequired()
	->addRule($form::Email, 'Invalid email format.');

$form->addInteger('age')
	->addRule($form::Range, 'Age must be between %d and %d', [18, 120]);

$form->addPassword('password')
	->setRequired()
	->addRule($form::MinLength, 'At least %d characters', 8);

$form->addPassword('password2')
	->setRequired()
	->addRule($form::Equal, 'Passwords must match', $form['password']);

Mark every required field with setRequired(). Rules added by addRule() run only when the control is filled, so an empty field passes them all and its empty value reaches onSuccess.

See the complete validation reference for all rules and conditions.

Conditional Validation

$form->addCheckbox('newsletter', 'Subscribe to newsletter');

$form->addEmail('email')
	->addConditionOn($form['newsletter'], $form::Equal, true)
		->setRequired('Email required for newsletter.');

Form Rendering

Default rendering:

{control productForm}

Manual rendering:

{form productForm}
<table>
	<tr>
		<th>{label name /}</th>
		<td>{input name} {inputError name}</td>
	</tr>
	<tr>
		<th>{label email /}</th>
		<td>{input email} {inputError email}</td>
	</tr>
</table>
{input send}
{/form}

With Bootstrap:

{form productForm, class => 'form-horizontal'}
<div class="mb-3">
	{label name class => 'form-label' /}
	{input name class => 'form-control'}
	{inputError name class => 'invalid-feedback'}
</div>
{/form}

See the complete rendering reference for all rendering options.

Form Events

// Before rendering (modify form)
$form->onRender[] = function (Form $form): void {
	// Add CSS classes, modify controls
};

// After successful validation
$form->onSuccess[] = function (Form $form, \stdClass $data): void {
	// Process valid data
};

// After any submission (valid or invalid)
$form->onSubmit[] = function (Form $form): void {
	// Logging, analytics
};

// Cross-field validation. Runs even when rules FAILED, so read values with
// getUntrustedValues() – getValues() here warns and returns unvalidated data.
$form->onValidate[] = function (Form $form): void {
	if ($this->isBlocked($form->getUntrustedValues()->email)) {
		$form->addError('This email is blocked.');
	}
};

Error Handling

private function productFormSucceeded(Form $form, \stdClass $data): void
{
	try {
		$this->facade->save($data);
	} catch (DuplicateEntryException) {
		$form['email']->addError('Email already exists.');
		return;
	}
	$this->redirect('default');
}

redirect() works by throwing AbortException (a \LogicException), so keep it outside the try: a catch-all \Exception there would swallow the redirect.

Documentation

The full Nette documentation for this topic is bundled with the plugin. Read a page when you need details beyond this skill:

Nette Http

Installed with composer require nette/http. The framework registers http.request (Nette\Http\Request), http.response (Nette\Http\Response), http.requestFactory and session.session (Nette\Http\Session). All autowired – inject Nette\Http\IRequest / Nette\Http\IResponse / Nette\Http\Session by type; in presenters use $this->getHttpRequest(), $this->getHttpResponse(), $this->getSession() / $this->getSession('sectionName').

Request – read-only, already sanitized

Nette\Http\Request is immutable; RequestFactory::fromGlobals() strips control characters and invalid UTF-8 from GET/POST/COOKIE and the URL.

$url = $httpRequest->getUrl();          // UrlScript, not a string
$httpRequest->getQuery();               // all GET params; getQuery('id') for one (null if missing)
$httpRequest->getPost('name');          // POST param or null
$httpRequest->getCookie('lang');        // ?string; getCookies() for all
$httpRequest->getHeader('User-Agent');  // ?string, case-insensitive; getHeaders() keys are lowercase
$httpRequest->isSecured();              // HTTPS?
$httpRequest->isAjax();                 // X-Requested-With: XMLHttpRequest
$httpRequest->getRemoteAddress();       // ?string
$httpRequest->getBasicCredentials();    // ?array – since 3.2 NOT in $url->getUser()/getPassword()

getRemoteAddress() and isSecured() are wrong behind a reverse proxy until you list the proxy, otherwise you get the load balancer's IP and http for a TLS-terminated request:

http:
	proxy: 127.0.0.1        # IP, CIDR range, or a list of them
	forceHttps: true        # 3.3.4+; proxy does not send X-Forwarded-Proto at all

getReferer() and getRemoteHost() are deprecated (getRemoteHost() always returns null). Use getOrigin(): ?UrlImmutable – scheme+host+port from the Origin header, absent for plain navigation and same-origin GET.

File uploads – always index with getFile(), never walk the getFiles() tree, because the client controls its shape:

$file = $httpRequest->getFile(['my-form', 'details', 'avatar']); // ?FileUpload
if ($file?->hasFile()) {
	$file->getUntrustedName();   // as sent by the user – never use as a path
	$file->getSanitizedName();   // safe filename
	$file->move($dest);
}

getFile() returns null when the field was submitted empty (UPLOAD_ERR_NO_FILE), so always use ?->. It is the form control that hands you a dummy object instead: UploadControl returns a FileUpload carrying that error unless setNullable() is on — that is where hasFile() (did the user pick a file?) and isOk() (did it arrive intact?) differ.

Response – mutable, but only before output

Every setter throws Nette\InvalidStateException once headers are out; isSent() tells you. setHeader() replaces (and null deletes), addHeader() appends another line of the same name.

$httpResponse->setCode(IResponse::S404_NotFound);
$httpResponse->setExpiration('1 hour');   // Cache-Control + Expires; null = no cache at all
$httpResponse->sendAsFile('invoice.pdf');
$httpResponse->redirect($url);            // does NOT terminate the script

In a presenter use $this->redirect() / $this->getHttpResponse()->redirect(); $this->terminate(); – Response::redirect() only sets Location and echoes a fallback link.

$httpResponse->setCookie('lang', 'en', '100 days');  // expiration: interval string, date, or null = session cookie
$httpResponse->setCookie('t', 'dark', '1 year', sameSite: SameSite::None, partitioned: true);
$httpResponse->deleteCookie('lang');

SameSite is now the enum Nette\Http\SameSite (Lax/Strict/None); the IResponse::SameSiteLax constants are deprecated. Defaults: sameSite = Lax, httpOnly = true, secure from http: cookieSecure (auto). SameSite=None and partitioned force Secure on regardless of what you pass. Passing an absolute UNIX timestamp as $expire is deprecated – a number means relative seconds; a session cookie is null, not 0.

Sessions

Never call session_start(), $_SESSION or session_regenerate_id() yourself – Nette configures the hardening ini directives (use_only_cookies, use_strict_mode, cookie_httponly, no trans-sid), namespaces data under $_SESSION['__NF'], and expires per-section/per-variable metadata at start. A hand-started session bypasses all of it.

The session starts lazily on the first read or write (autoStart: smart). Start it explicitly with $session->start() if you know you need it and output may already be flowing.

$section = $session->getSection('cart');   // SessionSection; $this->getSession('cart') in a presenter
$section->set('items', $items);
$section->set('flash', $msg, '30 seconds');  // 3rd arg = per-variable expiration
$section->get('items');                      // null when missing
$section->remove('items');                   // no argument = drop the whole section
$section->setExpiration('20 minutes');       // whole section; ($expire, $variables) for selected keys
$section->removeExpiration('flash');
  • set($name, null) is a remove, not a write of null.
  • get() takes exactly one argument – get('key', $default) throws ArgumentCountError. Use $section->get('key') ?? $default.
  • Magic property access ($section->items), isset(), unset() and ArrayAccess are all deprecated. The magic read in particular goes through &__get(), so it starts the session for writing and materialises the key even on a pure read; ArrayAccess reads and isset() do not. That is why set()/get() exist.
  • A section's expiration must not exceed the session's own (session: expiration:), otherwise you get a warning and the data dies with the session anyway.
session:
	expiration: 14 days      # inactivity timeout, default '3 hours'
	autoStart: smart         # smart (default) | always | never
	cookieSamesite: Lax      # Lax (default) | Strict | None
	name: MYID               # any PHP session directive in camelCase, e.g. savePath
	handler: @myHandler
	debugger: true           # session panel in Tracy Bar

Login/logout session-id regeneration is handled by nette/security – see nette-security.

CSRF: same-origin via Sec-Fetch, not tokens

Since nette/http 3.4 the protection is based on the Sec-Fetch-* request headers (Fetch Metadata), which the browser sets itself and page JavaScript can neither forge nor strip. It replaced the older SameSite=Strict cookie check (Request::isSameSite(), now deprecated).

Request::isFrom(FetchSite|array $site, FetchDest|array|null $dest = null, ?bool $user = null): bool

FetchSite cases: SameOrigin, SameSite, CrossSite, None (direct navigation – typed URL, bookmark, link in an e-mail). FetchDest describes the resource kind (Document, Empty, Image, …); $user = true requires a genuine user gesture. All given conditions must match.

if (!$httpRequest->isFrom(FetchSite::SameOrigin, FetchDest::Document, user: true)) {
	$this->error();
}

What this means in practice:

  • POST forms and presenter signals are protected automatically – Nette\Forms\Form::receiveHttpData() and UI\Form::signalReceived() require FetchSite::SameOrigin, and every handle*() method implicitly gets #[Requires(sameOrigin: true)].

  • $form->addProtection() is deprecated (nette/forms 3.3) – the built-in protection is sufficient, and unlike a token it needs no session. Do not add it to new forms.

  • To allow a legitimate cross-origin POST: $form->allowCrossOrigin() (this replaced disableSameSiteProtection()).

  • Behavior change in 3.4: direct navigation is no longer treated as same-site. A signal reached from a link in an e-mail (Sec-Fetch-Site: none) now fails. Mark it explicitly:

    #[Requires(sameOrigin: false)]
    public function handleUnsubscribe(string $token): void
    
  • Safari < 16.4 sends no Sec-Fetch-*; Nette falls back to the SameSite=Strict cookie _nss, sent only to such browsers since 3.4. It can only prove "not cross-site", so a check that also demands $dest or $user returns false there. http: disableNetteCookie: true switches the cookie off — and with it the only fallback, which breaks every POST from those browsers.

  • Any non-browser client fails the check, not just old Safari: curl, a mobile app, a webhook or server-to-server traffic sends no Sec-Fetch-* and no _nss, so isFrom(SameOrigin) is false. The failure is quiet — the form reports "not submitted" rather than an error. API endpoints therefore need #[Requires(sameOrigin: false)] (or allowCrossOrigin() on a form) plus authentication of their own, typically a token.

Form-side details live in nette-forms; authentication in nette-security.

SSRF: UrlValidator and IPAddress

New in nette/http 3.4. Validate every user-supplied URL before the server fetches it – otherwise an attacker reaches your loopback, private network or cloud metadata at 169.254.169.254.

use Nette\Http\UrlValidator;

if (!(new UrlValidator)->allows($userUrl)) {
	return; // unsafe
}

The default policy is deliberately strict: https only, port 443 only, and every DNS-resolved A/AAAA address must be publicly routable. Loosen it through constructor named arguments – schemes, ports (null = any), allowPrivateIps, allowLoopback, allowLinkLocal, allowReserved, allowUserinfo, hostAllowlist, hostBlocklist. Multicast is rejected unconditionally. Host patterns are exact or *.example.com (any subdomain depth, not the apex – list both).

  • allowsWithoutDns() – same checks minus DNS resolution and IP ranges; a cheap pre-filter only.
  • getResolvedIPs() – returns the validated IPs ([] on failure). Pin the fetch to them (CURLOPT_RESOLVE) to close the DNS-rebinding race between validation and download.

Nette\Http\IPAddress is the value object behind it: new IPAddress($s) (throws), IPAddress::tryFrom(), isValid(), predicates isPublic(), isPrivate(), isLoopback(), isLinkLocal(), isMulticast(), isReserved(), plus isInRange('10.0.0.0/8'). IPv4-mapped IPv6 (::ffff:127.0.0.1) is normalized, so isLoopback() sees through that classic filter bypass.

Url, UrlImmutable, UrlScript

Url is mutable (setters), UrlImmutable returns new instances from with*() withers, and UrlScript extends UrlImmutable adding the notion of where the application root sits. Request::getUrl() returns a UrlScript with those parts already filled in – don't construct one by hand.

For http://nette.org/admin/script.php/pathinfo/?name=param#footer with script path /admin/script.php:

MethodValue
getScriptPath()/admin/script.php
getBasePath()/admin/
getBaseUrl()http://nette.org/admin/
getRelativeUrl()script.php/pathinfo/?name=param#footer
getPathInfo()/pathinfo/

When generating links or asset paths by hand, prefix with getBasePath() – a bare /css/style.css breaks as soon as the app lives in a subdirectory. getBasePath(), getBaseUrl() and getRelativeUrl() on plain Url are deprecated (3.1); they belong to UrlScript. $url->getFragment() on a request URL is always empty – browsers never send the fragment.

Documentation

The full Nette documentation for this topic is bundled with the plugin. Read a page when you need details beyond this skill:

Nette Mail

composer require nette/mail

Message

$mail = (new Nette\Mail\Message)
	->setFrom('John <john@example.com>')   // or setFrom($email, $name)
	->addTo('peter@example.com')           // addCc(), addBcc(), addReplyTo() likewise
	->setSubject('Order Confirmation')
	->setBody("plain text");               // setHtmlBody() for HTML

Everything must be UTF-8. Priority constants are Message::High / Normal / Low (1/3/5). Internationalized domains (jan@příklad.cz) are punycoded automatically, but only when intl is loaded – without it the UTF-8 domain goes out as-is. (4.2.0)

Embedding Images

A second argument to setHtmlBody() makes it scan the HTML and embed what it finds:

$mail->setHtmlBody('<b>Hello</b> <img src="background.gif">', '/path/to/images');

It rewrites <img src>, <body background>, url(...) in style attributes and <style> blocks, and the [[file.png]] placeholder. It skips anything absolute – a value starting with a scheme, a / or a # is left alone, which is the usual reason "automatic embedding didn't work". It also fills the subject from <title> when none is set and generates the plain-text alternative. Doing it by hand:

$part = $mail->addEmbeddedFile('/path/to/logo.png');   // returns a MimePart
$cid = trim($part->getHeader('Content-ID'), '<>');
$mail->setHtmlBody('<img src="cid:' . $cid . '">');

MimePart has no getContentId(). The id lives in the Content-ID header, stored wrapped in angle brackets (<random@host>) that must be stripped for a cid: URI. Never concatenate the returned object into markup – it is a MimePart, not a string. addAttachment($file, $content = null, $contentType = null) and addEmbeddedFile() share a trap: when $content is given, $file is only the display filename, nothing is read.

One-Click Unsubscribe (4.2.0)

$mail->setUnsubscribe('https://example.com/unsubscribe?token=xyz');  // or setUnsubscribe(email: '...')

Sets List-Unsubscribe plus List-Unsubscribe-Post (RFC 8058), which Gmail and Yahoo require from bulk senders. The -Post header is emitted only with a URL, because one-click needs an endpoint that unsubscribes on a bare HTTP POST with no confirmation.

Latte Templates and CSS

No template integration lives in Message; render first, pass the string. For n:href / {link} in a mail template, feed Nette\Application\LinkGenerator into Latte as the uiControl provider – links then come out absolute.

$html = (new Nette\Mail\CssInliner)->addCss($css)->inline($html);  // inline BEFORE setHtmlBody
$mail->setHtmlBody($html, '/path/to/images');

CssInliner requires PHP 8.4+ (Dom\HTMLDocument) and the dom extension. Since 4.2.0 conflicts are resolved by the real CSS cascade: !important, then an existing inline style attribute, then specificity, then source order, with <style> rules processed before addCss() ones. It also emits Outlook attributes (bgcolor, width, height, cellspacing), and leaves @media / :hover in the preserved <style> tag.

Mailers

$mailer = new Nette\Mail\SmtpMailer(
	host: 'smtp.gmail.com', username: 'john@gmail.com', password: '*****',
	encryption: 'ssl',     // or 'tls'; port defaults to 465 / 587 / 25 respectively
);

Use named arguments – the positional order is (host, username, password, port, encryption, persistent, timeout, clientHost, streamOptions), which matches neither the NEON key order nor intuition.

host, username and password are required, without defaults, so an unauthenticated local catcher still needs them spelled out: new SmtpMailer(host: '127.0.0.1', username: '', password: '', port: 1025) – omitting the two empty ones is an ArgumentCountError.

OAuth 2.0 / XOAUTH2 (4.2.0), now required by Gmail and Microsoft 365: keep the username, leave the password empty, and call $mailer->setAccessToken(fn() => $oauth->getFreshToken()). A Closure is re-resolved on every connection, so an expiring token can refresh itself.

FallbackMailer([$a, $b], retryCount: 3, retryWaitTime: 1000) cycles through mailers and throws FallbackMailerException (with a $failures array) if everything fails; since 4.2.0 a permanent failure such as rejected credentials drops that mailer from later attempts. FileMailer('/path/to/mails') (4.2.0) writes each message as a timestamped .eml instead of sending it – the right choice for tests.

DKIM

$mailer->setSigner(new Nette\Mail\DkimSigner(
	domain: 'example.com',
	selector: 'dkim',
	privateKey: file_get_contents('/path/to/dkim.key'),   // the key CONTENT
	oversignHeaders: ['From'],                            // 4.2.0
));

The key type is detected from the key: PEM means RSA (needs openssl), raw base64 of 32 or 64 bytes means Ed25519 per RFC 8463 (needs sodium). (4.2.0) oversignHeaders signs a header one extra time so a spoofer cannot append a second copy. The constructor takes the key contents, but the NEON privateKey takes a file path – DI reads the file.

Configuration

mail:
	smtp: true
	host: 127.0.0.1      # with port 1025: a local Mailpit / MailHog catcher
	port: 1025
	encryption: ...      # ssl|tls|null; 'secure' is the deprecated alias
	dkim: {domain: example.com, selector: dkim, privateKey: %appDir%/cert/dkim.key}
	redirect: dev@example.com     # or {to: ..., subjectPrefix: '[debug]'}

redirect clears To, Cc, Bcc, Disposition-Notification-To and X-Confirm-Reading-To, preserves each in an X-Original-* header and sets To alone to the given address – the safe way to run staging. Registered services: mail.mailer and, with DKIM, mail.signer.

Documentation

The full Nette documentation for this topic is bundled with the plugin. Read a page when you need details beyond this skill:

  • Mail – Message API, embedding, mailers, CssInliner, DKIM, configuration
  • Mail Upgrading – changes between major versions

Nette PhpGenerator

composer require nette/php-generator

Version 4.2 supports PHP 8.1 to 8.5 and generates the latest syntax (enums, readonly, property hooks, asymmetric visibility).

Print the Namespace or the File, Not the Class

Code is modeled as objects and turned into a string by a printer: echo $object uses Printer (Nette style: tabs, brace of a method on its own line), new PsrPrinter produces PSR-12 / PER output. Pick the one the target project uses.

$file = new Nette\PhpGenerator\PhpFile;
$file->setStrictTypes();                   // declare(strict_types=1)
$namespace = $file->addNamespace('App\Model');
$namespace->addUse(App\Entity\Product::class);
$class = $namespace->addClass('ProductRepository');

file_put_contents($path, (new Nette\PhpGenerator\PsrPrinter)->printFile($file));

A class that belongs to a namespace, printed on its own, has its names already shortened by the use clauses but carries neither the namespace line nor the use lines – the result does not compile. Print the PhpNamespace or the PhpFile. A PhpFile holds only namespaces, classes and functions; there is no API for other global code.

Class Names Inside a Namespace Are Fully Qualified

A class added to a namespace has all its types resolved: parent, interfaces, traits, attributes, parameter, property and return types. Write every name fully qualified without the leading backslash; the printer shortens it by the use clauses and the current namespace, or prints \Foo\Bar when nothing applies.

$method->addParameter('product')->setType('App\Entity\Product'); // printed as Product thanks to addUse()
$method->addComment('@return ' . $namespace->simplifyType('App\Entity\Product[]'));

Comments and bodies are not resolved – they are copied as written, so simplify names in them by hand (simplifyName(), simplifyType()). A class created by new ClassType outside any namespace gets no resolution; names are printed as written. Printer::setTypeResolving(false) turns resolution off.

Bodies and Placeholders

setBody($code) and addBody($line) (one line per call) take PHP code as a string. With a second argument, an array, they fill placeholders by Dumper, which exports any value as valid PHP:

PlaceholderResult
?the value exported as PHP
...?array items as arguments, ...?: as named arguments
$?, ->?, ::?a variable, property or static member of that name
\?a literal ?

With arguments, every ? not followed by a letter is a placeholder, including those in ??, ?-> and ? :. Write them as \?\?, \?-> and \? :, or build that part of the code without arguments. Without arguments nothing is replaced and \? stays in the output literally.

$method->setBody('return $this->db->table(?)->where(?, ?);', [$table, $column, $value]);
$method->addBody('return $x \?\? ?;', [$default]);

Members

  • addProperty(), addMethod(), addConstant() and addTrait() throw InvalidStateException when the member exists; the first three take overwrite: true to replace it. addParameter() overwrites silently.
  • A default value is exported as data: addProperty('mode', 'fast') prints 'fast'. For code (a constant, an expression, new Foo) pass new Literal('self::Fast') or Literal::new(Foo::class, [$arg]).
  • addProperty('list')->setType('?array') has no default; ->setInitialized() adds = null.
  • Variadic is a flag of the function, not the parameter: $method->setVariadic() makes the last parameter variadic.
  • Types are strings ('?array', 'int|string') or Type constants and helpers: Type::Array, Type::nullable(Type::String), Type::union(...).
  • Constructor promotion: addMethod('__construct')->addPromotedParameter('name')->setType('string')->setPrivate()->setReadOnly(). A readonly property or promoted parameter must have a type, otherwise printing throws.

Reading Existing Code

$class = ClassType::from(Foo::class);                    // by reflection, bodies are empty
$class = ClassType::from(Foo::class, withBodies: true);  // bodies too, needs nikic/php-parser
$file = PhpFile::fromCode(file_get_contents($path));     // needs nikic/php-parser

fromCode() keeps the file comment and strict_types but drops other global code and single-line comments outside bodies. To edit statements inside bodies, use nikic/php-parser directly. ClassManipulator adds inheritMethod(), inheritProperty() and implement() (stubs for every abstract member of an interface or abstract class).

(new Dumper)->dump($value) is a readable replacement for var_export() when generating configuration or cache files.

Documentation

The full Nette documentation for this topic is bundled with the plugin. Read a page when you need details beyond this skill:

Nette Routing

A route is bidirectional: the same object matches an incoming URL and generates links, and almost every routing bug comes from forgetting the second direction. Related skills: nette-architecture (RouterFactory, lifecycle), nette-configuration (registering it), nette-components (signal links), latte-templates (n:href/{link}). Verified against nette/application 3.3.0 and nette/routing 3.1.3.

Order governs link GENERATION, not just matching

RouteList::constructUrl() walks the routes in declaration order and returns the URL from the first route that can build one – so a catch-all placed first silently hijacks every link, with no error:

$router->addRoute('admin/<presenter>/<action>', 'Admin:Default:default'); // WRONG order:
$router->addRoute('rss.xml', 'Feed:rss');       // link to Feed:rss generates '/admin/feed/rss'

Specific first, catch-all last. The canonical URL of a page is whatever the first non-one-way matching route generates, so the order also decides where canonicalization redirects.

Mask grammar

$router->addRoute('chronicle/<year=2020>', 'History:show');           // default inside the mask
$router->addRoute('<presenter>/<action>[/<id \d+>]', 'Home:default'); // optional part + regex
$router->addRoute('<path .+>', 'File:serve');   // default pattern is [^/]+; only .+ eats slashes
$router->addRoute('//<lang>.example.com/<presenter>', /* ... */);     // host part needs the // prefix
  • A defaulted parameter becomes optional only if everything after it is optional too: '<presenter=Home>/<action=default>/<id=>' equals '[<presenter=Home>/[<action=default>/[<id>]]]', hence the trailing slash. Write the brackets yourself – '[<presenter=Home>[/<action=default>[/<id>]]]' – to drop it. Generation prefers the shortest variant; [!...] keeps an optional part in generated URLs while still accepting URLs without it ('<name>[!.html]' generates /hello.html).
  • %basePath%, %host%, %domain%, %sld%, %tld% are substituted only in //-masks, and %basePath% is matched with its surrounding slashes – write //www.%domain%/%basePath%/<presenter>.
  • Query parameters can be renamed but not validated: in 'product ? id=<productId>' a regex would be silently discarded.
  • A parameter in the metadata array but not in the mask is constant: unchangeable from the query string, and a link passing a different value makes the route decline and fall through – that is how addRoute('tos', ['presenter' => 'Article', 'id' => 123]) works.

RouteList, modules, nesting

$router = new Nette\Application\Routers\RouteList;
$router->withModule('Front')
	->addRoute('rss.xml', 'Feed:rss')            // presenter becomes Front:Feed
	->addRoute('<presenter>/<action>', 'Home:default')
	->end()
	->withDomain('admin.%domain%')->withModule('Admin')
		->addRoute('<presenter>/<action>', 'Dashboard:default');
return $router;                                  // the ROOT, not the chain result
  • withModule()/withDomain()/withPath() create and attach a new child list and return it, not $this; end() returns the parent. Keep the root in a variable – return (new RouteList)->withModule('Front')->addRoute(...) returns the child and loses the siblings.
  • Without withModule() (or a fixed module parameter) the full presenter name lands in the URL, where each : becomes a dot and each PascalCase boundary a dash: Front:Admin:ProductList shows up as front.admin.product-list. Dotted URLs mean a missing withModule(). <module> in a mask captures the whole module path, up to the last colon, and Nette: presenters (Nette:Micro, Nette:Error) are never prefixed.
  • $router[] = new Route(...) is deprecated and emits E_USER_DEPRECATED – use addRoute()/add(), which return static; prepend() returns void. Add a Nette\Application\Routers\Route, never a Nette\Routing\Route – only the former knows presenter/action/module inflection (importing the latter for Route::Value constants is fine).

One-way routes

$router->addRoute('product-info', 'Product:detail', oneWay: true);  // old URL, accepted only
$router->addRoute('product/<id>', 'Product:detail');                // canonical, generates links

oneWay is int|bool. One-way routes are skipped while the generation cache is built, so such a route can never produce a URL; the old address is matched and then 301-redirected by canonicalization. Router::ONE_WAY still works but is @deprecated on master – prefer the named argument.

Filters

Route::FilterIn converts URL -> application, FilterOut back; both take either one parameter (a string) or, under the empty key '', the whole parameter array. Route::FilterTable is a declarative url => app map for one parameter and Route::FilterStrict => true makes it reject unlisted values.

$router->addRoute('article/<id [0-9]+>[-<slug>]', [
	'presenter' => 'Article', 'action' => 'detail',
	'' => [ // general filter: sees all parameters at once
		Route::FilterOut => fn(array $p): array => $p + ['slug' => $slugs->get((int) $p['id'])],
	],
]);
  • The order is asymmetric: on input the per-parameter FilterIn runs before the general one, on output the general FilterOut runs before the per-parameter one, so inside a general filter presenter/action are always PascalCase/camelCase.
  • presenter, action and module already carry filters converting PascalCase/camelCase to kebab-case; write defaults in the application form, <presenter=ProductEdit>, not <presenter=product-edit>.
  • A FilterIn returning null rejects the route (matching falls through to the next one) unless the parameter has a default; FilterStrict behaves the same.
  • Several FilterTable keys may map to one value; the last wins as canonical, because the reverse table is array_flip()ped. Adding a slug to every link is likewise a FilterOut-only job – no template changes; cache the lookup, one page generates the same link often.

Canonicalization

Presenter::canonicalize() regenerates the URL through the router and 301-redirects if it differs from the current one. It runs after the action phase and before signals (see nette-architecture for the full lifecycle) – an action can still change parameters before it fires, a signal handler cannot.

  • Skipped for AJAX and for anything other than GET/HEAD. Disable it with $this->autoCanonicalize = false and call $this->canonicalize() where it suits; switch() inside an action disables it automatically.
  • 301 unless the request carries the VARYING flag, which gives 302; nothing in the framework sets it – use $this->getRequest()->setFlag(Nette\Application\Request::VARYING) when the canonical URL depends on the user or locale.
  • A redirect loop means the generated URL never equals the incoming one, usually a FilterOut that is not the exact inverse of what the mask accepts.

Configuration and debugging

  • Register the factory as a service (- App\Core\RouterFactory::createRouter), or for query-string URLs (?presenter=…&action=…) just - Nette\Application\Routers\SimpleRouter('Home:default'). routing: cache: true serializes the compiled router into the DI container, but only works when the factory takes no arguments and every route is serializable — a closure in FilterIn/FilterOut (the slug pattern above) makes compilation fail with Unable to cache router due to error: Serialization of 'Closure' is not allowed. Use FilterTable or a callable array instead, or leave the cache off.
  • The Tracy routing panel lists every route: green ✓ matched, blue ≈ would also have matched but was overtaken, plus a one-way label. After an unexpected redirect read its redirect bar – it shows how the router understood the original URL. Disable the browser cache; 301s are cached aggressively.
  • $presenter->getHttpRequest()->getUrl() is the raw incoming URL, $presenter->getRequest() is the Nette\Application\Request the router produced – comparing them says at once whether the fault is in matching or in link generation.

Documentation

The full Nette documentation for this topic is bundled with the plugin. Read a page when you need details beyond this skill:

Nette Schema

A library for validating and normalizing data structures against a defined schema. Declare what correct data looks like, and Schema verifies and transforms input in one step.

composer require nette/schema

When to Use Schema

  • Configuration validation – validate config arrays loaded from .neon files
  • API input validation – validate request data before processing
  • Data import/transform – normalize external data into typed structures
  • DI extension config – validate extension configuration in loadConfiguration()

Schema is complementary to Nette Forms (which handles user input with UI) and database constraints (which enforce storage-level rules). Use Schema for programmatic data validation where there's no form UI.

Basic Usage

use Nette\Schema\Expect;
use Nette\Schema\Processor;

$schema = Expect::structure([
	'name' => Expect::string()->required(),
	'email' => Expect::email(),
	'age' => Expect::int()->min(0)->max(120),
]);

$processor = new Processor;

try {
	$normalized = $processor->process($schema, $data);
	// $normalized is stdClass with validated data
} catch (Nette\Schema\ValidationException $e) {
	echo 'Invalid: ' . $e->getMessage();
	// $e->getMessages() returns array of all errors
}

Data Types

Expect::string()              // string, default null
Expect::string('default')     // string with default value
Expect::int()                 // integer
Expect::float()               // float
Expect::bool()                // boolean
Expect::null()                // null only
Expect::array()               // array, default []
Expect::scalar()              // scalar value
Expect::type('ClassName')     // instance of class
Expect::type('bool|string')   // union types

Arrays

// Array of strings
Expect::arrayOf('string')
Expect::arrayOf(Expect::string())

// Array with string keys
Expect::arrayOf('string', 'string')

// List (indexed array)
Expect::listOf('string')
Expect::listOf('email', wrap: true)  // since 1.4: a single value becomes a one-item list

// Tuple (fixed positions, since 1.4); Expect::array([...]) is a structure-like array with keys
Expect::tuple([
	Expect::int(),
	Expect::string(),
	Expect::bool(),
])

On the 1.x line '?int[]' means an array of nullable ints; 2.0 reads it as phpDoc does (a nullable array). Write Expect::arrayOf(Expect::int()->nullable()), which means the same in both.

Structures

$schema = Expect::structure([
	'database' => Expect::structure([
		'host' => Expect::string()->required(),
		'port' => Expect::int(3306),
		'user' => Expect::string()->required(),
		'password' => Expect::string()->nullable(),
	]),
	'debug' => Expect::bool(false),
]);

Properties are optional by default (null). Use required() for mandatory fields.

Enumeration

// One of specific values
Expect::anyOf('small', 'medium', 'large')

// One of values or schemas
Expect::anyOf(
	Expect::string(),
	Expect::int(),
	null
)

// First is default
Expect::anyOf('small', 'medium', 'large')->firstIsDefault()

// Backed enum (since 1.4): accepts the value or the case, always gives the case
Expect::enum(Mode::class)->default(Mode::Production)

Expect::type(Mode::class) is different: like any class name, it accepts only the case itself.

Constraints

// Required field
Expect::string()->required()

// Nullable (accepts null)
Expect::string()->nullable()

// Default value
Expect::string()->default('hello')
Expect::string('hello')  // shorthand

// Length/count limits
Expect::string()->min(3)->max(100)
Expect::array()->min(1)->max(10)

// Numeric range
Expect::int()->min(0)->max(100)

// Pattern
Expect::string()->pattern('\d{5}')  // regex for entire value

// Description, also exported to JSON Schema (since 1.4)
Expect::int(3306)->description('Port the server listens on')

Since 1.4 pattern() on a number or an array, and min()/max() on a union such as Expect::type('int|string'), raise E_USER_DEPRECATED; put the limits on each anyOf() variant.

Assertions

// Custom validation
Expect::string()->assert(fn($s) => strlen($s) % 2 === 0, 'Must be even length')

// Built-in validators
Expect::string()->assert('is_file')
Expect::string()->assert('ctype_alpha')

Transformations

// Transform value after validation
Expect::string()->transform(fn($s) => strtoupper($s))

// Chain transformations
Expect::string()
	->assert('ctype_lower', 'Must be lowercase')
	->transform(fn($s) => strtoupper($s))

// Transform with validation
Expect::string()->transform(function ($s, $context) {
	if (!ctype_alpha($s)) {
		// $code is REQUIRED – a single-argument call is an ArgumentCountError
		$context->addError('Must be letters only', Nette\Schema\Message::FailedAssertion);
		return null;
	}
	return strtoupper($s);
})

Casting

// Cast to type
Expect::scalar()->castTo('string')
Expect::scalar()->castTo('int')
Expect::scalar()->castTo('bool')

// Cast to class (without constructor)
Expect::structure([
	'name' => Expect::string(),
	'age' => Expect::int(),
])->castTo(Person::class)

// Cast to class with constructor
Expect::structure([
	'host' => Expect::string(),
	'port' => Expect::int(),
])->castTo(DatabaseConfig::class)
// Creates: new DatabaseConfig(host: ..., port: ...)

Since 1.4 null is never cast to an object or enum, and castTo('?string') keeps null while castTo('string') turns it into ''.

Normalization (before)

// Normalize before validation
Expect::arrayOf('string')
	->before(fn($v) => is_string($v) ? explode(' ', $v) : $v)

// Now accepts both:
// - ['a', 'b', 'c']
// - 'a b c' (converted to array)

An element has one before() handler: a second call replaces the first (and since 1.4 raises E_USER_DEPRECATED, as 2.0 will chain them). Put all normalization into one handler.

Merging and JSON Schema

$processor->processMultiple($schema, [$defaults, $local]) merges configuration layers. Since 1.4 mergeMode(MergeMode::Replace) (or AppendKeys, OverwriteKeys) and mergeWith() choose how a layer combines with the previous one. Nette\Schema\JsonSchema::export($schema) (since 1.4) gives a JSON Schema document for editors; defaults, castTo() and transform() are not exported.

Structure Options

// Allow extra items
Expect::structure([
	'known' => Expect::string(),
])->otherItems(Expect::mixed())

// Skip default values in output
Expect::structure([
	'debug' => Expect::bool(false),
])->skipDefaults()

// Extend structure
$base = Expect::structure(['name' => Expect::string()]);
$extended = $base->extend(['email' => Expect::email()]);

From Class

Generate schema from class properties:

class Config
{
	public string $name;
	public ?string $email = null;
	public bool $debug = false;
}

$schema = Expect::from(new Config);

// Override specific fields
$schema = Expect::from(new Config, [
	'email' => Expect::email()->required(),
]);

Deprecation

$schema = Expect::structure([
	'oldOption' => Expect::int()->deprecated('Use newOption instead'),
	'newOption' => Expect::int(),
]);

$processor->process($schema, $data);
$warnings = $processor->getWarnings();

Practical Examples

Configuration validation:

$configSchema = Expect::structure([
	'database' => Expect::structure([
		'driver' => Expect::anyOf('mysql', 'pgsql', 'sqlite')->required(),
		'host' => Expect::string('localhost'),
		'port' => Expect::int(),
		'name' => Expect::string()->required(),
		'user' => Expect::string()->required(),
		'password' => Expect::string()->nullable(),
	])->castTo('array'),

	'cache' => Expect::structure([
		'enabled' => Expect::bool(true),
		'ttl' => Expect::int(3600)->min(0),
	]),

	'mail' => Expect::structure([
		'from' => Expect::email()->required(),
		'smtp' => Expect::structure([
			'host' => Expect::string(),
			'port' => Expect::int(587),
			'secure' => Expect::anyOf('tls', 'ssl', null),
		]),
	]),
]);

API input validation:

$createUserSchema = Expect::structure([
	'username' => Expect::string()
		->required()
		->min(3)->max(20)
		->pattern('[a-z0-9_]+'),
	'email' => Expect::email()->required(),
	'password' => Expect::string()->required()->min(8),
	'roles' => Expect::listOf(
		Expect::anyOf('user', 'admin', 'moderator')
	)->default(['user'])->mergeDefaults(false),
])->castTo('array');

Defaults of arrays and lists are MERGED into the input, not replaced. Without mergeDefaults(false) above, a client sending ['admin'] ends up with ['user', 'admin'] – the default silently survives. That is harmless for config (where merging is the point) and a privilege bug for API input.

Documentation

The full Nette documentation for this topic is bundled with the plugin. Read a page when you need details beyond this skill:

Nette Security

Installed with composer require nette/security. The framework registers security.user (Nette\Security\User), security.passwords, security.userStorage, plus security.authenticator / security.authorizator when the security: config section defines them. All are autowired – inject Nette\Security\User or Nette\Security\Passwords by type; in presenters use $this->getUser().

Current names vs. Nette 2.x names

Using an old name still "works" (aliases/deprecated stubs exist), which makes the mistake silent. Always write the current one:

Current (all in Nette\Security\)Deprecated 2.x name
SimpleIdentityIdentity
AuthenticatorIAuthenticator – a different, array-based authenticate(array $credentials) contract; never implement it
Authorizator, Role, ResourceIAuthorizator, IRole, IResource
Authenticator::IdentityNotFound, InvalidCredentialIDENTITY_NOT_FOUND, INVALID_CREDENTIAL
Authorizator::All, Allow, DenyALL, ALLOW, DENY
User::LogoutManual, LogoutInactivityLOGOUT_MANUAL/MANUAL, LOGOUT_INACTIVITY/INACTIVITY

Authenticator

// interface Nette\Security\Authenticator – error codes: IdentityNotFound, InvalidCredential, Failure, NotApproved
function authenticate(string $username, string $password): IIdentity;

InvalidCredential is singular, no trailing s. The error code is the exception's second argument:

public function authenticate(string $username, string $password): SimpleIdentity
{
	$row = $this->database->table('users')->where('username', $username)->fetch();
	if (!$row) {
		throw new AuthenticationException('User not found.', self::IdentityNotFound);
	}
	if (!$this->passwords->verify($password, $row->password)) {
		throw new AuthenticationException('Invalid password.', self::InvalidCredential);
	}
	if ($this->passwords->needsRehash($row->password)) { // transparent hash upgrade
		$this->database->table('users')->wherePrimary($row->id)
			->update(['password' => $this->passwords->hash($password)]);
	}

	return new SimpleIdentity($row->id, $row->role, ['name' => $row->username]);
}

Register it as an ordinary service (services: - MyAuthenticator); User picks it up by autowiring. With several authenticators, mark each autowired: self and call $user->setAuthenticator($this->authenticator) before login(). The return type may be narrowed to SimpleIdentity (covariance). SimpleIdentity(string|int $id, string|array|null $roles = null, ?iterable $data = null) – roles accept a single string. Data is read via magic properties ($identity->name) and getData(); IIdentity declares only getId() and getRoles().

Passwords is a service with instance methods

hash(), verify() and needsRehash() are instance methods on the injected service – not static, and not a wrapper to skip in favour of password_hash() / password_verify():

$hash = $passwords->hash($password);       // throws on empty password
$passwords->verify($password, $hash);      // bool
$passwords->needsRehash($hash);            // bool – rehash on successful login

Configure the algorithm by overriding the service, or with the static factories (3.2.6+):

services:
	security.passwords: Nette\Security\Passwords(::PASSWORD_BCRYPT, [cost: 12])
	# or Nette\Security\Passwords::bcrypt(12)
	# or Nette\Security\Passwords::argon2id(memoryCost: 131072, timeCost: 4) – throws NotSupportedException without Argon2

Store hashes in a VARCHAR(255) column – PASSWORD_DEFAULT may change length between PHP versions.

User

$user->login($username, $password);   // or login($identity) directly; throws AuthenticationException
$user->logout();                      // keeps the identity!
$user->logout(true);                  // discards it
$user->getIdentity();                 // ?IIdentity – nullable
$user->getId();                       // string|int|null
$user->getLogoutReason();             // User::LogoutManual | User::LogoutInactivity | null
$user->onLoggedIn[] = fn() => ...;    // event array; also $onLoggedOut

logout() does not clear the identity by default. getIdentity() and getId() keep returning it afterwards, so "identity exists" is not "logged in" – gate on isLoggedIn(). Use logout(true), or set $user->persistIdentity = false / security: authentication: persistIdentity: false to disable retention globally. Cookie storage cannot retain it either way.

isInRole() / getRoles() / isAllowed() work with effective roles: the identity's roles when logged in, otherwise $user->guestRole ('guest'), never the retained identity's roles – so they need no isLoggedIn() guard. Session-id regeneration on login and logout is done by SessionStorage; do not add your own.

Expiration

$user->setExpiration('30 minutes') must be called before login(); null cancels it. It is inactivity-based and sliding – the window restarts on every request that touches the storage. On expiry the user becomes logged out and getLogoutReason() returns User::LogoutInactivity; the identity survives unless setExpiration($time, clearIdentity: true). It cannot outlive the session itself (session: expiration:, default 3 hours).

Authorization

Authorizator has one method, and its parameters are string-typed: isAllowed(?string $role, ?string $resource, ?string $privilege): bool. User::isAllowed(mixed $resource = Authorizator::All, mixed $privilege = Authorizator::All) omits the role – it loops over the user's effective roles and returns true if any is allowed. Authorizator::All is null and means "anything".

Permission is the built-in ACL:

$acl = new Nette\Security\Permission;
$acl->addRole('registered', 'guest');       // roles inherit
$acl->addResource('perex', 'article');      // resources inherit too
$acl->allow('guest', ['article', 'perex'], 'view');
$acl->allow('admin', $acl::All, ['view', 'edit']);
$acl->deny('admin', 'poll', 'edit');
$acl->allow('registered', 'article', 'edit', fn(Permission $acl, ?string $role, ?string $res, ?string $priv)
	=> $acl->getQueriedRole()->id === $acl->getQueriedResource()->authorId);

Permission::isAllowed(string|Role|null, string|Resource|null, ?string) also takes objects implementing Role::getRoleId() / Resource::getResourceId(); assertions then read them back with getQueriedRole() / getQueriedResource().

Multiple-parent role weight: the LAST parent listed wins. addRole('john', ['admin', 'guest']) gives guest's deny precedence; ['guest', 'admin'] gives admin's allow precedence. This is easy to get backwards. Register the finished ACL through a factory: services: - App\Model\AuthorizatorFactory::create.

NEON configuration

security:
	users:                  # creates SimpleAuthenticator – testing only
		johndoe: 'secret123'
		janedoe:
			password: 'secret123'
			roles: [admin]
			data: {name: Jane}   # ends up in the identity

	roles: {registered: [guest]}      # role: parent(s)
	resources: {comment: [article]}   # resource: parent

	rules:                  # 3.2.6+; [role(s), resource(s), privilege(s)], omitted = all
		allow:
			- [guest, article, view]
			- [registered, comment, [add, edit]]
			- [admin]       # everything
		deny:
			- [banned, comment, add]

	authentication:
		expiration: 30 minutes
		storage: session    # or cookie
		persistIdentity: true
		cookieName: userId  # cookie storage only; plus cookieDomain, cookieSamesite

SimpleAuthenticator compares usernames case-insensitively, and accepts either a plaintext password or a crypt-format hash (auto-detected, 3.2.6+); always quote passwords and hashes – they contain characters NEON and DI treat specially. Defining roles/resources/rules registers a Permission service – if you also register your own authorizator, define everything there instead, or you end up with two competing services.

IdentityHandler – fixing stale roles

The identity is serialized into the storage at login, so role and data changes do not reach a logged-in user until re-login. Let the authenticator also implement Nette\Security\IdentityHandler to refresh on every request:

public function sleepIdentity(IIdentity $identity): IIdentity { return $identity; } // before writing

public function wakeupIdentity(IIdentity $identity): ?IIdentity  // after reading; null forces a logout
{
	$identity->setRoles($this->facade->getUserRoles($identity->getId()));
	return $identity;
}

// used whenever nobody is logged in; null = no guest identity
public function getGuestIdentity(): ?IIdentity { return new SimpleIdentity('guest', ['guest']); }

sleepIdentity() is also how cookie storage works: return a proxy identity whose id is a random authtoken, and reload the real row from it in wakeupIdentity(). The guest identity is never persisted.

Traps

  • Never put the password hash into the identity. new SimpleIdentity($row->id, $row->role, (array) $row) copies it into the session/cookie – unset it first.
  • getIdentity() is nullable; $user->getIdentity()->name on a guest is a fatal error. Prefer $user->getId(), or check isLoggedIn().
  • Reading an unknown identity data key raises an undefined-key warning – it is a plain array lookup, not a null-safe getter.
  • Multiple independent logins in one session need $user->getStorage()->setNamespace('backend') in every place of that section (e.g. BasePresenter::checkRequirements()), plus $user->refreshStorage() if switched mid-request.

Documentation

The full Nette documentation for this topic is bundled with the plugin. Read a page when you need details beyond this skill:

Testing with Nette Tester

Nette Tester is a testing framework for PHP. Test files use the .phpt extension by convention; the runner also collects *Test.php.

Two failure modes worth knowing before writing a single test:

  • A test that executes no assertion is an error – Error: This test forgets to execute an assertion. (exit code 178). It is on by default via Environment::setup().
  • exit() / die() in a test ends it with code 0, i.e. as a PASS. Use Assert::fail() to fail deliberately.
composer require nette/tester --dev

Bootstrap File

The bootstrap file should set up the Tester environment and enable helper functions:

<?php declare(strict_types=1);

require __DIR__ . '/../vendor/autoload.php';

Tester\Environment::setup();
Tester\Environment::setupFunctions();  // enables test(), testException(), testNoError(), setUp()

Basic Test Structure

<?php declare(strict_types=1);

use Tester\Assert;
require __DIR__ . '/../bootstrap.php';


test('Calculator adds numbers correctly', function () {
	$calc = new App\Model\Calculator;
	Assert::same(5, $calc->add(2, 3));
});


test('Calculator throws on division by zero', function () {
	$calc = new App\Model\Calculator;
	Assert::exception(
		fn() => $calc->divide(10, 0),
		\DivisionByZeroError::class,
	);
});

Key points:

  • Use the test() function for each test case
  • The first parameter of test() should be a clear description of what is being tested
  • Do not add comments before test() calls - the description parameter serves this purpose
  • Group related tests in the same file
  • Test file naming: {ClassName}.phpt or {ClassName}.{feature}.phpt

Test Annotations

In the first docblock of the test file, before require. Case-insensitive; no effect when the file is run as plain php test.phpt. The first non-@ line is the test title (written TEST: ...).

AnnotationSyntaxNotes
@skip–always skipped
@phpVersion[op] versionop: <= < == = != <> >= >, default >=
@phpExtensionpdo, pdo_mysqlcomma/space separated; repeatable
@dataProviderfile.ini[, query]path relative to the test file; a .php file returning array/Traversable works too
@dataProvider?? file.inileading ? = skip (not fail) when the file is missing
@multipleNruns the file exactly N times
@testCase–file holds a Tester\TestCase; runner runs each method in its own process
@exitCodeNdefault 0
@outputMatch / @outputMatchFilepattern / fileAssert::match / matchFile against stdout
@phpInikey=valuesame as the runner's -d key=value; repeatable

Trap — @phpVersion with an exact version. The skip condition is version_compare(annotation, actualPhpVersion, op), so equality skips. @phpVersion 8.4.3 on PHP 8.4.3 is skipped; write two components (@phpVersion 8.4), which sorts below 8.4.0 and therefore runs.

In the @dataProvider file form the test loads its own data set: $args = Tester\Environment::loadData(); — called once per run, returning one INI section. INI is parsed with INI_SCANNER_TYPED (values arrive typed). The optional query filters sections: its tokens are matched left to right against the whitespace-separated parts of the section name, operators <= =< < == = != <> >= => > (bare token = =), numeric tokens compared by version_compare. So @dataProvider databases.ini postgresql, >=9.0 selects [postgresql 9.1].

Tester\TestCase

class RectangleTest extends Tester\TestCase
{
	protected function setUp() {}      // before each test method
	protected function tearDown() {}   // after each test method
	public function testArea() { Assert::same(6, (new Rect(2, 3))->area()); }
}

(new RectangleTest)->run();   // MANDATORY, last line of the file
  • Discovery pattern is #^test[A-Z0-9_]#: testArea, test_area, test2 are tests — testarea silently is not.
  • A test* method must be public; a protected one is discovered, then fails with Method X is not public. Make it public or rename it.
  • Forgetting ->run(): with @testCase the runner reports Cannot list TestCase methods in file '…'. Do you call TestCase::run() in it?; without it the file merely defines a class and dies as This test forgets to execute an assertion. (exit 178).
  • Order per method: setUp(), test, tearDown(). If the test throws, tearDown() still runs but errors inside it are suppressed. A failure in setUp()/tearDown() fails the test.
  • In v2.6.1 run() aborts at the first failing method; @testCase sidesteps that by isolating each method.
  • $this->skip('reason') skips the current method from anywhere inside it.
/** @throws RuntimeException  Wrong argument order */   // class + optional message pattern; once per method
/** @dataProvider getArgs */      // value without a dot -> method of this class
/** @dataProvider args.ini x>1 */ // value with a dot -> ini/php file relative to the test file + optional query
public function testLoop($a, $b) {}

The provider returns an array/Traversable of arrays. String-keyed sets are merged over the method's parameter defaults; list-keyed sets are passed positionally. A method with required parameters and no @dataProvider throws TestCaseException.

Assertions Overview

  • Assert::same($expected, $actual) - strict identity (===)
  • Assert::notSame($expected, $actual) - not strictly equal
  • Assert::equal($expected, $actual) - loose comparison (ignores object identity, array key order, float epsilon)
  • Assert::notEqual($expected, $actual)
  • Assert::true($actual), Assert::false($actual), Assert::null($actual), Assert::notNull($actual)
  • Assert::truthy($actual), Assert::falsey($actual)
  • Assert::contains($needle, $haystack) - checks substring or array element; avoid for testing output (see Weak Tests below)
  • Assert::notContains($needle, $haystack)
  • Assert::hasKey($key, $array), Assert::hasNotKey($key, $array)
  • Assert::count($count, $value)
  • Assert::type($type, $value) - class/interface or built-in type ('string', 'int', 'list', etc.)
  • Assert::match($pattern, $actual) - pattern matching with placeholders (see below)
  • Assert::matchFile($file, $actual) - pattern loaded from file
  • Assert::exception($fn, $class, $message, $code) - asserts exception is thrown
  • Assert::error($fn, $type, $message) - asserts PHP error/warning/deprecation is generated
  • Assert::noError($fn) - asserts no errors or exceptions

Weak Tests

A test exists to fail when the code breaks. Before finishing one, ask: would it fail if the code were wrong? If several plausible breakages would still pass, the test only proves that the code runs.

WeakWhyInstead
Assert::contains($needle, $html), match('%A%x%A%')pass for any broken output that keeps the needlesame() / match() / matchFile() on the whole output
Assert::notContains('x', $out), notSame($a->toArray(), $b->toArray())countless wrong values differ or lack xthe exact value, or the difference on one key
Assert::truthy($out), type('string', $out), count() > 0prove only that something came backthe expected value
Assert::same($x->a(), $x->b()), > 1both sides break the same waythe known value
Assert::exception(fn, Exception::class), message '%a%key%a%'a rejection for a wrong reason passesthe concrete class and the whole message, %a% only for parts that vary
Assert::null($x->a ?? null), $x?->parent?->parent in an argument?? and ?-> swallow the errorAssert::type() first, then the value
Assert::noError(fn) where the result mattersruns, checks nothingassert the result
assert() in a test helperdepends on zend.assertions, which is -1 in a production php.iniAssert::type()

The same weakness has three common sources:

  • The expected value cannot disagree. It comes from the tested code itself (one method delegates to the other, $expected = $sut->run($in)), it is computed by the test's own helper, it repeats the decision of the code (the same version condition), or a repeated call is compared with itself, which shows determinism, not purity (compare serialize() of the input before and after instead).
  • The input never reaches the code under test: an early return, a syntax without the closing delimiter it needs, a reference the test defines itself, input the operation has nothing to do with, a parameter whose branch is chosen by a threshold the input does not cross (two workers over one file). A data-driven or meta-test (Assert::same([], $failures), assertions in a loop over found items) passes when it finds nothing: assert that it checked something, with a threshold from the measured value.
  • The test does not check what it claims. A description promising more than the assertions ("exactly once", "every type" with one type, a method name that no longer exists), a comment "checks" next to a call without an assertion, setup that plays no role, a "does not report / change / call" test without the same input in the form that does, a validator run only over clean data, a missing side effect inferred from a result a fallback would give too (observe the file, the content, the mtime). Comparing only the output misses state the output does not show, such as parent pointers; add a structural check over the same data.

Also wrong in the other direction: an exact number where the contract says only "it changed" (a revision), or a number that depends on the environment (files in a directory) instead of being derived from the data.

Not weak, keep it
  • One assertion on a documented default value. A tautology is testing PHP itself (clone, extends, readonly) or the same default in many tests.
  • Assert::type(X::class, $e) right after $e = Assert::exception(…, X::class): unlike type('string', $out) above, it narrows X|null for PHPStan.
  • A test of a foreign library that guards an assumption your code relies on.
  • An order the code creates on purpose (ksort() before output).
  • A duplicate case on which the truth of another test's description rests.

To verify that a new check can fail, break the code on purpose and watch it fail; do not judge it.

Pattern Matching with Assert::match

Assert::match($pattern, $actual) compares a string against a pattern with placeholders. Assert::matchFile($file, $actual) works the same way but loads the pattern from a file.

Available placeholders:

PatternMeaning
%a%one or more of anything except end of line
%a?%zero or more of anything except end of line
%A%one or more of anything including end of line
%A?%zero or more of anything including end of line
%s% / %s?%one or more / zero or more whitespace (except EOL)
%S% / %S?%one or more / zero or more non-whitespace
%c%a single character (except end of line)
%d% / %d?%one or more / zero or more digits
%i%signed integer
%f%floating point number
%h%one or more HEX digits
%w%one or more alphanumeric characters
%ds%directory separator (/ or \)
%%literal % character

Important behavior:

  • Ungreedy matching - placeholders match as little text as possible, so %a% captures the shortest possible string
  • Line endings are normalized - \r\n and \n are treated as equivalent, so tests work cross-platform
  • Trailing whitespace is ignored
  • Patterns can also be raw regexps delimited by ~ or #
Assert::match('<div class="item">%a%</div>', $html);

// For larger patterns, use NOWDOC syntax
Assert::match(<<<'XX'
	<html>
	<body>%A%</body>
	</html>
	XX, $html);

// Or load the pattern from a file (supports the same placeholders)
Assert::matchFile(__DIR__ . '/expected/output.html', $actual);

When Assert::matchFile() fails, the expected and actual output are written to the test output directory as .expected and .actual files.

Testing Exceptions

For simple single-call exceptions, use the concise fn() style:

Assert::exception(
	fn() => Arrays::pick($arr, 'undefined'),
	Nette\InvalidArgumentException::class,
	"Missing item '%s%'.",
);

The Assert::exception() method:

  1. First parameter: A closure that should throw the exception
  2. Second parameter: Expected exception class
  3. Third parameter (optional): Expected exception message, can contain match placeholders (%a%, %s%, etc.)

For testing PHP errors and deprecations:

Assert::error(
	fn() => $object->deprecatedMethod(),
	E_USER_DEPRECATED,
	'This method is deprecated',
);

If the entire test() block is to end with an exception, you can use testException():

testException('throws exception for invalid input', function () {
	$mapper = new FilesystemMapper(__DIR__ . '/fixtures');
	$mapper->getAsset('missing.txt');
}, AssetNotFoundException::class, "Asset file 'missing.txt' not found at path: %a%");

Assert::exception() returns the exception

public static function exception(callable $function, string $class, ?string $message = null, int|string|null $code = null): ?\Throwable

The 3rd argument is an Assert::match pattern, the 4th compares getCode() strictly. The caught exception is returned, so a previous/nested one can be asserted further. Assert::throws() is a plain alias.

$e = Assert::exception(fn() => $obj->save(), DbException::class, 'Insert failed%a%', 1062);
Assert::type(PDOException::class, $e->getPrevious());

setUp() for Shared Setup

Use setUp() to run common initialization before each test() block:

$db = null;

setUp(function () use (&$db) {
	$db = new TestDatabase;
});

test('insert works', function () use (&$db) {
	$db->table('user')->insert(['name' => 'John']);
	Assert::count(1, $db->table('user')->fetchAll());
});

test('each test gets fresh setup', function () use (&$db) {
	// setUp() runs again before this test
	Assert::type(TestDatabase::class, $db);
});

Helpers

CallPurpose
DomQuery::fromHtml($html) / ::fromXml($xml)CSS querying; extends SimpleXMLElement, so text is (string) $el, attributes $el['href']. find($sel): list<DomQuery>, has($sel), matches($sel) (2.5.3), closest($sel) (2.5.5, needs PHP 8.4)
FileMock::create(string $content = '', ?string $extension = null): stringreturns a mock://N.ext URL usable with fopen, file_get_contents, parse_ini_file, …
Helpers::purge(string $dir): voidcreates the dir, wipes its contents; throws on an empty string or a root path
Environment::lock(string $name, string $path): voidserializes parallel tests; the only sane fix for several tests hitting one database
Environment::skip(string $message = ''): voidskips the running test
Assert::with(object|string $objectOrClass, Closure $fn): mixedruns $fn bound to the object so $this reaches private members (a class-string binds statically); returns the closure's value

Environment::lock()'s $path defaults to '', putting the lock file in the filesystem root — always pass a directory: Tester\Environment::lock('database', __DIR__ . '/tmp').

Tester\Expect builds partial constraints, honoured only inside Assert::equal(), never in Assert::same():

Assert::equal([
	'id' => Expect::type('int'),
	'name' => Expect::match('%a%ová')->andType('string'),
	'tags' => Expect::count(3),
], $row);

Static factories mirror the assertions (same, notSame, equal, contains, true, null, nan, truthy, count, type, match, matchFile, …); chain more with the and* prefix, or use Expect::that(fn($v) => $v > 0) for a callback (returning false fails).

Tester\HttpAssert (since 2.5.6) drives real HTTP requests over cURL; deny* variants exist for all three:

HttpAssert::fetch($url, method: 'POST', headers: [...], cookies: [...], follow: false, body: '{}')
	->expectCode(201)->expectHeader('Content-Type', contains: 'json')->expectBody(matches: '%A%ok%A%');

Essential Commands

vendor/bin/tester tests/ -s                     # run everything, show skip reasons
php tests/common/Engine.phpt                    # run one test directly, without the runner
vendor/bin/tester tests/ --coverage coverage.html --coverage-src app/
FlagEffect
-sshow why tests were skipped (otherwise skips are silent)
-j <num>parallel jobs, default 8 — not 1
--stop-on-failstop at the first failure
-w | --watch <path>after the run keep watching the path and re-run on change; repeatable
-o <format>[:<file>]console, console-lines, tap, junit, log, none; repeatable, e.g. -o junit:out.xml -o none
--setup <path>PHP script loaded at startup with Tester\Runner\Runner $runner in scope
--coverage <file> + --coverage-src <path>needs Xdebug or PCOV and Environment::setup() in the tests, else the report is empty

Test Output Directory

When a test fails, Nette Tester writes the expected and actual output into an output directory next to the test files (e.g. tests/Tracy/output/). For each failing test Foo.phpt, you will find:

  • Foo.expected - what the test expected to see
  • Foo.actual - what was actually produced

Always look at these files first when investigating test failures. Comparing .expected vs .actual shows the exact difference and is much more informative than the short failure message printed by the runner.

Accepting a new expected file from .actual:

  • The first failing test() ends the file – it rethrows the assertion. Further matchFile() calls in that file have not run yet; accept one, run again, repeat.
  • Clear output/ before the run: .actual files of earlier runs stay there.
  • Read the diff before accepting it. A snapshot regenerated blindly records bugs as expected behavior, and a typo in the source fixture can silently stop exercising the feature at all.
  • .actual may differ in line endings and in the final newline from the original (matchFile ignores trailing whitespace); diff with --strip-trailing-cr.
  • To find an exact expected value, put a placeholder into the assertion and read .actual. It shows what the code does, not what it should do: judge it before you accept it.

Documentation

The full Nette documentation for this topic is bundled with the plugin. Read a page when you need details beyond this skill:

Nette: Retired Names and Silent Traps

Most of these old names still work – as a class_alias, a deprecated stub or a magic property – and at runtime most of them are completely silent. A real E_USER_DEPRECATED is the exception (Strings::TRIM_CHARACTERS, the @persistent / @crossOrigin annotations, NEON ..., getParameter($name, $default), @property-deprecated), so never rely on a notice appearing.

They are not invisible to tooling, though. The aliases live in each package's src/compatibility.php / compatibility-intf.php in this shape:

if (false) {
	/** @deprecated use Nette\Database\Explorer */
	class Context extends Explorer
	{
	}
} elseif (!class_exists(Context::class)) {
	class_alias(Explorer::class, Context::class);
}

The if (false) branch never executes, but the IDE, PHPStan and Composer's classmap all read it – which is exactly why the editor strikes the old name through while PHP says nothing. So static analysis will flag these; a passing test run will not. Prefer the current name always. Area-specific tables live in nette-security (Authenticator, Authorizator, User constants) and nette-components (component tree, redrawControl); this skill does not repeat them.

Interfaces: the I prefix was dropped

RetiredCurrentNote
Nette\Application\IResponseNette\Application\Responsealias, silent
UI\ITemplate, ITemplateFactory, IRenderable, ISignalReceiver, IStatePersistentUI\Template, TemplateFactory, Renderable, SignalReceiver, StatePersistentalias, silent
Nette\Bridges\ApplicationLatte\ILatteFactory…\LatteFactoryalias, silent
Nette\Application\IRouterNette\Routing\Routeralias, silent up to application 3.2; removed in 3.3 – hard error
Nette\Caching\IStorage, Nette\Mail\IMailerCaching\Storage, Mail\Maileralias, silent
Nette\Localization\ITranslator, Nette\Utils\IHtmlStringLocalization\Translator, Nette\HtmlStringablealias, silent
Nette\Security\IUserStorageNette\Security\UserStorageremoved in security 3.2 – hard error, and a different contract
Nette\Database\IRow, IRowContainer–deprecated as unnecessary

Nette\Application\IPresenter and IPresenterFactory keep the I – do not "modernize" them.

Renamed classes

RetiredCurrentSince
Nette\ConfiguratorNette\Bootstrap\Configuratorbootstrap 3.1 – alias, silent
Nette\Database\ContextNette\Database\Explorerdatabase 3.1 – alias, silent (src/compatibility.php)
Nette\Security\IdentityNette\Security\SimpleIdentitysecurity 3.1 – deprecated stub, silent. Note SimpleIdentity extends Identity, so an Identity is not an instance of SimpleIdentity and a SimpleIdentity type hint rejects it
Nette\Http\UserStorage(use Nette\Security\UserStorage)removed in http 3.4
Nette\PhpGenerator\PhpLiteralNette\PhpGenerator\Literaldeprecated stub
Nette\DI\StatementNette\DI\Definitions\StatementDI 3.0 – alias, silent
Nette\ObjectNette\SmartObject traitremoved in 3.0 (Nette\LegacyObject in nette/deprecated)
Nette\Utils\Finder from nette/finderships in nette/utils 4.0composer remove nette/finder

Constants: UPPER_CASE became PascalCase

Every one below is a deprecated alias that still evaluates, so the old code runs unchanged.

RetiredCurrent
Cache::EXPIRE, EXPIRATIONCache::Expire (also Priority, Sliding, Tags, Files, Items, Callbacks, Namespaces, All; CONSTS -> Constants)
Form::FILLED, EMAIL, MIN_LENGTH, IS_IN, …Form::Filled, Email, MinLength, IsIn, …
Form::PATTERN_ICASEForm::PatternInsensitive
Presenter::INVALID_LINK_WARNING, PRESENTER_KEY, SIGNAL_KEY, ACTION_KEY, FLASH_KEY, DEFAULT_ACTIONInvalidLinkWarning, PresenterKey, SignalKey, ActionKey, FlashKey, DefaultAction
IRequest::GET, POSTIRequest::Get, Post
IResponse::S404_NOT_FOUND, REASON_PHRASESIResponse::S404_NotFound, ReasonPhrases
IResponse::SAME_SITE_LAX / SameSiteLaxNette\Http\SameSite::Lax (enum, http 3.4)
Debugger::DEVELOPMENT, PRODUCTION, DETECT, COOKIE_SECRETDebugger::Development, Production, Detect, CookieSecret
Image::SHRINK_ONLY, STRETCH, EMPTY_GIFImage::ShrinkOnly, Stretch, EmptyGIF
Image::FIT, FILL, EXACTImage::OrSmaller, OrBigger, Cover – renamed, not just recased
IComponent::NAME_SEPARATORIComponent::NameSeparator (3.0.3; removed in 4.0)
Strings::TRIM_CHARACTERSStrings::TrimCharacters

Renamed methods

RetiredCurrent
Cache::start()Cache::capture() (caching 3.1)
FileUpload::getName()getUntrustedName() (http 3.0.5) – also getSanitizedName(), getUntrustedFullPath()
Request::isSameSite()isFrom(FetchSite::SameOrigin) (http 3.4)
Container::getUnsafeValues(), addImage()getUntrustedValues(), addImageButton()
Checkbox::getSeparatorPrototype()getContainerPrototype()
BaseControl::setAttribute(), TextInput::setType()setHtmlAttribute(), setHtmlType()
SelectBox/MultiSelectBox::addOptionAttributes()setOptionAttribute()
Arrays::searchKey()Arrays::getKeyOffset()
Strings::startsWith/endsWith/contains()native str_starts_with/str_ends_with/str_contains()
Strings::normalizeNewLines(), checkEncoding()Strings::unixNewLines(), Validators::isUnicode()
Validators::isList()Arrays::isList()
Callback::closure()Closure::fromCallable(…) / first-class $obj->m(...) – removed
Reflection::getParameterType/getPropertyType/getReturnType()Nette\Utils\Type – removed in utils 4.0
PhpGenerator::setDocuments/addDocument()setComment() / addComment()
Latte\Engine::setTempDirectory()setCacheDirectory(); setStrictTypes()/setStrictParsing() -> setFeature(Feature::…)

Signature changes – do not pass the old arguments

  • getComponents() takes no arguments. $deep/$filterType left the signature in component-model 3.1 and throw Nette\DeprecatedException in 4.0. Use getComponentTree() (also since 3.1), optionally array_filter()-ed. See nette-components.
  • Passwords::hash()/verify()/needsRehash() are instance methods since security 3.0 – inject Nette\Security\Passwords, never call them statically.
  • Flags replaced by named arguments (utils 4.0; the constants still work but are deprecated): Json::PRETTY -> pretty:, Json::ESCAPE_UNICODE -> asciiSafe:, Json::FORCE_ARRAY -> forceArrays:, PREG_GREP_INVERT in Arrays::grep() -> invert:, PREG_* in Strings::split/match/matchAll() -> named arguments. Image::ShrinkOnly is not among them – it stays a bit flag in the $mode argument of resize().
  • Nette\ComponentModel\Component has no constructor since 3.0 – never call parent::__construct() in a presenter or control.
  • Response::setCookie(): an absolute UNIX timestamp is deprecated; a session cookie is null, not 0.
  • $component->getParameter($name, $default): the $default argument is deprecated, use ?? .
  • Form::getValues() returns only validated controls since forms 3.1 (same for the $values handed to onSuccess); getUntrustedValues() returns everything.

Silent traps worth checking explicitly

  • IAuthenticator still exists but is an empty deprecated interface – its authenticate(array $credentials) method is commented out. Implementing it compiles and is never called as you expect. Implement Nette\Security\Authenticator with authenticate(string $username, string $password) – the first parameter is $username, which matters if you call it with named arguments.
  • NEON service keys: the current key is create:. factory: and class: are silently remapped (class: -> type: or create:), so old configs never complain. dynamic: became imported: and an omitted argument is _, not ....
  • Annotations still parse but emit E_USER_DEPRECATED: @persistent -> #[Persistent], @crossOrigin -> #[Requires(sameOrigin: false)], @deprecated -> #[Attributes\Deprecated].
  • Session sections: $section->foo = 1 / $section->foo are deprecated magic properties – use set(), get(), remove(), which correctly distinguish read from write and do not start the session needlessly.
  • $cache[$key] is a fatal error – Cache dropped ArrayAccess back in caching 2.5. Use load() / save().
  • SmartObject emulated properties need a @property annotation and are silent (only @property-deprecated emits a notice); there are no extension methods and no getReflection(). The $obj->onFoo() event sugar does still work.

Still-reproduced Nette 2.x behaviour

  • Nette\Routing\Router::match() returns an array of parameters and constructUrl() accepts one (3.0), not a Nette\Application\Request.
  • fetch() / fetchField() return null, not false, when there is no row (database 3.0).
  • Form controls are optional by default – drop setRequired(false); a control with addRule() must be explicitly setRequired().
  • Presenter and route names are case-sensitive; so is RobotLoader.
  • Overriding a framework method requires the same type hints as the parent (3.0), or PHP raises "Declaration must be compatible".
  • Signals and form submissions are same-origin-checked; allow others with #[Requires(sameOrigin: false)] or $form->allowCrossOrigin().

How to check which rules apply

Each package versions independently, so read composer.json / composer show nette/* for the actual constraint before deciding a name is current – nette/utils 4.x and nette/security 3.x coexist normally. Every package has its own upgrade page, and you must upgrade one minor at a time (3.0 -> 3.1 -> 3.2, never 3.0 -> 3.2). Temporarily silencing E_USER_DEPRECATED hides exactly the warnings this skill is about.

Documentation

The full Nette documentation for this topic is bundled with the plugin. Read a page when you need details beyond this skill:

nette/command-line 2.0 is a new API with no compatibility layer; follow its upgrade guide from 1.x.

Nette Utils

A collection of useful PHP utility classes for everyday tasks.

composer require nette/utils

For detailed references:


DateTime

Extended DateTime class with strict validation and DST fixes. There is also Nette\Utils\DateTimeImmutable (since 4.1.5) with the same API on top of \DateTimeImmutable — prefer it for new code, mutable date objects are a classic source of action-at-a-distance bugs.

use Nette\Utils\DateTime;

// Create from various formats
DateTime::from(1138013640);              // from timestamp
DateTime::from('2024-02-26 04:15:32');   // from string
DateTime::from($dateTimeInterface);       // from object

// Create from parts (throws on invalid date)
DateTime::fromParts(2024, 2, 26, 4, 15);

// Immutable modification
$clone = $original->modifyClone('+1 day');

// Convert relative time to seconds
DateTime::relativeToSeconds('10 minutes'); // 600
DateTime::relativeToSeconds('-1 hour');    // -3600

// JSON serialization (ISO 8601)
echo json_encode($dateTime); // "2024-02-26T04:15:32+01:00"

Json

Safe JSON encoding/decoding with exceptions.

use Nette\Utils\Json;

// Encode
$json = Json::encode($data);
$json = Json::encode($data, pretty: true);        // formatted
$json = Json::encode($data, asciiSafe: true);     // escape unicode
$json = Json::encode($data, htmlSafe: true);      // escape < > &
$json = Json::encode($data, forceObjects: true);  // arrays as objects

// Decode
$data = Json::decode($json);                    // returns stdClass
$data = Json::decode($json, forceArrays: true); // returns array (note the plural)

// Both throw Nette\Utils\JsonException on error

Validators

Value validation and type checking.

use Nette\Utils\Validators;

// Type checking
Validators::is($value, 'int');              // true/false
Validators::is($value, 'int|string|bool');  // union types
Validators::is($value, 'int:0..100');       // range
Validators::is($value, 'string:10..20');    // length range
Validators::is($value, 'array:1..5');       // count range

// Specific validators
Validators::isEmail('user@example.com');    // true
Validators::isUrl('https://nette.org');     // true
Validators::isUri('mailto:info@nette.org'); // true
Validators::isNumeric('123');               // true (string number)
Validators::isNumericInt('123');            // true (string integer)
Validators::isUnicode($string);             // valid UTF-8?
Validators::isInRange($value, [0, 100]);    // in range?
Validators::isNone($value);                 // 0, '', false, null, []?

// Assertion (throws on failure)
Validators::assert($value, 'string:5..10');
Validators::assertField($array, 'key', 'int');

Expected Types

TypeDescription
int, float, bool, string, array, nullPHP types
scalarint|float|bool|string
listindexed array
numberint|float
numericnumber or numeric string
unicodevalid UTF-8 string
email, url, uriformat validation
alnum, alpha, digit, lower, uppercharacter classes
class, interfaceexisting class/interface
file, directoryexisting path

FileSystem

File operations with exception handling.

use Nette\Utils\FileSystem;

// Read/Write
$content = FileSystem::read('/path/to/file');
FileSystem::write('/path/to/file', $content);

// Read large files line by line
foreach (FileSystem::readLines('/path/to/file') as $line) {
	echo $line;
}

// Copy/Move/Delete
FileSystem::copy($source, $target);
FileSystem::rename($source, $target);
FileSystem::delete($path);  // works on directories too

// Directory operations
FileSystem::createDir('/path/to/dir');
FileSystem::makeWritable('/path');

// Path utilities
FileSystem::isAbsolute('../path');                    // false
FileSystem::normalizePath('/file/../path');           // '/path'
FileSystem::joinPaths('a', 'b', 'file.txt');          // 'a/b/file.txt'
FileSystem::resolvePath('/base', '../file.txt');      // '/file.txt'
FileSystem::unixSlashes('path\\to\\file');            // 'path/to/file'

Floats

Safe floating-point comparisons.

use Nette\Utils\Floats;

// Compare floats (handles precision issues)
Floats::isZero(0.0);                    // true
Floats::areEqual(0.1 + 0.2, 0.3);       // true (!)
Floats::isLessThan($a, $b);
Floats::isLessThanOrEqualTo($a, $b);
Floats::isGreaterThan($a, $b);
Floats::isGreaterThanOrEqualTo($a, $b);

// Compare with result
Floats::compare($a, $b);  // -1, 0, or 1

Random

Cryptographically secure random values.

use Nette\Utils\Random;

// Random string (default: 0-9, a-z)
Random::generate(10);                    // 'a4b3c2d1e0'
Random::generate(10, 'A-Z');             // 'XYZABCDEF'
Random::generate(10, '0-9A-Za-z');       // 'aB3cD4eF5g'
Random::generate(10, 'A-Za-z!@#$%');     // 'aBc!@Def#$'

Paginator

Pagination calculations.

use Nette\Utils\Paginator;

$paginator = new Paginator;
$paginator->setItemCount(100);  // total items
$paginator->setItemsPerPage(10);
$paginator->setPage(3);

echo $paginator->getPageCount();    // 10
echo $paginator->getOffset();       // 20 (for SQL OFFSET)
echo $paginator->getLength();       // 10 (for SQL LIMIT)
echo $paginator->isFirst();         // false
echo $paginator->isLast();          // false

Html

HTML element builder.

use Nette\Utils\Html;

// Create element
$el = Html::el('a', ['href' => 'https://nette.org']);
$el->setText('Nette');
echo $el;  // <a href="https://nette.org">Nette</a>

// Fluent interface
$el = Html::el('div')
	->id('container')
	->class('main active')
	->data('id', 123)
	->setHtml('<p>Content</p>');

// Shorthand
Html::el('input', ['type' => 'text', 'name' => 'email']);
Html::el('div class="box"');  // from string

Escaping is explicit and it is the one thing to get right here. setText() / addText() escape, setHtml() / addHtml() do not — reach for the Html variants only when the string is provably safe. add() escapes strings but inserts Html objects as they are.

class and style behave as arrays, which is what makes conditional markup readable — a null item is skipped, so no if is needed around it:

$el->class[] = 'active';
$el->class[] = $isTop ? 'top' : null;   // null is ignored
$el->style['color'] = 'green';
$el->data('config', ['a' => 1]);        // array is JSON-encoded

Process

Running external processes (since 4.1.4) — use this instead of exec(), shell_exec() or pulling in symfony/process.

use Nette\Utils\Process;

// No shell involved, arguments are passed as an array -> nothing to escape
$p = Process::runExecutable('git', ['log', '-1', '--format=%H']);
$p->ensureSuccess();              // returns void, do not chain
echo $p->getStdOutput();          // note the capital O

// Shell string: convenient for pipes, NEVER build it from untrusted input
$p = Process::runCommand('git log --oneline | head -n 20');

Both take $env, $options, $stdin, $stdout, $stderr, $directory and $timeout (default 60 s) — with that many parameters, pass them as named arguments (timeout: 30). Instance methods: wait(), isRunning(), getExitCode(), isSuccess(), ensureSuccess(), getStdOutput(), getStdError(), terminate(), detach(), getPid(). Reading output throws if it was redirected, discarded or piped instead of captured.

Callback

Working with PHP callables.

use Nette\Utils\Callback;

// Normalize to closure – use PHP itself, there is no Callback::closure() in Utils 4
$closure = $callable(...);
$closure = $obj->method(...);

// Check validity
Callback::check($callable);  // throws if invalid

// Invoke a native function and turn its warnings into an exception.
// First argument is a function NAME, not a callable; the handler gets (string $message, int $severity).
Callback::invokeSafe(
	'preg_match',
	[$pattern, $subject],
	fn(string $message) => throw new \RuntimeException($message),
);

// Reflection
$reflection = Callback::toReflection($callable);

Type

PHP type utilities.

use Nette\Utils\Type;

// Get type from reflection
$type = Type::fromReflection($reflectionProperty);
$type = Type::fromReflection($reflectionParameter);

// Parse type string
$type = Type::fromString('int|string|null');

// Type info
$type->getSingleName();     // 'int' or null if union
$type->getNames();          // ['int', 'string', 'null']
$type->isUnion();           // true
$type->isIntersection();    // false
$type->isBuiltin();         // false – only true for a SINGLE built-in type
$type->allows('null');      // true – there is no allowsNull() method
$type->isClass();           // false

SmartObject Trait

Getter/setter property access for classes. Its historical jobs are done by PHP itself now; for new code prefer PHP 8.4 property hooks. The trait is still useful for exposing getters as read-only properties.

The @property annotation is mandatory – without it the magic access throws MemberAccessException, because the trait only maps properties declared in the docblock.

use Nette\SmartObject;

/**
 * @property string $name
 */
class MyClass
{
	use SmartObject;

	private string $name;

	public function getName(): string
	{
		return $this->name;
	}

	public function setName(string $name): void
	{
		$this->name = $name;
	}
}

$obj = new MyClass;
$obj->name = 'John';    // calls setName()
echo $obj->name;        // calls getName()

Documentation

The full Nette documentation for this topic is bundled with the plugin. Read a page when you need details beyond this skill:

Tracy Debugging

Tracy is enabled automatically in debug mode. In debug mode, Tracy displays errors in the browser; in production mode, errors are logged to the log/ directory and the user sees a generic error page.

Requires Tracy ≥ 2.12 for the markdown-to-console output described below. With older versions, only the visual HTML BlueScreen and Tracy Bar are available — you will need to scrape HTML instead.

Enabling Debug Mode

Debug mode is controlled in app/Bootstrap.php:

// Auto-detect: debug on localhost, production elsewhere
$this->configurator->setDebugMode('secret@23.75.345.200');

// Force debug mode (development only!)
$this->configurator->setDebugMode(true);

// Enable Tracy with log directory
$this->configurator->enableTracy($this->rootDir . '/log');

In production, Tracy logs exceptions to log/exception-*.html files (full BlueScreen snapshots) and errors to log/error.log. Tracy ≥ 2.12 additionally writes a .md sibling next to every .html exception — see Batch reading production exceptions below.

How Tracy detects an agent

The markdown-to-console output is conditional — it activates only when Tracy thinks an AI/automation agent is reading the page. Detection works in two stages:

  1. JavaScript stage. The Tracy Bar's own JavaScript checks navigator.webdriver. When true (which Chrome and Firefox set automatically under WebDriver, Chrome DevTools Protocol, Playwright, Puppeteer), it sets a cookie tracy-webdriver=1;path=/;SameSite=Lax.
  2. PHP stage. On every request, PHP calls Tracy\Helpers::isAgent(), which checks $_COOKIE['tracy-webdriver'] === '1'. If yes, markdown outputs are emitted alongside the normal HTML rendering.

Implication for curl / API testing: curl does not run JavaScript, so it never sets the cookie itself. To get markdown outputs in a curl response, set the cookie manually:

curl --cookie 'tracy-webdriver=1' https://example.l/admin/products

Without that cookie, Tracy still works normally for humans (red BlueScreen, visual Tracy Bar in the corner), but the markdown JSON inside <script>console.log(...)</script> / <script>console.error(...)</script> is not emitted.

Chrome MCP — reading Tracy output

When using Chrome MCP (or any browser-automation MCP server: Playwright MCP, mcp-chrome, Puppeteer-based, Browser Use), navigator.webdriver is true, the cookie is set automatically after the first page load, and from then on every page response includes markdown for the agent. Read it all with one call to the server's console tool – list_console_messages in chrome-devtools-mcp, read_console_messages in Claude in Chrome, browser_console_messages in Playwright MCP.

What you get:

  • [error] — BlueScreen error report (full markdown with stack trace, source snippets, arguments, environment). Only present when an exception occurred.
  • [log] — Tracy Bar summary (execution time, memory, plus any panel info like warnings, SQL queries, dumps). Present on every page rendered while the cookie is set.
  • [log] for individual dump() calls — each dump($var) in PHP also pushes a plain-text version through Helpers::consoleLog() for the agent.
  • [error] on a production 500 page — Tracy ≥ 2.12 prints Tracy: Server Error 500. Details have been logged on the server. so the agent knows where to look even when the visible page is the generic placeholder.

The page title on a BlueScreen is set via JavaScript to Tracy: <ExceptionType>: <message>[ #<code>] where <ExceptionType> is the actual exception class or PHP error severity (RuntimeException, Notice, Error, etc.). Useful for grep / wait_for in scripts.

No screenshots or snapshots needed. The visual HTML BlueScreen and Tracy Bar are still rendered for the human user — the markdown is added on top.

Tracy Bar

A floating panel in the bottom-right of every successful page. For humans it is rendered as HTML; for a detected agent the same content is mirrored as a markdown summary into console.log(). Typical contents:

  • Execution time and memory usage
  • SQL queries (count, total time, individual queries with parameters)
  • Request and response details
  • Logged messages, warnings, recent dumps

Custom panels can expose their own markdown rendition by implementing Tracy\IBarPanel::getAgentInfo(): ?string. Built-in panels (SQL, Errors, Dumps, etc.) already do this.

BlueScreen (exceptions & fatal errors)

When an exception is thrown or a fatal error occurs, Tracy renders a full HTML BlueScreen for the human. For a detected agent the same exception is also emitted as markdown via console.error() with:

  • Exception class, message, and code
  • Stack trace with file paths and line numbers
  • Source code context around the error
  • Arguments at each stack frame
  • Request parameters, headers, environment

The BlueScreen provides enough information to diagnose most issues without looking at logs.

Using dump() for debugging

Insert dump($variable) anywhere in PHP code to inspect values:

// In presenter or service code
dump($product);           // dumps single variable
dump($query->getSql());   // dumps SQL string
dump($form->getValues()); // dumps form data

The visual HTML dump is rendered inline as usual; for a detected agent, the same value is also written through Helpers::consoleLog(Dumper::toText($var)) into the browser console, so it shows up in list_console_messages() as a [log] entry.

Batch reading production exceptions

In production, Tracy logs exceptions into log/exception-<hash>.html. Tracy ≥ 2.12 writes a parallel log/exception-<hash>.md next to each one with the same content in markdown — created at the moment the HTML is first written, never overwritten afterwards.

For batch triage read the .md files; the .html siblings are for human inspection. A report can be older than the fix, so check each one against the current code before proposing changes.

Reading the output over curl

A browser page is the richer source for web pages. Over curl (API endpoints, or no browser at hand) the markdown sits in the response body inside <script>console.log(...)</script> / <script>console.error(...)</script>, JSON-encoded; decode the first argument to get it. The SQL queries of a request are in the SQL section of the Tracy Bar entry.

Documentation

The full Nette documentation for this topic is bundled with the plugin. Read a page when you need details beyond this skill:

Sponsors

Details

Marketplace
nette/claude-code
Source
plugins/nette
Category
Development

More from nette/claude-code

All 4