<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/">
<channel>
	<title>Nette Blog</title>
	<link>https://blog.nette.org/en/</link>
	<language>en</language>
	<category>blog</category>
	<docs>http://backend.userland.com/rss</docs>
	<image>
		<url>https://files.nette.org/images/og-nette.png?v=1641878944</url>
		<title>Nette Blog</title>
		<link>https://blog.nette.org/en/</link>
	</image>
	<atom:link rel="self" href="https://blog.nette.org/en/feed/rss" type="application/rss+xml" />

	<item>
		<title>A Model That Asks Does Not Invent</title>
		<link>https://blog.nette.org/en/php-tool-calling-structured-output</link>
		<description>Wiring a language model into an application takes a few lines of code these
days. You send text, you get text back. As long as you want a translation or a
summary, it works beautifully. The trouble starts the moment it has to answer
something only your application knows.

Say you are building customer support for an e-shop. You want the model to
handle questions like “where is my parcel” or “when will my order
arrive”. It writes well, it stays polite, it phrases an answer nicely. It just
has no idea what orders sit in your database, because you can see into it and
the model cannot.

The first idea is usually to attach the data it needs to the question. But
then you would have to know in advance what the customer will ask. Sending the
whole database is not an option, and even if it were, you pay for every word
you send.

And if you do not give it the data, something worse can happen than a refusal
to answer. The model does not have to admit that it does not know. Now and then
it makes an answer up, and a made-up answer sounds every bit as convincing as a
true one. Your customer walks away with a tracking number that never
existed.

There is another way, though: swap the roles. Instead of guessing what the
model will need, you describe what your application is able to find out. The
model then speaks up on its own, saying it would like to look up order
2026–001234, you hand it the result and it composes the answer for the
customer. The technique is called tool calling, sometimes also function calling,
and in PHP it is handled for you by the AI Access library, which has just
reached version 1.0.

One thing about it matters more than anything else: the model does not run
your code. It only says what it would like called and with which arguments.
Whether that actually happens is your application&apos;s decision. It sounds like a
detail, but it is the whole difference between a model that asks and a model
that commands.

Tool calling is a technique that allows LLMs (like ChatGPT
or Claude) to request your PHP application to execute a specific function,
fetching real-time data or performing an action. Structured output, on
the other hand, guarantees that the model returns its response in a strictly
defined, valid JSON format. In this guide, we will implement both using the AI
Access PHP library.

How to Setup Tool Calling in
PHP

You describe a tool with a Tool object: a name, a description of
what it is for, a schema of the arguments and the function that performs it. Do
not look for the model name in the example, the client carries the one you gave
it when you created it; you can also pass it straight to
createChat():

use AIAccess\Chat\Tool;

$chat = $client-&gt;createChat();

$chat-&gt;addTool(new Tool(
	name: &apos;findOrder&apos;,
	description: &apos;Returns the status and shipping date of the order with the given number.&apos;,
	parameters: [
		&apos;type&apos; =&gt; &apos;object&apos;,
		&apos;properties&apos; =&gt; [
			&apos;orderNumber&apos; =&gt; [&apos;type&apos; =&gt; &apos;string&apos;, &apos;description&apos; =&gt; &apos;Order number in the form 2026-001234&apos;],
		],
		&apos;required&apos; =&gt; [&apos;orderNumber&apos;],
	],
	handler: fn(array $args) =&gt; $this-&gt;orders-&gt;findByNumber($args[&apos;orderNumber&apos;])-&gt;toArray(),
));

echo $chat-&gt;sendMessage(&apos;Where is my order 2026-001234?&apos;)-&gt;getText();


That is all of it. A single sendMessage() covers the whole
exchange: the model asks for a tool, the library calls your handler, sends the
result back and waits for the model to answer. The handler returns an array or a
string, because that is exactly what the model gets to read.

The description deserves a pause, because it is easily dismissed as
paperwork. It is a prompt like any other. The model decides from it whether to
call the tool at all, and it has no other clue to go on. “Returns the status
and shipping date of the order with the given number” is a good description.
“Orders” is a bad one. The same goes for the individual arguments: tell the
model what an order number looks like and it will stop putting the
customer&apos;s name there.

The Tool Loop and API Call
Limits

One round means one question from the model and one answer from you. The
interesting part is that several of them happen in a row without you doing
anything about it.

Add two more tools to the previous one, findCustomer to look up
a customer by e-mail and listOrders to list their orders. Asked
what orders does jana@example.com have, the model first calls
findCustomer, waits for the result, takes the identifier out of it
and only then reaches for listOrders. You never described that
procedure; the model assembled it from the descriptions you gave it.

The whole series is called a loop. It has a cap, because otherwise the model
could go round in circles at your expense:

$chat-&gt;setToolLoop(maxRounds: 3);


The default of eight rounds is plenty for ordinary work; if the conversation
does not settle even by then, you get a TooManyRoundsException. And
if you want to know what the whole exchange cost, ask
getTotalUsage(), because getUsage() on the response
speaks only about the last round.

Security and
Authorization in Function Calling

So far it looks as though the model can reach anything you offer it. For
looking up an order that is fine. For cancelling one it is not, and there you
want to decide yourself.

The automatic loop starts only when every tool being called has a
handler. As soon as one is missing, the library stops and hands control back
to you. It is not an oversight you have to guard against, but the way to say
“I will watch this one myself”:

$chat-&gt;addTool(new Tool(
	name: &apos;cancelOrder&apos;,
	description: &apos;Cancels the order with the given number.&apos;,
	parameters: [
		&apos;type&apos; =&gt; &apos;object&apos;,
		&apos;properties&apos; =&gt; [&apos;orderNumber&apos; =&gt; [&apos;type&apos; =&gt; &apos;string&apos;]],
		&apos;required&apos; =&gt; [&apos;orderNumber&apos;],
	],
	// the handler is deliberately missing
));

$response = $chat-&gt;sendMessage(&apos;Please cancel my order 2026-001234.&apos;);

foreach ($response-&gt;getToolCalls() as $call) {
	$number = $call-&gt;arguments[&apos;orderNumber&apos;];
	if ($this-&gt;user-&gt;isAllowed(&apos;order&apos;, &apos;cancel&apos;)) {
		$this-&gt;orders-&gt;cancel($number);
		$chat-&gt;addToolResult($call, &quot;Order $number has been cancelled.&quot;);
	} else {
		$chat-&gt;addToolResult($call, &apos;You are not allowed to cancel orders.&apos;, isError: true);
	}
}

echo $chat-&gt;sendMessage()-&gt;getText();


The model asks for the cancellation, but your code performs it only after the
check. Note the second branch: a refusal is a valid result too. You send
it back with the isError flag and the model knows what to do with
it, so the customer learns why it could not be done instead of waiting for
something that will never come.

The same route fits anywhere you want to merely log or restrict the calls.
And when you need the opposite, namely to make the model reach for one
particular tool, you ask for it with setToolChoice().

Error Handling and AI
Hallucinations

Every so often the model asks for a tool that does not exist, or sends
arguments that do not match the schema. It happens now and then, and above all
it is not your application&apos;s fault, so the library does not treat it as an
exception.

It sends the mistake back to the model as an error result and lets it
correct itself. Models are surprisingly good at this: they read what was wrong
and call the tool again properly. Had an exception been thrown instead, you
would lose the whole answer over a mistake the model can fix on its own.

A failure of your own handler is a different matter. When the
database goes down, the exception propagates to
you, which is right, because a broken database is not for the model to deal
with. If you do want it to learn about the failure and try another route, you
ask for that:

$chat-&gt;setToolLoop(catchErrors: true);


Even then one exception to the exceptions holds: errors of the
Error kind, meaning typos in your own code, always propagate. Were
they sent to the model as a tool result, your bug would hide inside the
conversation and you would never hear about it.

More happens under the hood than would be worth listing here. Gemini, for
instance, never announces a tool call among the reasons an answer ended, and reasoning models want
their thoughts back unchanged in the next round or they reject the request. The
library takes care of that for you, so you only ever meet it when you look into
raw responses.

Structured Output
in PHP: Enforcing JSON Schemas

So far the model has been asking. Now turn it around: you want to pull data
out of a customer e-mail and into your database. No question, no action, just
values.

The obvious move is to ask for JSON in the prompt. Nine times out of ten it
works. The tenth time you get this:

Certainly! Here is the requested data:

```json
{&quot;category&quot;: &quot;complaint&quot;, &quot;orderNumber&quot;: &quot;2026-001234&quot;}
```

The answer is factually right, but json_decode() fails on it,
because there is a sentence and a markdown block around it. Another time the
model names a key differently than you wanted, or returns a number as text. You
will not catch this in testing, because most of the time it simply works. You
catch it in production, usually on data nobody expected.

The fix is not to ask more nicely, but to prescribe the shape of the answer
with a JSON schema:

$chat-&gt;setResponseSchema([
	&apos;type&apos; =&gt; &apos;object&apos;,
	&apos;properties&apos; =&gt; [
		&apos;category&apos; =&gt; [&apos;type&apos; =&gt; &apos;string&apos;, &apos;enum&apos; =&gt; [&apos;complaint&apos;, &apos;question&apos;, &apos;spam&apos;]],
		&apos;orderNumber&apos; =&gt; [&apos;type&apos; =&gt; [&apos;string&apos;, &apos;null&apos;], &apos;description&apos; =&gt; &apos;Order number if the text mentions one&apos;],
		&apos;urgency&apos; =&gt; [&apos;type&apos; =&gt; &apos;integer&apos;, &apos;description&apos; =&gt; &apos;Urgency from 1 to 5&apos;],
	],
	&apos;required&apos; =&gt; [&apos;category&apos;, &apos;orderNumber&apos;, &apos;urgency&apos;],
	&apos;additionalProperties&apos; =&gt; false,
]);

$data = $chat-&gt;sendMessage($email)-&gt;getJson();


getJson() returns the decoded data directly. No stripping of
markdown, no extra json_decode(). And above all: the difference
from a prompt is not that the model suddenly respects the instruction better.
The shape of the answer is enforced by the provider, not by the
model&apos;s good will.

Three things about schemas are worth knowing. Describe the individual fields,
the model reads them and follows them; the description “amount without the
currency and without spaces” gets you 1500, whereas a bare
“amount” may well get you &quot;1 500 USD&quot;. Use enum
for closed lists, as with the category above, and the model cannot invent a
fourth option. And expect strict mode: OpenAI and Grok demand
additionalProperties: false and every key in required,
so keep an optional value there and let it be null instead, exactly
as with the order number.

One exception is worth knowing in advance: DeepSeek has no schemas. Its API
can ask for JSON but cannot prescribe its shape, so
setResponseSchema() is there, yet it always ends in an exception
pointing you to plain JSON mode. The other four providers and the generic client for the
OpenAI dialect all handle schemas.

Structured
Output vs. Tool Calling: Which One to Choose?

Both make the model produce JSON following a schema, which is why they get
confused. The difference is in who hands what to whom.

Structured output is the shape of the answer. The model finishes and
you receive data. Use it when you want a result from the model: sorting an
e-mail into a category, extracting values from text, splitting an address
into parts.

A tool call is a question aimed at you. The model stops and waits for
you to find something out, then carries on. Use it when the model needs
information or an action that your application owns.

Put simply: structured output is an answer, a tool is a question. And nothing
stops you from using both at once, letting the model first find out the status
of an order and then hand you a finished record for the database.

AI Access is a PHP
library that unifies OpenAI, Claude, Gemini, DeepSeek and Grok behind one
interface, with no dependencies at all. Besides tool calling and structured
output it does streaming, images and documents as
input, embeddings for
meaning-based search and batch processing at half the
price. Install it with composer require ai-access/ai-access, it
needs PHP 8.3 and ships around twenty runnable examples. I wrote about how
it came about on my own blog.
</description>
		<content:encoded><![CDATA[
		<p>Wiring a language model into an application takes a few lines of code these
days. You send text, you get text back. As long as you want a translation or a
summary, it works beautifully. The trouble starts the moment it has to answer
something only your application knows.</p>

<p>Say you are building customer support for an e-shop. You want the model to
handle questions like “where is my parcel” or “when will my order
arrive”. It writes well, it stays polite, it phrases an answer nicely. It just
has no idea what orders sit in your database, because you can see into it and
the model cannot.</p>

<p>The first idea is usually to attach the data it needs to the question. But
then you would have to know in advance what the customer will ask. Sending the
whole database is not an option, and even if it were, you pay for every word
you send.</p>

<p>And if you do not give it the data, something worse can happen than a refusal
to answer. The model does not have to admit that it does not know. Now and then
it makes an answer up, and a made-up answer sounds every bit as convincing as a
true one. Your customer walks away with a tracking number that never
existed.</p>

<p>There is another way, though: swap the roles. Instead of guessing what the
model will need, you describe what your application is able to find out. The
model then speaks up on its own, saying it would like to look up order
2026–001234, you hand it the result and it composes the answer for the
customer. The technique is called tool calling, sometimes also function calling,
and in PHP it is handled for you by the <a
href="https://ai-access.deegee.dev/en/">AI Access library</a>, which has just
reached version 1.0.</p>

<p>One thing about it matters more than anything else: <b>the model does not run
your code.</b> It only says what it would like called and with which arguments.
Whether that actually happens is your application's decision. It sounds like a
detail, but it is the whole difference between a model that asks and a model
that commands.</p>

<p class="tip"><b>Tool calling</b> is a technique that allows LLMs (like ChatGPT
or Claude) to request your PHP application to execute a specific function,
fetching real-time data or performing an action. <b>Structured output</b>, on
the other hand, guarantees that the model returns its response in a strictly
defined, valid JSON format. In this guide, we will implement both using the AI
Access PHP library.</p>

<h2 id="toc-how-to-setup-tool-calling-in-php">How to Setup Tool Calling in
PHP</h2>

<p>You describe a tool with a <code>Tool</code> object: a name, a description of
what it is for, a schema of the arguments and the function that performs it. Do
not look for the model name in the example, the client carries the one you gave
it when you created it; you can also pass it straight to
<code>createChat()</code>:</p>

<pre
class="language-php"><code>use AIAccess\Chat\Tool;

$chat = $client-&gt;createChat();

$chat-&gt;addTool(new Tool(
	name: &#039;findOrder&#039;,
	description: &#039;Returns the status and shipping date of the order with the given number.&#039;,
	parameters: [
		&#039;type&#039; =&gt; &#039;object&#039;,
		&#039;properties&#039; =&gt; [
			&#039;orderNumber&#039; =&gt; [&#039;type&#039; =&gt; &#039;string&#039;, &#039;description&#039; =&gt; &#039;Order number in the form 2026-001234&#039;],
		],
		&#039;required&#039; =&gt; [&#039;orderNumber&#039;],
	],
	handler: fn(array $args) =&gt; $this-&gt;orders-&gt;findByNumber($args[&#039;orderNumber&#039;])-&gt;toArray(),
));

echo $chat-&gt;sendMessage(&#039;Where is my order 2026-001234?&#039;)-&gt;getText();
</code></pre>

<p>That is all of it. A single <code>sendMessage()</code> covers the whole
exchange: the model asks for a tool, the library calls your handler, sends the
result back and waits for the model to answer. The handler returns an array or a
string, because that is exactly what the model gets to read.</p>

<p>The description deserves a pause, because it is easily dismissed as
paperwork. It is a prompt like any other. The model decides from it whether to
call the tool at all, and it has no other clue to go on. “Returns the status
and shipping date of the order with the given number” is a good description.
“Orders” is a bad one. The same goes for the individual arguments: tell the
model what an order number looks like and it will stop putting the
customer's name there.</p>

<h2 id="toc-the-tool-loop-and-api-call-limits">The Tool Loop and API Call
Limits</h2>

<p>One round means one question from the model and one answer from you. The
interesting part is that several of them happen in a row without you doing
anything about it.</p>

<p>Add two more tools to the previous one, <code>findCustomer</code> to look up
a customer by e-mail and <code>listOrders</code> to list their orders. Asked
<code>what orders does jana@example.com have</code>, the model first calls
<code>findCustomer</code>, waits for the result, takes the identifier out of it
and only then reaches for <code>listOrders</code>. You never described that
procedure; the model assembled it from the descriptions you gave it.</p>

<p>The whole series is called a loop. It has a cap, because otherwise the model
could go round in circles at your expense:</p>

<pre
class="language-php"><code>$chat-&gt;setToolLoop(maxRounds: 3);
</code></pre>

<p>The default of eight rounds is plenty for ordinary work; if the conversation
does not settle even by then, you get a <code>TooManyRoundsException</code>. And
if you want to know what the whole exchange cost, ask
<code>getTotalUsage()</code>, because <code>getUsage()</code> on the response
speaks only about the last round.</p>

<h2 id="toc-security-and-authorization-in-function-calling">Security and
Authorization in Function Calling</h2>

<p>So far it looks as though the model can reach anything you offer it. For
looking up an order that is fine. For cancelling one it is not, and there you
want to decide yourself.</p>

<p>The automatic loop starts only when <b>every tool being called has a
handler</b>. As soon as one is missing, the library stops and hands control back
to you. It is not an oversight you have to guard against, but the way to say
“I will watch this one myself”:</p>

<pre
class="language-php"><code>$chat-&gt;addTool(new Tool(
	name: &#039;cancelOrder&#039;,
	description: &#039;Cancels the order with the given number.&#039;,
	parameters: [
		&#039;type&#039; =&gt; &#039;object&#039;,
		&#039;properties&#039; =&gt; [&#039;orderNumber&#039; =&gt; [&#039;type&#039; =&gt; &#039;string&#039;]],
		&#039;required&#039; =&gt; [&#039;orderNumber&#039;],
	],
	// the handler is deliberately missing
));

$response = $chat-&gt;sendMessage(&#039;Please cancel my order 2026-001234.&#039;);

foreach ($response-&gt;getToolCalls() as $call) {
	$number = $call-&gt;arguments[&#039;orderNumber&#039;];
	if ($this-&gt;user-&gt;isAllowed(&#039;order&#039;, &#039;cancel&#039;)) {
		$this-&gt;orders-&gt;cancel($number);
		$chat-&gt;addToolResult($call, &quot;Order $number has been cancelled.&quot;);
	} else {
		$chat-&gt;addToolResult($call, &#039;You are not allowed to cancel orders.&#039;, isError: true);
	}
}

echo $chat-&gt;sendMessage()-&gt;getText();
</code></pre>

<p>The model asks for the cancellation, but your code performs it only after the
check. Note the second branch: <b>a refusal is a valid result too.</b> You send
it back with the <code>isError</code> flag and the model knows what to do with
it, so the customer learns why it could not be done instead of waiting for
something that will never come.</p>

<p>The same route fits anywhere you want to merely log or restrict the calls.
And when you need the opposite, namely to make the model reach for one
particular tool, you ask for it with <code>setToolChoice()</code>.</p>

<h2 id="toc-error-handling-and-ai-hallucinations">Error Handling and AI
Hallucinations</h2>

<p>Every so often the model asks for a tool that does not exist, or sends
arguments that do not match the schema. It happens now and then, and above all
it is not your application's fault, so the library does not treat it as an
exception.</p>

<p>It <b>sends the mistake back to the model</b> as an error result and lets it
correct itself. Models are surprisingly good at this: they read what was wrong
and call the tool again properly. Had an exception been thrown instead, you
would lose the whole answer over a mistake the model can fix on its own.</p>

<p>A failure of <b>your own handler</b> is a different matter. When the
database goes down, the <a
href="https://ai-access.deegee.dev/en/errors">exception</a> propagates to
you, which is right, because a broken database is not for the model to deal
with. If you do want it to learn about the failure and try another route, you
ask for that:</p>

<pre
class="language-php"><code>$chat-&gt;setToolLoop(catchErrors: true);
</code></pre>

<p>Even then one exception to the exceptions holds: errors of the
<code>Error</code> kind, meaning typos in your own code, always propagate. Were
they sent to the model as a tool result, your bug would hide inside the
conversation and you would never hear about it.</p>

<p>More happens under the hood than would be worth listing here. Gemini, for
instance, never announces a tool call among the reasons an answer ended, and <a
href="https://ai-access.deegee.dev/en/options">reasoning models</a> want
their thoughts back unchanged in the next round or they reject the request. The
library takes care of that for you, so you only ever meet it when you look into
raw responses.</p>

<h2 id="toc-structured-output-in-php-enforcing-json-schemas">Structured Output
in PHP: Enforcing JSON Schemas</h2>

<p>So far the model has been asking. Now turn it around: you want to pull data
out of a customer e-mail and into your database. No question, no action, just
values.</p>

<p>The obvious move is to ask for JSON in the prompt. Nine times out of ten it
works. The tenth time you get this:</p>

<pre>Certainly! Here is the requested data:

```json
{"category": "complaint", "orderNumber": "2026-001234"}
```</pre>

<p>The answer is factually right, but <code>json_decode()</code> fails on it,
because there is a sentence and a markdown block around it. Another time the
model names a key differently than you wanted, or returns a number as text. You
will not catch this in testing, because most of the time it simply works. You
catch it in production, usually on data nobody expected.</p>

<p>The fix is not to ask more nicely, but to prescribe the shape of the answer
with a <a href="https://json-schema.org">JSON schema</a>:</p>

<pre
class="language-php"><code>$chat-&gt;setResponseSchema([
	&#039;type&#039; =&gt; &#039;object&#039;,
	&#039;properties&#039; =&gt; [
		&#039;category&#039; =&gt; [&#039;type&#039; =&gt; &#039;string&#039;, &#039;enum&#039; =&gt; [&#039;complaint&#039;, &#039;question&#039;, &#039;spam&#039;]],
		&#039;orderNumber&#039; =&gt; [&#039;type&#039; =&gt; [&#039;string&#039;, &#039;null&#039;], &#039;description&#039; =&gt; &#039;Order number if the text mentions one&#039;],
		&#039;urgency&#039; =&gt; [&#039;type&#039; =&gt; &#039;integer&#039;, &#039;description&#039; =&gt; &#039;Urgency from 1 to 5&#039;],
	],
	&#039;required&#039; =&gt; [&#039;category&#039;, &#039;orderNumber&#039;, &#039;urgency&#039;],
	&#039;additionalProperties&#039; =&gt; false,
]);

$data = $chat-&gt;sendMessage($email)-&gt;getJson();
</code></pre>

<p><code>getJson()</code> returns the decoded data directly. No stripping of
markdown, no extra <code>json_decode()</code>. And above all: the difference
from a prompt is not that the model suddenly respects the instruction better.
The shape of the answer is <b>enforced by the provider</b>, not by the
model's good will.</p>

<p>Three things about schemas are worth knowing. Describe the individual fields,
the model reads them and follows them; the description “amount without the
currency and without spaces” gets you <code>1500</code>, whereas a bare
“amount” may well get you <code>"1 500 USD"</code>. Use <code>enum</code>
for closed lists, as with the category above, and the model cannot invent a
fourth option. And expect strict mode: OpenAI and Grok demand
<code>additionalProperties: false</code> and every key in <code>required</code>,
so keep an optional value there and let it be <code>null</code> instead, exactly
as with the order number.</p>

<p>One exception is worth knowing in advance: DeepSeek has no schemas. Its API
can ask for JSON but cannot prescribe its shape, so
<code>setResponseSchema()</code> is there, yet it always ends in an exception
pointing you to plain JSON mode. The other four providers and the <a
href="https://ai-access.deegee.dev/en/providers">generic client for the
OpenAI dialect</a> all handle schemas.</p>

<h2 id="toc-structured-output-vs-tool-calling-which-one-to-choose">Structured
Output vs. Tool Calling: Which One to Choose?</h2>

<p>Both make the model produce JSON following a schema, which is why they get
confused. The difference is in who hands what to whom.</p>

<p><b>Structured output is the shape of the answer.</b> The model finishes and
you receive data. Use it when you want a result from the model: sorting an
e-mail into a category, extracting values from text, splitting an address
into parts.</p>

<p><b>A tool call is a question aimed at you.</b> The model stops and waits for
you to find something out, then carries on. Use it when the model needs
information or an action that your application owns.</p>

<p>Put simply: structured output is an answer, a tool is a question. And nothing
stops you from using both at once, letting the model first find out the status
of an order and then hand you a finished record for the database.</p>

<p><em><a href="https://ai-access.deegee.dev/en/">AI Access</a> is a PHP
library that unifies OpenAI, Claude, Gemini, DeepSeek and Grok behind one
interface, with no dependencies at all. Besides tool calling and structured
output it does <a
href="https://ai-access.deegee.dev/en/streaming">streaming</a>, <a
href="https://ai-access.deegee.dev/en/multimodal">images and documents as
input</a>, <a
href="https://ai-access.deegee.dev/en/embeddings">embeddings</a> for
meaning-based search and <a
href="https://ai-access.deegee.dev/en/batch">batch processing</a> at half the
price. Install it with <code>composer require ai-access/ai-access</code>, it
needs PHP 8.3 and ships around twenty runnable examples. I wrote about <a
href="https://phpfashion.com/en/ai-access-php-library-for-openai-claude-gemini">how
it came about</a> on my own blog.</em></p>

		]]></content:encoded>
		<comments>https://blog.nette.org/en/php-tool-calling-structured-output#comments</comments>
		<pubDate>Mon, 17 Aug 2026 17:07:00 +0200</pubDate>
		<guid isPermaLink="false">item556@http://blog.nette.org</guid>
	</item>
	<item>
		<title>Nette Mail 4.2.0: So Your Emails Actually Arrive</title>
		<link>https://blog.nette.org/en/nette-mail-email-deliverability</link>
		<description>Sending an email is one line of code. Getting it delivered is a discipline
where Gmail and Microsoft tighten the rules every year. Nette Mail 4.2.0 brings
what providers demand today: OAuth sign-in, one-click unsubscribe and more
modern DKIM. Plus one security patch that makes updating right away
worth it.

And it&apos;s a backward compatible release: you rewrite nothing, just update and
pick up the new features as you need them. Let&apos;s go through them in the order
they will come after you: from the requirements of the big providers through
security to developer convenience.

Passwords Are No Longer
Enough: OAuth 2.0

Gmail and Microsoft 365 are gradually switching off username-and-password
sign-in for SMTP; app passwords are on their way out and the future belongs to
OAuth tokens. SmtpMailer therefore supports XOAUTH2
authentication:

$mailer = new Nette\Mail\SmtpMailer(
	host: &apos;smtp.gmail.com&apos;,
	username: &apos;franta@gmail.com&apos;,
	password: &apos;&apos;,
	encryption: &apos;tls&apos;,
);
$mailer-&gt;setAccessToken($accessToken);


Access tokens expire, usually after an hour. Instead of a string you can pass
a callback, which is invoked on every connection and always supplies a
fresh token:

$mailer-&gt;setAccessToken(fn() =&gt; $oauth-&gt;getFreshToken());


Obtaining and refreshing the token stays with your OAuth library, that&apos;s its
craft. Nette Mail handles just the SMTP part, and handles it completely:
including properly closing the exchange when the server rejects the token, so
the error shows you the real reason instead of a mysterious timeout.

One-Click Unsubscribe

Gmail and Yahoo require bulk senders to let recipients unsubscribe from a
newsletter with a single click right in the client. Technically this means a
pair of headers per RFC 8058 that must match exactly; the
List-Unsubscribe header alone does not satisfy the requirement.
This is exactly the kind of knowledge a library should hold, not your code:

$mail-&gt;setUnsubscribe(&apos;https://example.com/unsubscribe?token=xyz&apos;, &apos;unsubscribe@example.com&apos;);


The first parameter is a URL that unsubscribes the recipient in response to a
bare HTTP POST, the second is an email address as a fallback for clients that
cannot send a POST. Both headers are now also signed with DKIM, so nobody can
swap the address the click goes to along the way.

DKIM: Ed25519 and One Patch

Nette Mail has been able to sign emails with DKIM for a long time.
Now, besides RSA, it also handles Ed25519 signatures per RFC 8463: you simply
pass the key and the library detects the type on its own: RSA comes in PEM
format, Ed25519 as raw bytes in base64. No new parameter, no configuration, you
just need the sodium extension.

There is also so-called oversigning: in the oversignHeaders
parameter you list headers that should be protected against a second copy being
appended to an already signed message. That&apos;s a favorite trick of spoofed
emails, because many clients display exactly the added From header.
With oversigning, such an attempt breaks the signature.

And the promised patch: the signature no longer includes the l=
tag with the body length. It sounded harmless, yet it allowed anyone to append
arbitrary content to a signed message without invalidating the signature. That
alone is a reason to update, even if none of the new features interest you.

CssInliner Learned the Cascade

Inlining CSS into style attributes is a necessity for emails,
because clients often ignore the &lt;style&gt; tag. Until now,
though, a simple rule applied: the last declaration wins. Take this
stylesheet:

p.intro { color: red; }
p { color: blue; }


A browser renders the paragraph with the intro class in red,
because the more specific selector wins. The inliner, however, colored it blue,
and the email differed from the website the stylesheet was written for. The more
carefully the styles were written, the further the result drifted.

Since version 4.2.0, CssInliner resolves conflicts with a real
CSS cascade, just like a browser: !important beats ordinary
declarations, an existing inline style beats selectors, then specificity decides
and only at the very end does order matter. Moreover, only the winning value is
written to the output, so style attributes are no longer bloated
with defeated declarations. The conversion to HTML attributes for Outlook got a
fix too: width: auto used to generate width=&quot;0&quot; and
the column in Outlook collapsed to nothing; now the attribute simply isn&apos;t
created.

FileMailer and Other Small
Things

The new FileMailer sends nothing: it writes every message as an
.eml file into a given directory. Open the file in any email client
and you see exactly what would have gone out. Ideal for tests and during
development:

$mailer = new Nette\Mail\FileMailer(__DIR__ . &apos;/mails&apos;);
$mailer-&gt;send($mail);


Alongside all this, a number of smaller improvements arrived that you&apos;ll
notice exactly when they matter:


	Addresses with an international domain like jan@příklad.cz
	are automatically converted to punycode, so ordinary SMTP servers won&apos;t
	reject them.

	STARTTLS defaults to port 587 and negotiates exclusively TLS 1.2 and 1.3;
	when the handshake fails, you learn the real reason.

	A persistent connection that the server has meanwhile closed is quietly
	re-established before the next send, instead of every attempt ending with
	an error.

	Large attachments can no longer be silently truncated when the send buffer
	fills up, and timeouts also apply against a server that never stops
	responding.

	FallbackMailer no longer falls back to mailers whose failure is
	permanent, for example due to rejected credentials.


How to Update

Version 4.2.0 is backward compatible, so the usual is enough:

composer update nette/mail


Sending an email is still one line of code. Making sure it actually arrives
is now much more the library&apos;s job. You&apos;ll find a complete overview of all the
options in the documentation.
</description>
		<content:encoded><![CDATA[
		<p>Sending an email is one line of code. Getting it delivered is a discipline
where Gmail and Microsoft tighten the rules every year. Nette Mail 4.2.0 brings
what providers demand today: OAuth sign-in, one-click unsubscribe and more
modern DKIM. Plus one security patch that makes updating right away
worth it.</p>

<p>And it's a backward compatible release: you rewrite nothing, just update and
pick up the new features as you need them. Let's go through them in the order
they will come after you: from the requirements of the big providers through
security to developer convenience.</p>

<h2 id="toc-passwords-are-no-longer-enough-oauth-2-0">Passwords Are No Longer
Enough: OAuth 2.0</h2>

<p>Gmail and Microsoft 365 are gradually switching off username-and-password
sign-in for SMTP; app passwords are on their way out and the future belongs to
OAuth tokens. <code>SmtpMailer</code> therefore supports XOAUTH2
authentication:</p>

<pre
class="language-php"><code>$mailer = new Nette\Mail\SmtpMailer(
	host: &#039;smtp.gmail.com&#039;,
	username: &#039;franta@gmail.com&#039;,
	password: &#039;&#039;,
	encryption: &#039;tls&#039;,
);
$mailer-&gt;setAccessToken($accessToken);
</code></pre>

<p>Access tokens expire, usually after an hour. Instead of a string you can pass
a callback, which is invoked on every connection and always supplies a
fresh token:</p>

<pre
class="language-php"><code>$mailer-&gt;setAccessToken(fn() =&gt; $oauth-&gt;getFreshToken());
</code></pre>

<p>Obtaining and refreshing the token stays with your OAuth library, that's its
craft. Nette Mail handles just the SMTP part, and handles it completely:
including properly closing the exchange when the server rejects the token, so
the error shows you the real reason instead of a mysterious timeout.</p>

<h2 id="toc-one-click-unsubscribe">One-Click Unsubscribe</h2>

<p>Gmail and Yahoo require bulk senders to let recipients unsubscribe from a
newsletter with a single click right in the client. Technically this means a
pair of headers per RFC 8058 that must match exactly; the
<code>List-Unsubscribe</code> header alone does not satisfy the requirement.
This is exactly the kind of knowledge a library should hold, not your code:</p>

<pre
class="language-php"><code>$mail-&gt;setUnsubscribe(&#039;https://example.com/unsubscribe?token=xyz&#039;, &#039;unsubscribe@example.com&#039;);
</code></pre>

<p>The first parameter is a URL that unsubscribes the recipient in response to a
bare HTTP POST, the second is an email address as a fallback for clients that
cannot send a POST. Both headers are now also signed with DKIM, so nobody can
swap the address the click goes to along the way.</p>

<h2 id="toc-dkim-ed25519-and-one-patch">DKIM: Ed25519 and One Patch</h2>

<p>Nette Mail has been able to sign emails with <a
href="https://blog.nette.org/en/sign-emails-with-dkim">DKIM</a> for a long time.
Now, besides RSA, it also handles Ed25519 signatures per RFC 8463: you simply
pass the key and the library detects the type on its own: RSA comes in PEM
format, Ed25519 as raw bytes in base64. No new parameter, no configuration, you
just need the <code>sodium</code> extension.</p>

<p>There is also so-called oversigning: in the <code>oversignHeaders</code>
parameter you list headers that should be protected against a second copy being
appended to an already signed message. That's a favorite trick of spoofed
emails, because many clients display exactly the added <code>From</code> header.
With oversigning, such an attempt breaks the signature.</p>

<p>And the promised patch: the signature no longer includes the <code>l=</code>
tag with the body length. It sounded harmless, yet it allowed anyone to append
arbitrary content to a signed message without invalidating the signature. That
alone is a reason to update, even if none of the new features interest you.</p>

<h2 id="toc-cssinliner-learned-the-cascade">CssInliner Learned the Cascade</h2>

<p>Inlining CSS into <code>style</code> attributes is a necessity for emails,
because clients often ignore the <code>&lt;style&gt;</code> tag. Until now,
though, a simple rule applied: the last declaration wins. Take this
stylesheet:</p>

<pre
class="language-css"><code>p.intro { color: red; }
p { color: blue; }
</code></pre>

<p>A browser renders the paragraph with the <code>intro</code> class in red,
because the more specific selector wins. The inliner, however, colored it blue,
and the email differed from the website the stylesheet was written for. The more
carefully the styles were written, the further the result drifted.</p>

<p>Since version 4.2.0, <code>CssInliner</code> resolves conflicts with a real
CSS cascade, just like a browser: <code>!important</code> beats ordinary
declarations, an existing inline style beats selectors, then specificity decides
and only at the very end does order matter. Moreover, only the winning value is
written to the output, so <code>style</code> attributes are no longer bloated
with defeated declarations. The conversion to HTML attributes for Outlook got a
fix too: <code>width: auto</code> used to generate <code>width="0"</code> and
the column in Outlook collapsed to nothing; now the attribute simply isn't
created.</p>

<h2 id="toc-filemailer-and-other-small-things">FileMailer and Other Small
Things</h2>

<p>The new <code>FileMailer</code> sends nothing: it writes every message as an
<code>.eml</code> file into a given directory. Open the file in any email client
and you see exactly what would have gone out. Ideal for tests and during
development:</p>

<pre
class="language-php"><code>$mailer = new Nette\Mail\FileMailer(__DIR__ . &#039;/mails&#039;);
$mailer-&gt;send($mail);
</code></pre>

<p>Alongside all this, a number of smaller improvements arrived that you'll
notice exactly when they matter:</p>

<ul>
	<li>Addresses with an international domain like <code>jan@příklad.cz</code>
	are automatically converted to punycode, so ordinary SMTP servers won't
	reject them.</li>

	<li>STARTTLS defaults to port 587 and negotiates exclusively TLS 1.2 and 1.3;
	when the handshake fails, you learn the real reason.</li>

	<li>A persistent connection that the server has meanwhile closed is quietly
	re-established before the next send, instead of every attempt ending with
	an error.</li>

	<li>Large attachments can no longer be silently truncated when the send buffer
	fills up, and timeouts also apply against a server that never stops
	responding.</li>

	<li><code>FallbackMailer</code> no longer falls back to mailers whose failure is
	permanent, for example due to rejected credentials.</li>
</ul>

<h2 id="toc-how-to-update">How to Update</h2>

<p>Version 4.2.0 is backward compatible, so the usual is enough:</p>

<pre class="language-bash"><code>composer update nette/mail
</code></pre>

<p>Sending an email is still one line of code. Making sure it actually arrives
is now much more the library's job. You'll find a complete overview of all the
options in the <a href="https://doc.nette.org/en/mail">documentation</a>.</p>

		]]></content:encoded>
		<comments>https://blog.nette.org/en/nette-mail-email-deliverability#comments</comments>
		<pubDate>Mon, 27 Jul 2026 18:23:00 +0200</pubDate>
		<guid isPermaLink="false">item554@http://blog.nette.org</guid>
	</item>
	<item>
		<title>A form inside a form? HTML says no, Nette 3.3 says yes</title>
		<link>https://blog.nette.org/en/nested-forms</link>
		<description>Anyone who has built a non-trivial page knows a &lt;form&gt;
can&apos;t sit inside another &lt;form&gt;. And if you have ever needed
to nest one form in another, you know there was no clean way to do it for a long
time. Nette Forms 3.3 finally changes that: {form detached} works
around the longstanding HTML restriction with a single word in your
template.

Why you can&apos;t put a form
inside a form

Picture an e-shop checkout: a big form with the delivery address, shipping
method and payment. And inside it a small form for a discount code that
recalculates the price on its own, without submitting the whole order. Two
independent forms, one visually inside the other.

The first instinct is to write it literally:

&lt;form n:name=&quot;orderForm&quot;&gt;
	{input address}

	{* the browser will throw this away *}
	&lt;form n:name=&quot;couponForm&quot;&gt;
		{input code}
		{input apply}
	&lt;/form&gt;

	{input send}
&lt;/form&gt;


But HTML doesn&apos;t allow nesting &lt;form&gt; inside
&lt;form&gt;, and the browser won&apos;t warn you. While parsing it
simply drops the inner opening tag, so no couponForm ever exists in
the document. Worse, the first &lt;/form&gt; closes the outer form
early, so even the send button falls out of it. You get no error,
just a bug that is hard to track down.

The form
attribute changes the rules

HTML5 has an elegant way out: the form attribute on a control.
Any &lt;input&gt; or &lt;button&gt; with
form=&quot;someId&quot; belongs to the &lt;form id=&quot;someId&quot;&gt;
no matter where it physically sits in the document.

So we can separate a form from its controls:

&lt;form id=&quot;newsletter&quot; action=&quot;/subscribe&quot; method=&quot;post&quot;&gt;&lt;/form&gt;

&lt;!-- somewhere else entirely, in a different part of the page --&gt;
&lt;input name=&quot;email&quot; form=&quot;newsletter&quot;&gt;
&lt;button form=&quot;newsletter&quot;&gt;Subscribe&lt;/button&gt;


The &lt;form&gt; tag is empty, the controls reference it by id.
The browser joins them on submit. No hack, it is part of the spec with broad
browser support.

{form detached}:
nesting in one line

This is exactly what Nette now does for you. The two forms stay independent,
each with its own factory:

protected function createComponentOrderForm(): Form
{
	$form = new Form;
	$form-&gt;addText(&apos;address&apos;, &apos;Address:&apos;);
	// ... delivery, payment
	$form-&gt;addSubmit(&apos;send&apos;, &apos;Place order&apos;);
	return $form;
}

protected function createComponentCouponForm(): Form
{
	$form = new Form;
	$form-&gt;addText(&apos;code&apos;, &apos;Discount code:&apos;);
	$form-&gt;addSubmit(&apos;apply&apos;, &apos;Apply&apos;, function (Form $form, $data) {
		$this-&gt;applyCoupon($data-&gt;code);
	});
	return $form;
}


A small aside: in 3.3 addSubmit() accepts the click handler
right at creation, so you no longer attach it separately via
$button-&gt;onClick[].

In the template the trick is to mark the outer form with the word
detached:

{form detached orderForm}
	{input address}

	{* a standalone form, visually inside the order *}
	{form couponForm}
		{input code}
		{input apply}
	{/form}

	{input send}
{/form}


Why the outer one? A detached form gives up its real
&lt;form&gt; tag and links its controls back through the
form attribute. That frees up room inside for a full-fledged inner
&lt;form&gt; that is no longer nested in anything. The resulting
HTML looks like this:

&lt;form id=&quot;frm-orderForm&quot; method=&quot;post&quot; action=&quot;...&quot;&gt;&lt;/form&gt;
&lt;input type=&quot;text&quot; name=&quot;address&quot; form=&quot;frm-orderForm&quot;&gt;

&lt;form id=&quot;frm-couponForm&quot; method=&quot;post&quot; action=&quot;...&quot;&gt;
	&lt;input type=&quot;text&quot; name=&quot;code&quot;&gt;
	&lt;input type=&quot;submit&quot; name=&quot;apply&quot;&gt;
&lt;/form&gt;

&lt;input type=&quot;submit&quot; name=&quot;send&quot; form=&quot;frm-orderForm&quot;&gt;


The outer orderForm is now an empty tag at the top and its
controls report to it through form=&quot;frm-orderForm&quot;. The inner
couponForm, on the other hand, is a perfectly ordinary form that
nothing wraps anymore, so it sails through the browser. Clicking “Apply”
submits only the coupon, clicking “Place order” the whole order.

The id is derived from the component name, that is frm- plus the
name (frm-orderForm). If you need a specific value, set it via
$form-&gt;getElementPrototype()-&gt;id.

You don&apos;t have to think hard about which form to mark. The outer form must
always be detached, the inner one may stay ordinary. And since
marking the inner one detached too does no harm, the simplest
approach is to just mark both. The same holds for deeper nesting: however you
stack the forms, feel free to mark them all detached.

The same principle powers POST
links

If that trick with an empty &lt;form&gt; and the
form attribute looks familiar, you are right. It is exactly what
the best practice POST links is
built on. Actions that change server state, like deleting, do not belong under a
GET link, so you put one empty form in the layout and hang the buttons
on it:

&lt;form method=&quot;post&quot; id=&quot;postForm&quot;&gt;&lt;/form&gt;

&lt;table&gt;
	&lt;tr n:foreach=&quot;$posts as $post&quot;&gt;
		&lt;td&gt;{$post-&gt;title}&lt;/td&gt;
		&lt;td&gt;
			&lt;button class=&quot;btn btn-link&quot; form=&quot;postForm&quot;
				formaction=&quot;{link delete $post-&gt;id}&quot;&gt;delete&lt;/button&gt;
		&lt;/td&gt;
	&lt;/tr&gt;
&lt;/table&gt;


You then protect the action against being triggered from another site with
the #[Requires] attribute (for signals the origin check is
automatic):

use Nette\Application\Attributes\Requires;

#[Requires(methods: &apos;POST&apos;, sameOrigin: true)]
public function actionDelete(int $id): void
{
	$this-&gt;facade-&gt;deletePost($id);
	$this-&gt;redirect(&apos;default&apos;);
}


{form detached} is really this manual technique wrapped into a
full Nette form. Once you write it by hand for a couple of buttons, the next
time you let it be generated for an entire form.

{form scope}:
render just a piece of a form

Alongside detached, the template gained a second tag,
{form scope}. It tells the {input} and
{label} elements inside it which form or container they belong to,
but renders no &lt;form&gt; tag itself. It comes in handy in two
situations.

First: you are rendering the fields of some container in a form. To avoid
repeating the full path like {input address-street} for each one,
{form scope} switches the context to the container and the names
inside are then written relatively:

&lt;form n:name=&quot;signForm&quot;&gt;
	{form scope address}
		{input street}
		{input city}
	{/form}
&lt;/form&gt;


Second: over AJAX you redraw just a piece of an already rendered form, say a
single field in a snippet. You must not render a new &lt;form&gt;
tag here, since it is already on the page, but {input} still has to
know where it belongs:

{snippet captcha}
	{form scope signForm}
		{input captcha}
	{/form}
{/snippet}


It probably reminds you of the older {formContext} and
{formContainer}. And those are exactly what scope
replaces. Each of them did one of those two things and people kept mixing them
up; a single keyword that adapts to the context is easier to remember. Both old
tags still work, by the way.

Conclusion

What HTML forbade, the form attribute brings back through the
back door. Nette Forms 3.3 turns it into a single word in your template,
detached, and the same principle that keeps POST links safe now
serves full-blown nested forms too. Just upgrade to Forms 3.3 and Latte
3.1. There is more in the release, like modernized CSRF
protection that checks the Sec-Fetch-Site header instead of
a token.
</description>
		<content:encoded><![CDATA[
		<p>Anyone who has built a non-trivial page knows a <code>&lt;form&gt;</code>
can't sit inside another <code>&lt;form&gt;</code>. And if you have ever needed
to nest one form in another, you know there was no clean way to do it for a long
time. Nette Forms 3.3 finally changes that: <code>{form detached}</code> works
around the longstanding HTML restriction with a single word in your
template.</p>

<h2 id="toc-why-you-can-t-put-a-form-inside-a-form">Why you can't put a form
inside a form</h2>

<p>Picture an e-shop checkout: a big form with the delivery address, shipping
method and payment. And inside it a small form for a discount code that
recalculates the price on its own, without submitting the whole order. Two
independent forms, one visually inside the other.</p>

<p>The first instinct is to write it literally:</p>

<pre
class="language-latte"><code>&lt;form n:name=&quot;orderForm&quot;&gt;
	{input address}

	{* the browser will throw this away *}
	&lt;form n:name=&quot;couponForm&quot;&gt;
		{input code}
		{input apply}
	&lt;/form&gt;

	{input send}
&lt;/form&gt;
</code></pre>

<p>But HTML doesn't allow nesting <code>&lt;form&gt;</code> inside
<code>&lt;form&gt;</code>, and the browser won't warn you. While parsing it
simply drops the inner opening tag, so no <code>couponForm</code> ever exists in
the document. Worse, the first <code>&lt;/form&gt;</code> closes the outer form
early, so even the <code>send</code> button falls out of it. You get no error,
just a bug that is hard to track down.</p>

<h2 id="toc-the-form-attribute-changes-the-rules">The <code>form</code>
attribute changes the rules</h2>

<p>HTML5 has an elegant way out: the <code>form</code> attribute on a control.
Any <code>&lt;input&gt;</code> or <code>&lt;button&gt;</code> with
<code>form="someId"</code> belongs to the <code>&lt;form id="someId"&gt;</code>
no matter where it physically sits in the document.</p>

<p>So we can separate a form from its controls:</p>

<pre
class="language-latte"><code>&lt;form id=&quot;newsletter&quot; action=&quot;/subscribe&quot; method=&quot;post&quot;&gt;&lt;/form&gt;

&lt;!-- somewhere else entirely, in a different part of the page --&gt;
&lt;input name=&quot;email&quot; form=&quot;newsletter&quot;&gt;
&lt;button form=&quot;newsletter&quot;&gt;Subscribe&lt;/button&gt;
</code></pre>

<p>The <code>&lt;form&gt;</code> tag is empty, the controls reference it by id.
The browser joins them on submit. No hack, it is part of the spec with broad
browser support.</p>

<h2 id="toc-form-detached-nesting-in-one-line"><code>{form detached}</code>:
nesting in one line</h2>

<p>This is exactly what Nette now does for you. The two forms stay independent,
each with its own factory:</p>

<pre
class="language-php"><code>protected function createComponentOrderForm(): Form
{
	$form = new Form;
	$form-&gt;addText(&#039;address&#039;, &#039;Address:&#039;);
	// ... delivery, payment
	$form-&gt;addSubmit(&#039;send&#039;, &#039;Place order&#039;);
	return $form;
}

protected function createComponentCouponForm(): Form
{
	$form = new Form;
	$form-&gt;addText(&#039;code&#039;, &#039;Discount code:&#039;);
	$form-&gt;addSubmit(&#039;apply&#039;, &#039;Apply&#039;, function (Form $form, $data) {
		$this-&gt;applyCoupon($data-&gt;code);
	});
	return $form;
}
</code></pre>

<p>A small aside: in 3.3 <code>addSubmit()</code> accepts the click handler
right at creation, so you no longer attach it separately via
<code>$button-&gt;onClick[]</code>.</p>

<p>In the template the trick is to mark the <i>outer</i> form with the word
<code>detached</code>:</p>

<pre
class="language-latte"><code>{form detached orderForm}
	{input address}

	{* a standalone form, visually inside the order *}
	{form couponForm}
		{input code}
		{input apply}
	{/form}

	{input send}
{/form}
</code></pre>

<p>Why the outer one? A detached form gives up its real
<code>&lt;form&gt;</code> tag and links its controls back through the
<code>form</code> attribute. That frees up room inside for a full-fledged inner
<code>&lt;form&gt;</code> that is no longer nested in anything. The resulting
HTML looks like this:</p>

<pre
class="language-latte"><code>&lt;form id=&quot;frm-orderForm&quot; method=&quot;post&quot; action=&quot;...&quot;&gt;&lt;/form&gt;
&lt;input type=&quot;text&quot; name=&quot;address&quot; form=&quot;frm-orderForm&quot;&gt;

&lt;form id=&quot;frm-couponForm&quot; method=&quot;post&quot; action=&quot;...&quot;&gt;
	&lt;input type=&quot;text&quot; name=&quot;code&quot;&gt;
	&lt;input type=&quot;submit&quot; name=&quot;apply&quot;&gt;
&lt;/form&gt;

&lt;input type=&quot;submit&quot; name=&quot;send&quot; form=&quot;frm-orderForm&quot;&gt;
</code></pre>

<p>The outer <code>orderForm</code> is now an empty tag at the top and its
controls report to it through <code>form="frm-orderForm"</code>. The inner
<code>couponForm</code>, on the other hand, is a perfectly ordinary form that
nothing wraps anymore, so it sails through the browser. Clicking “Apply”
submits only the coupon, clicking “Place order” the whole order.</p>

<p>The id is derived from the component name, that is <code>frm-</code> plus the
name (<code>frm-orderForm</code>). If you need a specific value, set it via
<code>$form-&gt;getElementPrototype()-&gt;id</code>.</p>

<p>You don't have to think hard about which form to mark. The outer form must
always be <code>detached</code>, the inner one may stay ordinary. And since
marking the inner one <code>detached</code> too does no harm, the simplest
approach is to just mark both. The same holds for deeper nesting: however you
stack the forms, feel free to mark them all <code>detached</code>.</p>

<h2 id="toc-the-same-principle-powers-post-links">The same principle powers POST
links</h2>

<p>If that trick with an empty <code>&lt;form&gt;</code> and the
<code>form</code> attribute looks familiar, you are right. It is exactly what
the best practice <a
href="https://doc.nette.org/en/best-practices/post-links">POST links</a> is
built on. Actions that change server state, like deleting, do not belong under a
GET link, so you put one empty form in the layout and hang the buttons
on it:</p>

<pre
class="language-latte"><code>&lt;form method=&quot;post&quot; id=&quot;postForm&quot;&gt;&lt;/form&gt;

&lt;table&gt;
	&lt;tr n:foreach=&quot;$posts as $post&quot;&gt;
		&lt;td&gt;{$post-&gt;title}&lt;/td&gt;
		&lt;td&gt;
			&lt;button class=&quot;btn btn-link&quot; form=&quot;postForm&quot;
				formaction=&quot;{link delete $post-&gt;id}&quot;&gt;delete&lt;/button&gt;
		&lt;/td&gt;
	&lt;/tr&gt;
&lt;/table&gt;
</code></pre>

<p>You then protect the action against being triggered from another site with
the <code>#[Requires]</code> attribute (for signals the origin check is
automatic):</p>

<pre
class="language-php"><code>use Nette\Application\Attributes\Requires;

#[Requires(methods: &#039;POST&#039;, sameOrigin: true)]
public function actionDelete(int $id): void
{
	$this-&gt;facade-&gt;deletePost($id);
	$this-&gt;redirect(&#039;default&#039;);
}
</code></pre>

<p><code>{form detached}</code> is really this manual technique wrapped into a
full Nette form. Once you write it by hand for a couple of buttons, the next
time you let it be generated for an entire form.</p>

<h2 id="toc-form-scope-render-just-a-piece-of-a-form"><code>{form scope}</code>:
render just a piece of a form</h2>

<p>Alongside <code>detached</code>, the template gained a second tag,
<code>{form scope}</code>. It tells the <code>{input}</code> and
<code>{label}</code> elements inside it which form or container they belong to,
but renders no <code>&lt;form&gt;</code> tag itself. It comes in handy in two
situations.</p>

<p>First: you are rendering the fields of some container in a form. To avoid
repeating the full path like <code>{input address-street}</code> for each one,
<code>{form scope}</code> switches the context to the container and the names
inside are then written relatively:</p>

<pre
class="language-latte"><code>&lt;form n:name=&quot;signForm&quot;&gt;
	{form scope address}
		{input street}
		{input city}
	{/form}
&lt;/form&gt;
</code></pre>

<p>Second: over AJAX you redraw just a piece of an already rendered form, say a
single field in a snippet. You must not render a new <code>&lt;form&gt;</code>
tag here, since it is already on the page, but <code>{input}</code> still has to
know where it belongs:</p>

<pre
class="language-latte"><code>{snippet captcha}
	{form scope signForm}
		{input captcha}
	{/form}
{/snippet}
</code></pre>

<p>It probably reminds you of the older <code>{formContext}</code> and
<code>{formContainer}</code>. And those are exactly what <code>scope</code>
replaces. Each of them did one of those two things and people kept mixing them
up; a single keyword that adapts to the context is easier to remember. Both old
tags still work, by the way.</p>

<h2 id="toc-conclusion">Conclusion</h2>

<p>What HTML forbade, the <code>form</code> attribute brings back through the
back door. Nette Forms 3.3 turns it into a single word in your template,
<code>detached</code>, and the same principle that keeps POST links safe now
serves full-blown nested forms too. Just upgrade to Forms 3.3 and Latte
3.1. There is more in the release, like <a
href="https://blog.nette.org/en/quarter-century-of-csrf">modernized CSRF
protection</a> that checks the <code>Sec-Fetch-Site</code> header instead of
a token.</p>

		]]></content:encoded>
		<comments>https://blog.nette.org/en/nested-forms#comments</comments>
		<pubDate>Mon, 29 Jun 2026 23:31:00 +0200</pubDate>
		<guid isPermaLink="false">item552@http://blog.nette.org</guid>
	</item>
	<item>
		<title>Your AI Agent Is Only as Good as Your Types</title>
		<link>https://blog.nette.org/en/ai-agent-only-as-good-as-your-types</link>
		<description>The moment you start coding with an AI agent, you notice something odd: the
value of a top-tier IDE like PhpStorm suddenly drops, while the value of solid
type checking, say with PHPStan, shoots up.
Two years ago that would&apos;ve sounded like heresy. Today it&apos;s closer to practical
advice on how to write better code.

The IDE was for
humans, analysis is for machines

We loved the IDE for its autocomplete, for the type that pops up on hover,
for jump-to-definition and safe refactoring. But all of that is help for the
human eye and hand. An agent doesn&apos;t read your screen. It doesn&apos;t need a tooltip
that appears when you hover. It needs information it can read as text and, above
all, verify on its own.

And that&apos;s exactly what static analysis is: not a hint for a human, but a
verdict for a machine. PhpStorm discreetly underlines a spot where you might be
passing null. PHPStan writes the same thing to the console as an
error that the agent reads, understands and fixes without you
sitting there.

It doesn&apos;t mean the IDE is dying, it&apos;s still a great tool. It&apos;s just that
where the useful value comes from has shifted. What the editor used to give one
person at the keyboard, you now need in a form that a tool running without you
can swallow too.

It&apos;s all about the loop

The first experience with an agent is usually a letdown, and almost always
for one reason:


	you run it without conventions

	you run it without an environment


An agent is no wizard that guesses how your code should look. You have to
describe it: conventions, style, linter. For Nette we wrote exactly this down
into a set of rules for Claude
Code, thanks to which the agent generates code just the way Nette
does it.

It&apos;s also a tool that&apos;s only as good as the feedback it gets. And the best
feedback is a loop. The agent writes something, runs static analysis and tests,
reads the result, fixes the error and tries again. Write, check, fix, repeat.
This cycle is called the agentic loop, and it&apos;s the moment a text generator
turns into someone who actually tunes the code into working shape.

Two sources of feedback are at hand right away. Static analysis and tests. If you don&apos;t write tests, that&apos;s the
very first thing to have the agent generate. Without decent coverage you can&apos;t
close the loop, the agent has no way to know it broke something.

A head start that&apos;s only
now paying off

This is where Nette comes in, because it&apos;s typed to the bone. And it&apos;s not
a thing of the past year.

When PHP 7.1 brought scalar and return types, Nette was the very first
full-stack framework to adopt them fully, including
declare(strict_types=1) in every file. And it kept going: as soon
as PHP 7.4 added typed properties, Nette took them on. Whatever the language
could express natively, Nette used it, usually before anyone else.

For years this was mainly a matter of quality and clean code. Nice, but a
detail only the purists cared about. With the arrival of agents it turned into a
competitive advantage. The better the foundation is typed, the less the agent
has to guess and the more precisely it generates your code.

What types can do when
PHP alone falls short

Native types have a ceiling. PHP can&apos;t write “an array of strings”, “a
non-empty list” or “the return value depends on the argument”. Yet PHPStan
can express exactly these things through PHPDoc annotations, and Nette uses them
to the fullest.

The best place to see it is a common pattern: a form hands you data straight
as your own DTO class. Just ask for it by name and getValues()
returns it fully typed:

$data = $form-&gt;getValues(RegistrationData::class);

echo $data-&gt;email;   // $data is RegistrationData, fully typed


It works thanks to a conditional return type that says “if I pass you a
class name, you return me an instance of that class”. No native type can
do this:

/**
 * @template T of object
 * @param class-string&lt;T&gt;|T|&apos;array&apos;|true|null  $returnType
 * @return ($returnType is class-string&lt;T&gt;|T ? T : ($returnType is &apos;array&apos;|true ? mixed[] : ArrayHash&lt;mixed&gt;))
 */
public function getValues(string|object|bool|null $returnType = null): object|array


So static analysis knows that $data is
RegistrationData, and so does the agent. It doesn&apos;t have to guess,
it reads it straight from the type, and when you write
$data-&gt;emial, it gets an error before the code even runs.

Across the framework you&apos;ll find array shapes like
array{absolute: bool, path: string, signal: bool, ...}, plus
class-string&lt;T&gt;, positive-int,
non-empty-string or @param-out. There are dozens upon
dozens of places where the type carries more information than bare PHP
could hold.

The result is an API that documents itself. And that&apos;s exactly what the
agent needs inside the loop.

New: all of Nette passes
PHPStan at level 8

Now the main thing. With the latest versions we&apos;ve taken typing all the way.
All Nette packages are now fitted with exhaustive type annotations, and every
single one passes static analysis at full level 8. Not just parts, not with a
pile of exceptions, but the whole framework.

The essential takeaway for you: you build on a foundation typed as rigorously
as makes sense. And on a well-typed foundation it&apos;s easy to build a well-typed
application. Your own types have something to lean on, and an agent building on
Nette has firm ground underfoot.

And why “only” level 8, when PHPStan has eleven levels (0 to 10)?
Because everything above it is just about strict handling of the
mixed type, which a framework legitimately works with
(configuration, the DI container, arbitrary callbacks), so level 8 is the
highest tier that still makes practical sense here.

And typing doesn&apos;t stop at the framework&apos;s edge. Nette also ships a PHPStan extension that
teaches the analyzer Nette specifics: it recognizes $this[&apos;menu&apos;]
as your MenuControl, infers form control types from
addText() or addSelect(), understands properties with
#[Inject]. So static analysis sees into your code too, not just the
framework&apos;s, and the agent in the loop has something to read.

Code is no longer read by
humans alone

The IDE won&apos;t vanish, it&apos;s still a great tool for humans. But the center of
gravity has shifted. The value we used to expect from the editor is now carried
by types and tests, because a machine reads them too. Nette has been
accumulating it for years, back when it still looked like a detail.

If you&apos;re tempted to get into coding with agents properly, it&apos;s worth
learning to do it right. And then just close the agent into the loop and let
it work.
</description>
		<content:encoded><![CDATA[
		<p>The moment you start coding with an AI agent, you notice something odd: the
value of a top-tier IDE like PhpStorm suddenly drops, while the value of solid
type checking, say with <a href="https://phpstan.org">PHPStan</a>, shoots up.
Two years ago that would've sounded like heresy. Today it's closer to practical
advice on how to write better code.</p>

<h2 id="toc-the-ide-was-for-humans-analysis-is-for-machines">The IDE was for
humans, analysis is for machines</h2>

<p>We loved the IDE for its autocomplete, for the type that pops up on hover,
for jump-to-definition and safe refactoring. But all of that is help for the
human eye and hand. An agent doesn't read your screen. It doesn't need a tooltip
that appears when you hover. It needs information it can read as text and, above
all, verify on its own.</p>

<p>And that's exactly what static analysis is: not a hint for a human, but a
verdict for a machine. PhpStorm discreetly underlines a spot where you might be
passing <code>null</code>. PHPStan writes the same thing to the console as an
error that the agent reads, understands and fixes without you
sitting there.</p>

<p>It doesn't mean the IDE is dying, it's still a great tool. It's just that
where the useful value comes from has shifted. What the editor used to give one
person at the keyboard, you now need in a form that a tool running without you
can swallow too.</p>

<h2 id="toc-it-s-all-about-the-loop">It's all about the loop</h2>

<p>The first experience with an agent is usually a letdown, and almost always
for one reason:</p>

<ul>
	<li>you run it without conventions</li>

	<li>you run it without an environment</li>
</ul>

<p>An agent is no wizard that guesses how your code should look. You have to
describe it: conventions, style, linter. For Nette we wrote exactly this down
into a <a href="https://ai.nette.org/en/claude-code">set of rules for Claude
Code</a>, thanks to which the agent generates code just the way Nette
does it.</p>

<p>It's also a tool that's only as good as the feedback it gets. And the best
feedback is a loop. The agent writes something, runs static analysis and tests,
reads the result, fixes the error and tries again. Write, check, fix, repeat.
This cycle is called the agentic loop, and it's the moment a text generator
turns into someone who actually tunes the code into working shape.</p>

<p>Two sources of feedback are at hand right away. Static analysis and <a
href="https://tester.nette.org">tests</a>. If you don't write tests, that's the
very first thing to have the agent generate. Without decent coverage you can't
close the loop, the agent has no way to know it broke something.</p>

<h2 id="toc-a-head-start-that-s-only-now-paying-off">A head start that's only
now paying off</h2>

<p>This is where Nette comes in, because it's typed to the bone. And it's not
a thing of the past year.</p>

<p>When PHP 7.1 brought scalar and return types, Nette was the very first
full-stack framework to adopt them fully, including
<code>declare(strict_types=1)</code> in every file. And it kept going: as soon
as PHP 7.4 added typed properties, Nette took them on. Whatever the language
could express natively, Nette used it, usually before anyone else.</p>

<p>For years this was mainly a matter of quality and clean code. Nice, but a
detail only the purists cared about. With the arrival of agents it turned into a
competitive advantage. The better the foundation is typed, the less the agent
has to guess and the more precisely it generates your code.</p>

<h2 id="toc-what-types-can-do-when-php-alone-falls-short">What types can do when
PHP alone falls short</h2>

<p>Native types have a ceiling. PHP can't write “an array of strings”, “a
non-empty list” or “the return value depends on the argument”. Yet PHPStan
can express exactly these things through PHPDoc annotations, and Nette uses them
to the fullest.</p>

<p>The best place to see it is a common pattern: a form hands you data straight
as your own DTO class. Just ask for it by name and <code>getValues()</code>
returns it fully typed:</p>

<pre
class="language-php"><code>$data = $form-&gt;getValues(RegistrationData::class);

echo $data-&gt;email;   // $data is RegistrationData, fully typed
</code></pre>

<p>It works thanks to a conditional return type that says “if I pass you a
class name, you return me an instance of that class”. No native type can
do this:</p>

<pre
class="language-php"><code>/**
 * @template T of object
 * @param class-string&lt;T&gt;|T|&#039;array&#039;|true|null  $returnType
 * @return ($returnType is class-string&lt;T&gt;|T ? T : ($returnType is &#039;array&#039;|true ? mixed[] : ArrayHash&lt;mixed&gt;))
 */
public function getValues(string|object|bool|null $returnType = null): object|array
</code></pre>

<p>So static analysis knows that <code>$data</code> is
<code>RegistrationData</code>, and so does the agent. It doesn't have to guess,
it reads it straight from the type, and when you write
<code>$data-&gt;emial</code>, it gets an error before the code even runs.</p>

<p>Across the framework you'll find array shapes like
<code>array{absolute: bool, path: string, signal: bool, ...}</code>, plus
<code>class-string&lt;T&gt;</code>, <code>positive-int</code>,
<code>non-empty-string</code> or <code>@param-out</code>. There are dozens upon
dozens of places where the type carries more information than bare PHP
could hold.</p>

<p>The result is an API that documents itself. And that's exactly what the
agent needs inside the loop.</p>

<h2 id="toc-new-all-of-nette-passes-phpstan-at-level-8">New: all of Nette passes
PHPStan at level 8</h2>

<p>Now the main thing. With the latest versions we've taken typing all the way.
All Nette packages are now fitted with exhaustive type annotations, and every
single one passes static analysis at full level 8. Not just parts, not with a
pile of exceptions, but the whole framework.</p>

<p>The essential takeaway for you: you build on a foundation typed as rigorously
as makes sense. And on a well-typed foundation it's easy to build a well-typed
application. Your own types have something to lean on, and an agent building on
Nette has firm ground underfoot.</p>

<p>And why “only” level 8, when PHPStan has eleven levels (0 to 10)?
Because everything above it is just about strict handling of the
<code>mixed</code> type, which a framework legitimately works with
(configuration, the DI container, arbitrary callbacks), so level 8 is the
highest tier that still makes practical sense here.</p>

<p>And typing doesn't stop at the framework's edge. Nette also ships a <a
href="https://doc.nette.org/en/tools/phpstan-rules">PHPStan extension</a> that
teaches the analyzer Nette specifics: it recognizes <code>$this['menu']</code>
as your <code>MenuControl</code>, infers form control types from
<code>addText()</code> or <code>addSelect()</code>, understands properties with
<code>#[Inject]</code>. So static analysis sees into your code too, not just the
framework's, and the agent in the loop has something to read.</p>

<h2 id="toc-code-is-no-longer-read-by-humans-alone">Code is no longer read by
humans alone</h2>

<p>The IDE won't vanish, it's still a great tool for humans. But the center of
gravity has shifted. The value we used to expect from the editor is now carried
by types and tests, because a machine reads them too. Nette has been
accumulating it for years, back when it still looked like a detail.</p>

<p>If you're tempted to get into coding with agents properly, it's worth
learning to do it right. And then just close the agent into the loop and let
it work.</p>

		]]></content:encoded>
		<comments>https://blog.nette.org/en/ai-agent-only-as-good-as-your-types#comments</comments>
		<pubDate>Fri, 26 Jun 2026 09:15:00 +0200</pubDate>
		<guid isPermaLink="false">item550@http://blog.nette.org</guid>
	</item>
	<item>
		<title>Component Model 4.0: top-down and no more magic</title>
		<link>https://blog.nette.org/en/nette-component-model-4-0</link>
		<description>Component Model is the quietest library in all of Nette. Nobody talks about
it, almost nobody uses it directly, and yet it sits underneath every form and
every Control in your application. Version 4.0 is largely a cleanup of
deprecated API, but it also hides one genuine change in behavior.

So what is Component Model actually for? If you write presenters and forms,
you use Component Model every day without realizing it. It defines the basic
building blocks: Component (something that has a name and a parent)
and Container (a component that can hold other components).
Nette\Application\UI\Control, Nette\Forms\Form and
Nette\Forms\Container all inherit from them.

getComponents() is
back to direct children only

The getComponents() method once took two parameters:
getComponents($deep, $filterType). They let you recursively
retrieve every component in the subtree and filter them by type along the way.
But we&apos;ve been backing away from these parameters for a while. First we quietly
hid them from the signature in 3.x; in 4.0 they&apos;re gone entirely and using them
throws a DeprecatedException. The method now always returns an
array of direct children and nothing more.

To walk the whole subtree there&apos;s getComponentTree(). It isn&apos;t
new in 4.0; it&apos;s been around since version 3.1:

// before:
$all = $container-&gt;getComponents(true);

// now (but it&apos;s not the same thing)
$all = $container-&gt;getComponentTree();


But it isn&apos;t just a rename — the shape of the result differs. The old
getComponents(true) returned an iterator whose keys were component
names. getComponentTree() returns a plain array with
numeric keys.

Those numeric keys aren&apos;t cosmetic. A component&apos;s name is unique only
within a single container, not across the whole tree, so within a subtree you
can easily run into several components sharing the same name at different
levels. That&apos;s why getComponents(true) couldn&apos;t return a
name-keyed array and returned the iterator instead, which complicated its
implementation and signature. So the aim was to drop the true
parameter and offer two simple methods instead.

Filtering by type (the replacement for $filterType) is easy in
today&apos;s PHP:

$forms = array_filter(
	$container-&gt;getComponentTree(),
	fn($c) =&gt; $c instanceof Form,
);


No more magic: SmartObject is
gone

The Component class no longer uses the
Nette\SmartObject trait, which used to guard access to non-existent
properties and add magic getters. In practice you won&apos;t notice. The
nette/application 3.3 and nette/forms 3.3 releases that Component Model
4.0 expects add SmartObject directly to Control and
BaseControl respectively. So if you write presenters, forms or your
own controls, nothing changes for you. You&apos;ll only notice if you extend the base
classes from Component Model directly.

Notification order: top-down

The last change is the only one that truly alters behavior, and it concerns
monitoring. Monitoring is a key feature of Component Model. A component
can say: “let me know when someone attaches me under a presenter”, and only
at that moment, once it knows its ancestor, does it add things like signals or
persistent parameters. The monitor() method is what you use
for that:

$this-&gt;monitor(Presenter::class, function (Presenter $presenter): void {
	// now I know which presenter I&apos;m under
});


And this is exactly where the change happened.

When you attach a component to a tree that&apos;s already hanging under some
ancestor, all the relevant attached callbacks in the subtree fire.
The question is: in what order?

Up to version 3.x the callbacks were called bottom-up (from the
deepest child to the ancestor). In 4.0 they&apos;re called top-down (from the
ancestor to the children). It looks like cosmetics, but it&apos;s a fix for
genuinely impractical behavior.

The old algorithm worked in two phases. First it walked the entire subtree
and collected every (callback, ancestor) pair into a list. Only then did
it fire the whole list at once. The problem is that the list was a
snapshot of the tree taken before anything had run.

But callbacks routinely manipulate the tree. A parent component can, inside
its attached, remove or move its children, perform a redirect or
destroy itself. And because the children&apos;s callbacks had already been
collected, they fired even for components that had meanwhile fallen out of the
tree. A component received the notification “you are attached under the
presenter” at a moment when it had long since left it.

The new algorithm no longer works in two phases. Instead of collecting the
callbacks up front and firing them all at once, it walks the tree and at each
node calls that node&apos;s callbacks immediately, only then descending to the
children. Before each descent it verifies that the child is still genuinely
a child and that it hasn&apos;t already been processed. As a result:


	The parent is notified before its children. This matches intuition,
	and also how the capture phase of DOM events works, for instance. Before a child
	gets its turn, its parent has already had a chance to prepare the ground.

	The parent can stop a child. When a parent callback removes a child,
	the child&apos;s callback simply isn&apos;t called. The tree is walked live, not from a
	snapshot.

	Moves and reentrancy are handled. If a callback moves a component
	into a container that comes up later, the set of already-processed nodes ensures
	it isn&apos;t processed twice. The crude boolean lock from 3.x has been replaced by
	precise per-object tracking.

	Deduplication stays. The same callback-plus-specific-ancestor pair is
	called exactly once, even when several monitors point at the same ancestor.


So this is a change that makes behavior more predictable and fixes the cases
where a callback used to fire on a component that was no longer in
the tree.

Will it cause a BC break?

This is the only behavioral change, not just an API cleanup, so it deserves
an honest answer. I went through a number of libraries built on top of
Component Model and found not a single case where the change in order broke
anything. The reason is simple: a typical attached callback
only looks “up” at the ancestor that exists at that moment and deals with
itself. It assumes nothing about whether a sibling&apos;s or a child&apos;s callback has
already run.

In theory, though, it can break, in two situations:


	You rely on the opposite order. If you have two components that
	coordinate through attached callbacks, and the child used to write
	state that the parent read (or vice versa), the new order swaps that around. The
	parent now runs first and will see a different state than before. This is rare,
	because it requires deliberate communication between components across the tree
	through callbacks.

	You rely on the old buggy behavior. If your code somehow depended on
	a child&apos;s callback firing even after the parent removed it during attachment,
	that callback now simply won&apos;t run.


If you do none of this — and that&apos;s the vast majority of cases — the
upgrade will have no impact on you from this angle.

How to migrate

For most projects the upgrade is trivial. Check whether any of the following
applies to you:


	rewrite overridden attached() / detached() as
	monitor($type, $attached, $detached),

	replace getComponents(true) with
	getComponentTree(),

	replace filtering getComponents(false, Foo::class) with
	array_filter() over getComponents() (or over
	getComponentTree() if you were filtering recursively),

	replace magic $component-&gt;name and friends with
	getters,

	rename the NAME_SEPARATOR constant to
	NameSeparator,

	if you override addComponent(), add the : static
	return type to the signature (it was previously only in phpDoc as
	@return static).

</description>
		<content:encoded><![CDATA[
		<p>Component Model is the quietest library in all of Nette. Nobody talks about
it, almost nobody uses it directly, and yet it sits underneath every form and
every Control in your application. Version 4.0 is largely a cleanup of
deprecated API, but it also hides one genuine change in behavior.</p>

<p>So what is Component Model actually for? If you write presenters and forms,
you use Component Model every day without realizing it. It defines the basic
building blocks: <code>Component</code> (something that has a name and a parent)
and <code>Container</code> (a component that can hold other components).
<code>Nette\Application\UI\Control</code>, <code>Nette\Forms\Form</code> and
<code>Nette\Forms\Container</code> all inherit from them.</p>

<h2 id="toc-getcomponents-is-back-to-direct-children-only">getComponents() is
back to direct children only</h2>

<p>The <code>getComponents()</code> method once took two parameters:
<code>getComponents($deep, $filterType)</code>. They let you recursively
retrieve every component in the subtree and filter them by type along the way.
But we've been backing away from these parameters for a while. First we quietly
hid them from the signature in 3.x; in 4.0 they're gone entirely and using them
throws a <code>DeprecatedException</code>. The method now always returns an
array of direct children and nothing more.</p>

<p>To walk the whole subtree there's <code>getComponentTree()</code>. It isn't
new in 4.0; it's been around since version 3.1:</p>

<pre
class="language-php"><code>// before:
$all = $container-&gt;getComponents(true);

// now (but it&#039;s not the same thing)
$all = $container-&gt;getComponentTree();
</code></pre>

<p>But it isn't just a rename — the shape of the result differs. The old
<code>getComponents(true)</code> returned an iterator whose keys were component
names. <code>getComponentTree()</code> returns a plain array with
numeric keys.</p>

<p>Those numeric keys aren't cosmetic. A component's name is unique only
within a single container, not across the whole tree, so within a subtree you
can easily run into several components sharing the same name at different
levels. That's why <code>getComponents(true)</code> couldn't return a
name-keyed array and returned the iterator instead, which complicated its
implementation and signature. So the aim was to drop the <code>true</code>
parameter and offer two simple methods instead.</p>

<p>Filtering by type (the replacement for <code>$filterType</code>) is easy in
today's PHP:</p>

<pre
class="language-php"><code>$forms = array_filter(
	$container-&gt;getComponentTree(),
	fn($c) =&gt; $c instanceof Form,
);
</code></pre>

<h2 id="toc-no-more-magic-smartobject-is-gone">No more magic: SmartObject is
gone</h2>

<p>The <code>Component</code> class no longer uses the
<code>Nette\SmartObject</code> trait, which used to guard access to non-existent
properties and add magic getters. In practice you won't notice. The
nette/application 3.3 and nette/forms 3.3 releases that Component Model
4.0 expects add SmartObject directly to <code>Control</code> and
<code>BaseControl</code> respectively. So if you write presenters, forms or your
own controls, nothing changes for you. You'll only notice if you extend the base
classes from Component Model directly.</p>

<h2 id="toc-notification-order-top-down">Notification order: top-down</h2>

<p>The last change is the only one that truly alters behavior, and it concerns
<i>monitoring</i>. Monitoring is a key feature of Component Model. A component
can say: “let me know when someone attaches me under a presenter”, and only
at that moment, once it knows its ancestor, does it add things like signals or
persistent parameters. The <code>monitor()</code> method is what you use
for that:</p>

<pre
class="language-php"><code>$this-&gt;monitor(Presenter::class, function (Presenter $presenter): void {
	// now I know which presenter I&#039;m under
});
</code></pre>

<p>And this is exactly where the change happened.</p>

<p>When you attach a component to a tree that's already hanging under some
ancestor, all the relevant <code>attached</code> callbacks in the subtree fire.
The question is: in what order?</p>

<p>Up to version 3.x the callbacks were called <b>bottom-up</b> (from the
deepest child to the ancestor). In 4.0 they're called <b>top-down</b> (from the
ancestor to the children). It looks like cosmetics, but it's a fix for
genuinely impractical behavior.</p>

<p>The old algorithm worked in two phases. First it walked the entire subtree
and <b>collected</b> every (callback, ancestor) pair into a list. Only then did
it <b>fire</b> the whole list at once. The problem is that the list was a
snapshot of the tree taken <i>before</i> anything had run.</p>

<p>But callbacks routinely manipulate the tree. A parent component can, inside
its <code>attached</code>, remove or move its children, perform a redirect or
destroy itself. And because the children's callbacks had already been
collected, they fired even for components that had meanwhile fallen out of the
tree. A component received the notification “you are attached under the
presenter” at a moment when it had long since left it.</p>

<p>The new algorithm no longer works in two phases. Instead of collecting the
callbacks up front and firing them all at once, it walks the tree and <b>at each
node calls that node's callbacks immediately, only then descending to the
children</b>. Before each descent it verifies that the child is still genuinely
a child and that it hasn't already been processed. As a result:</p>

<ul>
	<li><b>The parent is notified before its children.</b> This matches intuition,
	and also how the capture phase of DOM events works, for instance. Before a child
	gets its turn, its parent has already had a chance to prepare the ground.</li>

	<li><b>The parent can stop a child.</b> When a parent callback removes a child,
	the child's callback simply isn't called. The tree is walked live, not from a
	snapshot.</li>

	<li><b>Moves and reentrancy are handled.</b> If a callback moves a component
	into a container that comes up later, the set of already-processed nodes ensures
	it isn't processed twice. The crude boolean lock from 3.x has been replaced by
	precise per-object tracking.</li>

	<li><b>Deduplication stays.</b> The same callback-plus-specific-ancestor pair is
	called exactly once, even when several monitors point at the same ancestor.</li>
</ul>

<p>So this is a change that makes behavior more predictable and fixes the cases
where a callback used to fire on a component that was no longer in
the tree.</p>

<h2 id="toc-will-it-cause-a-bc-break">Will it cause a BC break?</h2>

<p>This is the only behavioral change, not just an API cleanup, so it deserves
an honest answer. I went through a number of libraries built on top of
Component Model and <b>found not a single case where the change in order broke
anything</b>. The reason is simple: a typical <code>attached</code> callback
only looks “up” at the ancestor that exists at that moment and deals with
itself. It assumes nothing about whether a sibling's or a child's callback has
already run.</p>

<p>In theory, though, it <b>can</b> break, in two situations:</p>

<ul>
	<li><b>You rely on the opposite order.</b> If you have two components that
	coordinate through <code>attached</code> callbacks, and the child used to write
	state that the parent read (or vice versa), the new order swaps that around. The
	parent now runs first and will see a different state than before. This is rare,
	because it requires deliberate communication between components across the tree
	through callbacks.</li>

	<li><b>You rely on the old buggy behavior.</b> If your code somehow depended on
	a child's callback firing even after the parent removed it during attachment,
	that callback now simply won't run.</li>
</ul>

<p>If you do none of this — and that's the vast majority of cases — the
upgrade will have no impact on you from this angle.</p>

<h2 id="toc-how-to-migrate">How to migrate</h2>

<p>For most projects the upgrade is trivial. Check whether any of the following
applies to you:</p>

<ul>
	<li>rewrite overridden <code>attached()</code> / <code>detached()</code> as
	<code>monitor($type, $attached, $detached)</code>,</li>

	<li>replace <code>getComponents(true)</code> with
	<code>getComponentTree()</code>,</li>

	<li>replace filtering <code>getComponents(false, Foo::class)</code> with
	<code>array_filter()</code> over <code>getComponents()</code> (or over
	<code>getComponentTree()</code> if you were filtering recursively),</li>

	<li>replace magic <code>$component-&gt;name</code> and friends with
	getters,</li>

	<li>rename the <code>NAME_SEPARATOR</code> constant to
	<code>NameSeparator</code>,</li>

	<li>if you override <code>addComponent()</code>, add the <code>: static</code>
	return type to the signature (it was previously only in phpDoc as
	<code>@return static</code>).</li>
</ul>

		]]></content:encoded>
		<comments>https://blog.nette.org/en/nette-component-model-4-0#comments</comments>
		<pubDate>Thu, 25 Jun 2026 23:30:01 +0200</pubDate>
		<guid isPermaLink="false">item548@http://blog.nette.org</guid>
	</item>
	<item>
		<title>A Quarter Century of CSRF. Now the Browser Finally Handles It</title>
		<link>https://blog.nette.org/en/quarter-century-of-csrf</link>
		<description>Cross-Site Request Forgery has been with us since at least the turn of the
millennium. The principle is primitive: a foreign website sends a request to
your server from the browser of an unsuspecting victim. The browser happily
attaches cookies to it, so the request looks like a legitimate action by a
logged-in user: a password change, a form submission, an account deletion.

And for a whole quarter century it was handled poorly, with crutches on the
application side.

The era of tokens and tricks

The classic defense: generate a random token, hide it in the form, store it
in the session and compare on submit. It works, but it&apos;s clumsy: the token has
to be in every form, it has to live somewhere, it expires, it fights with
caching and with AJAX. In Nette it meant calling
$form-&gt;addProtection() and, above all, never forgetting it
anywhere. A single form without a token = a hole.

The first big relief came with SameSite
cookies: a cookie can be marked with an attribute so the browser won&apos;t send
it with requests from foreign websites. Nette built its own protection on top of
that: it sent a special cookie _nss (formerly
nette-samesite) with SameSite=Strict, and the
isSameSite() method recognized from its presence that a request
hadn&apos;t come from a foreign website. A clever trick, but with inherent limits.
A cookie can only distinguish site, not origin: a request from
any subdomain looks the same as one straight from your website, so a subdomain
with user-generated content passes the check too. And it&apos;s still stateful
information, an extra cookie sent with every request.

Sec-Fetch headers:
A systemic solution at last!

And then browsers added Fetch Metadata: the Sec-Fetch-* headers,
with which they tell you on every request where it came from and why:

Sec-Fetch-Site: cross-site   (a foreign website initiated the request)
Sec-Fetch-Dest: document     (the target is a page navigation)
Sec-Fetch-User: ?1           (the user triggered the action themselves)


No token, no cookie, no state on the server. Headers with the
Sec- prefix can&apos;t be set by the browser for JavaScript or for
extensions. Outside the browser anyone can of course add them, but an
attacker&apos;s cURL doesn&apos;t have the victim&apos;s cookies, so for CSRF
it&apos;s irrelevant. The point is that the victim&apos;s browser always tells
the truth.

Nette deliberately waited with the rollout: the headers have existed since
2019, but Safari was the last to add them, only in version 16.4 (March 2023).
Adoption is finally broad enough, so the new API arrives.

isFrom(): say where a
request may come from

use Nette\Http\FetchSite;
use Nette\Http\FetchDest;

// did the request come from my origin?
$request-&gt;isFrom(FetchSite::SameOrigin);

// is it a page navigation triggered by the user themselves on my origin?
$request-&gt;isFrom(FetchSite::SameOrigin, FetchDest::Document, user: true);


The first parameter of the isFrom() method
corresponds to the Sec-Fetch-Site header (the
FetchSite enum), optionally you can narrow down the request target
(the FetchDest enum: document, image, script, fetch…) and verify
that the user triggered the action themselves.

Notice that unlike the cookie, you can now distinguish
SameOrigin from SameSite: same-site allows subdomains
too, same-origin requires an exact match of scheme, domain and port. For
sensitive actions choose FetchSite::SameOrigin.

The original isSameSite() remains functional, it&apos;s just
deprecated and internally delegates to isFrom().

Fallback for old iOS

One back door has stayed, at least for now: browsers without Sec-Fetch
support, which today mainly means Safari older than 16.4. And because on iOS
every browser is just a layer over the system WebKit, this affects older iPhones
and iPads regardless of which browser runs on them.

In that case the good old _nss cookie steps in. Nette now sends
it only to browsers that didn&apos;t send the Sec-Fetch-Site header,
everywhere else the protection already runs completely without cookies.

Nette does it for you
automatically

Maybe you don&apos;t even know it: forms in Nette have been defending themselves
for a long time already. Since nette/forms 3.1 a POST coming from a foreign
website isn&apos;t accepted at all unless you explicitly allow it via
$form-&gt;allowCrossOrigin(). And signals in nette/application are
automatically protected, as if they had the
#[Requires(sameOrigin: true)] attribute. Both have so far
internally relied on isSameSite(), that is on the _nss
cookie.

What changes now:


	Right away with nette/http 3.4 isSameSite() switches
	internally to the Sec-Fetch headers, so the existing automatic protection of
	forms and signals gets more precise without a single change to your code. One
	visible change in behavior: direct navigation (a bookmark, a manually typed
	address, a link from an email) is no longer considered same-site; previously it
	passed thanks to the strict cookie. If some signal of yours relies on action
	links in emails, mark it #[Requires(sameOrigin: false)].

	With nette/forms 3.3 and nette/application 3.3 both switch from
	isSameSite() to isFrom(FetchSite::SameOrigin) and the
	protection gets a touch stricter still: requests from subdomains no longer pass.
	The sameOrigin attribute will thus for the first time check the
	actual origin, not just the site.


The end of addProtection()

And that brings us to the point: you actually don&apos;t need
$form-&gt;addProtection() anymore today, the automatic protection
covers the same thing. The last difference, protection against requests from
subdomains, is erased by the switch to same-origin in forms 3.3. Tokens in the
session, hidden fields and wondering whether we forgot one somewhere can all
retire.

In practice this means: upgrade nette/http to 3.4, skip
addProtection() on new forms and start removing it from
existing ones.

It only took a quarter century.

The new API arrives with nette/http 3.4.0,
forms 3.3 and application 3.3. The same release also adds protection against SSRF attacks.
</description>
		<content:encoded><![CDATA[
		<p>Cross-Site Request Forgery has been with us since at least the turn of the
millennium. The principle is primitive: a foreign website sends a request to
your server from the browser of an unsuspecting victim. The browser happily
attaches cookies to it, so the request looks like a legitimate action by a
logged-in user: a password change, a form submission, an account deletion.</p>

<p>And for a whole quarter century it was handled poorly, with crutches on the
application side.</p>

<h2 id="toc-the-era-of-tokens-and-tricks">The era of tokens and tricks</h2>

<p>The classic defense: generate a random token, hide it in the form, store it
in the session and compare on submit. It works, but it's clumsy: the token has
to be in every form, it has to live somewhere, it expires, it fights with
caching and with AJAX. In Nette it meant calling
<code>$form-&gt;addProtection()</code> and, above all, never forgetting it
anywhere. A single form without a token = a hole.</p>

<p>The first big relief came with <a
href="https://phpfashion.com/en/what-are-samesite-cookies-and-why-do-we-need-them">SameSite
cookies</a>: a cookie can be marked with an attribute so the browser won't send
it with requests from foreign websites. Nette built its own protection on top of
that: it sent a special cookie <code>_nss</code> (formerly
<code>nette-samesite</code>) with <code>SameSite=Strict</code>, and the
<code>isSameSite()</code> method recognized from its presence that a request
hadn't come from a foreign website. A clever trick, but with inherent limits.
A cookie can only distinguish <i>site</i>, not <i>origin</i>: a request from
any subdomain looks the same as one straight from your website, so a subdomain
with user-generated content passes the check too. And it's still stateful
information, an extra cookie sent with every request.</p>

<h2 id="toc-sec-fetch-headers-a-systemic-solution-at-last">Sec-Fetch headers:
A systemic solution at last!</h2>

<p>And then browsers added Fetch Metadata: the <code>Sec-Fetch-*</code> headers,
with which they tell you on every request where it came from and why:</p>

<pre><code>Sec-Fetch-Site: cross-site   (a foreign website initiated the request)
Sec-Fetch-Dest: document     (the target is a page navigation)
Sec-Fetch-User: ?1           (the user triggered the action themselves)
</code></pre>

<p>No token, no cookie, no state on the server. Headers with the
<code>Sec-</code> prefix can't be set by the browser for JavaScript or for
extensions. Outside the browser anyone can of course add them, but an
attacker's cURL doesn't have the victim's cookies, so for CSRF
it's irrelevant. The point is that the victim's browser always tells
the truth.</p>

<p>Nette deliberately waited with the rollout: the headers have existed since
2019, but Safari was the last to add them, only in version 16.4 (March 2023).
Adoption is finally broad enough, so the new API arrives.</p>

<h2 id="toc-isfrom-say-where-a-request-may-come-from">isFrom(): say where a
request may come from</h2>

<pre
class="language-php"><code>use Nette\Http\FetchSite;
use Nette\Http\FetchDest;

// did the request come from my origin?
$request-&gt;isFrom(FetchSite::SameOrigin);

// is it a page navigation triggered by the user themselves on my origin?
$request-&gt;isFrom(FetchSite::SameOrigin, FetchDest::Document, user: true);
</code></pre>

<p>The first parameter of the <a
href="https://doc.nette.org/en/http/request#toc-isfrom">isFrom() method</a>
corresponds to the <code>Sec-Fetch-Site</code> header (the
<code>FetchSite</code> enum), optionally you can narrow down the request target
(the <code>FetchDest</code> enum: document, image, script, fetch…) and verify
that the user triggered the action themselves.</p>

<p>Notice that unlike the cookie, you can now distinguish
<code>SameOrigin</code> from <code>SameSite</code>: same-site allows subdomains
too, same-origin requires an exact match of scheme, domain and port. For
sensitive actions choose <code>FetchSite::SameOrigin</code>.</p>

<p>The original <code>isSameSite()</code> remains functional, it's just
deprecated and internally delegates to <code>isFrom()</code>.</p>

<h2 id="toc-fallback-for-old-ios">Fallback for old iOS</h2>

<p>One back door has stayed, at least for now: browsers without Sec-Fetch
support, which today mainly means Safari older than 16.4. And because on iOS
every browser is just a layer over the system WebKit, this affects older iPhones
and iPads regardless of which browser runs on them.</p>

<p>In that case the good old <code>_nss</code> cookie steps in. Nette now sends
it only to browsers that didn't send the <code>Sec-Fetch-Site</code> header,
everywhere else the protection already runs completely without cookies.</p>

<h2 id="toc-nette-does-it-for-you-automatically">Nette does it for you
automatically</h2>

<p>Maybe you don't even know it: forms in Nette have been defending themselves
for a long time already. Since nette/forms 3.1 a POST coming from a foreign
website isn't accepted at all unless you explicitly allow it via
<code>$form-&gt;allowCrossOrigin()</code>. And signals in nette/application are
automatically protected, as if they had the
<code>#[Requires(sameOrigin: true)]</code> attribute. Both have so far
internally relied on <code>isSameSite()</code>, that is on the <code>_nss</code>
cookie.</p>

<p>What changes now:</p>

<ul>
	<li><b>Right away with nette/http 3.4</b> <code>isSameSite()</code> switches
	internally to the Sec-Fetch headers, so the existing automatic protection of
	forms and signals gets more precise without a single change to your code. One
	visible change in behavior: direct navigation (a bookmark, a manually typed
	address, a link from an email) is no longer considered same-site; previously it
	passed thanks to the strict cookie. If some signal of yours relies on action
	links in emails, mark it <code>#[Requires(sameOrigin: false)]</code>.</li>

	<li><b>With nette/forms 3.3 and nette/application 3.3</b> both switch from
	<code>isSameSite()</code> to <code>isFrom(FetchSite::SameOrigin)</code> and the
	protection gets a touch stricter still: requests from subdomains no longer pass.
	The <code>sameOrigin</code> attribute will thus for the first time check the
	actual origin, not just the site.</li>
</ul>

<h2 id="toc-the-end-of-addprotection">The end of addProtection()</h2>

<p>And that brings us to the point: you actually don't need
<code>$form-&gt;addProtection()</code> anymore today, the automatic protection
covers the same thing. The last difference, protection against requests from
subdomains, is erased by the switch to same-origin in forms 3.3. Tokens in the
session, hidden fields and wondering whether we forgot one somewhere can all
retire.</p>

<p>In practice this means: upgrade nette/http to 3.4, skip
<code>addProtection()</code> on new forms and start removing it from
existing ones.</p>

<p>It only took a quarter century.</p>

<p>The new API arrives with <a
href="https://github.com/nette/http/releases/tag/v3.4.0">nette/http 3.4.0</a>,
forms 3.3 and application 3.3. The same release also adds <a
href="https://blog.nette.org/en/nette-http-ssrf-protection">protection against SSRF attacks</a>.</p>

		]]></content:encoded>
		<comments>https://blog.nette.org/en/quarter-century-of-csrf#comments</comments>
		<pubDate>Sat, 13 Jun 2026 15:19:00 +0200</pubDate>
		<guid isPermaLink="false">item546@http://blog.nette.org</guid>
	</item>
	<item>
		<title>Nette Http 3.4.0 Brings Protection Against SSRF Attacks</title>
		<link>https://blog.nette.org/en/nette-http-ssrf-protection</link>
		<description>A user avatar. An image generated by an MCP server. An OG preview in a
comment. A webhook callback. An OAuth redirect. An RSS feed import. Whenever
your application fetches a URL submitted by a user (or an AI assistant), it
becomes a target for Server-Side Request Forgery (SSRF), one of the OWASP
Top 10 vulnerabilities.

Nette/Http 3.4.0 introduces two new classes, UrlValidator and
IPAddress, that
solve this problem in a single line.

How SSRF Attacks Work
in Cloud Environments

A classic SSRF attack looks innocent:

https://169.254.169.254/latest/meta-data/iam/security-credentials/


The address 169.254.169.254 is a cloud metadata endpoint,
reachable only from inside an AWS, Azure or GCP instance. An attacker can&apos;t
reach it from the outside, but your server can. If the application blindly
fetches that URL (say, as a “user profile picture”), the attacker gets back
active IAM credentials.

Other popular targets: https://192.168.1.1/admin/ (an internal
router), http://localhost:6379/ (Redis with no auth),
https://10.0.5.7/internal-api/ (anything on your LAN).

A naive “is it https://?” check isn&apos;t enough. You need to
know which IP addresses the URL actually points to, not how it looks.
That means resolving the name to IP addresses via DNS, checking them against a
list of forbidden ranges and handling gotchas like IPv4-mapped IPv6 or DNS
rebinding… it quickly turns into fifty lines of code that every project solves
a little differently, usually wrong.

With the rise of MCP servers and AI integrations, the attack surface has
grown dramatically. The AI receives a URL from the user and passes it to a tool
to fetch. The server downloads the URL. The AI has no intuition for “this is
an internal endpoint”, so without this protection an AI agent makes an ideal
target for an attack.

How to Validate URLs in PHP

use Nette\Http\UrlValidator;

if (!(new UrlValidator)-&gt;allows($userUrl)) {
	return; // unsafe URL
}
// now it&apos;s safe to fetch


The default is strict: https only, port 443 only, the hostname
must resolve exclusively to public IP addresses. It blocks loopback,
private ranges, link-local including cloud metadata, multicast and
IANA-reserved.

When you need different rules, you configure them in the constructor:

// Internal monitoring needs the LAN (http and any port)
new UrlValidator(schemes: [&apos;http&apos;, &apos;https&apos;], ports: null, allowPrivateIps: true);

// OAuth only to known partners
new UrlValidator(
	hostAllowlist: [&apos;*.partner1.com&apos;, &apos;*.partner2.com&apos;],
);


The wildcard *.example.com matches subdomains of any depth. Add
the apex domain separately.

Preventing DNS Rebinding
Attacks in PHP

Between allows() and the actual fetch there&apos;s a short window
where an attacker who controls the host&apos;s DNS switches the A record from a
public to an internal IP. Validation passes, but the request goes elsewhere (a
DNS rebinding attack).

For full defense there&apos;s getResolvedIPs(). It works just like
allows(): for an unsafe URL it returns [], for a safe
one an array of validated addresses. You then pass those to cURL via
CURLOPT_RESOLVE:

$ips = (new UrlValidator)-&gt;getResolvedIPs($url);
if (!$ips) {
	return; // unsafe
}

$ch = curl_init($url);
$host = parse_url($url, PHP_URL_HOST);
curl_setopt($ch, CURLOPT_RESOLVE, [&quot;$host:443:&quot; . implode(&apos;,&apos;, $ips)]);


cURL no longer makes a new DNS query, the connection goes exactly to the IPs
that passed validation. The window for DNS rebinding closes.

Validating IPv4 and IPv6
Addresses in PHP

Alongside comes IPAddress, an immutable object for working with
IPv4 and IPv6 addresses:

use Nette\Http\IPAddress;

$ip = new IPAddress(&apos;169.254.169.254&apos;);
$ip-&gt;isLinkLocal();                // true (cloud metadata)
$ip-&gt;isInRange(&apos;192.168.0.0/16&apos;);  // false


Full support for IPv4-mapped IPv6: ::ffff:127.0.0.1 evaluates as
loopback. A naive check doesn&apos;t recognize this form as loopback, so an attacker
easily bypasses its protection through it.

Usable independently of UrlValidator anywhere you work with IPs:
rate limiting, audit logs, trusted proxy validation. The static
IPAddress::isValid() as a quick checker,
IPAddress::tryFrom() as a factory returning ?self
without an exception.



What this pair doesn&apos;t solve: HTTP redirects (your client should have
them disabled, or revalidate every hop) and attacks targeting the content of the
fetched response itself. Validating the address is not validating the
content.

What else 3.4 brings

SSRF protection is the flagship, but version 3.4 brings more:


	The End of CSRF Tokens: The new Request::isFrom() method
	identifies the origin of a request using Sec-Fetch-* headers, and
	this is such a big topic that we’ve dedicated a separate article to it.

	More modern cookies: setCookie() now sends the
	Max-Age attribute, supports partitioned cookies (CHIPS) via the
	partitioned: true parameter and automatically enforces
	Secure for SameSite=None or partitioned cookies.

	The SameSite enum: instead of the string constants
	IResponse::SameSiteLax and friends, you now write
	SameSite::Lax. Both setCookie() and
	Session::setCookieParameters() accept it, the old constants are
	deprecated.

	Expiration the same everywhere: setCookie(),
	Session::setExpiration() and section expiration all interpret the
	value the same way: a number is a relative count of seconds, a string is an
	interval (&apos;20 minutes&apos;) or a date; setCookie()
	additionally accepts DateTimeInterface. Passing an absolute UNIX
	timestamp is deprecated, and a session cookie is now requested with the value
	null instead of the former 0.

	detectLanguage() understands the wildcard: the
	Accept-Language header may contain * (mainly sent by
	API clients and bots). Previously the method ignored it and returned
	null, now it returns one of the languages the application
	offers.

	The library now requires PHP 8.3+, the deprecated
	Request::getRemoteHost() method returns null, and the
	long-deprecated UserStorage class has been removed.


Everything described above ships with nette/http
3.4.0.
</description>
		<content:encoded><![CDATA[
		<p>A user avatar. An image generated by an MCP server. An OG preview in a
comment. A webhook callback. An OAuth redirect. An RSS feed import. Whenever
your application fetches a URL submitted by a user (or an AI assistant), it
becomes a target for <b>Server-Side Request Forgery (SSRF)</b>, one of the OWASP
Top 10 vulnerabilities.</p>

<p>Nette/Http 3.4.0 introduces two new classes, <a
href="https://doc.nette.org/en/http/ssrf#toc-urlvalidator">UrlValidator</a> and
<a href="https://doc.nette.org/en/http/ssrf#toc-ipaddress">IPAddress</a>, that
solve this problem in a single line.</p>

<h2 id="toc-how-ssrf-attacks-work-in-cloud-environments">How SSRF Attacks Work
in Cloud Environments</h2>

<p>A classic SSRF attack looks innocent:</p>

<pre><code>https://169.254.169.254/latest/meta-data/iam/security-credentials/
</code></pre>

<p>The address <code>169.254.169.254</code> is a cloud metadata endpoint,
reachable only from inside an AWS, Azure or GCP instance. An attacker can't
reach it from the outside, but your server can. If the application blindly
fetches that URL (say, as a “user profile picture”), the attacker gets back
active IAM credentials.</p>

<p>Other popular targets: <code>https://192.168.1.1/admin/</code> (an internal
router), <code>http://localhost:6379/</code> (Redis with no auth),
<code>https://10.0.5.7/internal-api/</code> (anything on your LAN).</p>

<p>A naive “is it <code>https://</code>?” check isn't enough. You need to
know <b>which IP addresses the URL actually points to</b>, not how it looks.
That means resolving the name to IP addresses via DNS, checking them against a
list of forbidden ranges and handling gotchas like IPv4-mapped IPv6 or DNS
rebinding… it quickly turns into fifty lines of code that every project solves
a little differently, usually wrong.</p>

<p>With the rise of MCP servers and AI integrations, the attack surface has
grown dramatically. The AI receives a URL from the user and passes it to a tool
to fetch. The server downloads the URL. The AI has no intuition for “this is
an internal endpoint”, so without this protection an AI agent makes an ideal
target for an attack.</p>

<h2 id="toc-how-to-validate-urls-in-php">How to Validate URLs in PHP</h2>

<pre
class="language-php"><code>use Nette\Http\UrlValidator;

if (!(new UrlValidator)-&gt;allows($userUrl)) {
	return; // unsafe URL
}
// now it&#039;s safe to fetch
</code></pre>

<p>The default is strict: <code>https</code> only, port 443 only, the hostname
must resolve <b>exclusively</b> to public IP addresses. It blocks loopback,
private ranges, link-local including cloud metadata, multicast and
IANA-reserved.</p>

<p>When you need different rules, you configure them in the constructor:</p>

<pre
class="language-php"><code>// Internal monitoring needs the LAN (http and any port)
new UrlValidator(schemes: [&#039;http&#039;, &#039;https&#039;], ports: null, allowPrivateIps: true);

// OAuth only to known partners
new UrlValidator(
	hostAllowlist: [&#039;*.partner1.com&#039;, &#039;*.partner2.com&#039;],
);
</code></pre>

<p>The wildcard <code>*.example.com</code> matches subdomains of any depth. Add
the apex domain separately.</p>

<h2 id="toc-preventing-dns-rebinding-attacks-in-php">Preventing DNS Rebinding
Attacks in PHP</h2>

<p>Between <code>allows()</code> and the actual fetch there's a short window
where an attacker who controls the host's DNS switches the A record from a
public to an internal IP. Validation passes, but the request goes elsewhere (a
DNS rebinding attack).</p>

<p>For full defense there's <code>getResolvedIPs()</code>. It works just like
<code>allows()</code>: for an unsafe URL it returns <code>[]</code>, for a safe
one an array of validated addresses. You then pass those to cURL via
<code>CURLOPT_RESOLVE</code>:</p>

<pre
class="language-php"><code>$ips = (new UrlValidator)-&gt;getResolvedIPs($url);
if (!$ips) {
	return; // unsafe
}

$ch = curl_init($url);
$host = parse_url($url, PHP_URL_HOST);
curl_setopt($ch, CURLOPT_RESOLVE, [&quot;$host:443:&quot; . implode(&#039;,&#039;, $ips)]);
</code></pre>

<p>cURL no longer makes a new DNS query, the connection goes exactly to the IPs
that passed validation. The window for DNS rebinding closes.</p>

<h2 id="toc-validating-ipv4-and-ipv6-addresses-in-php">Validating IPv4 and IPv6
Addresses in PHP</h2>

<p>Alongside comes <code>IPAddress</code>, an immutable object for working with
IPv4 and IPv6 addresses:</p>

<pre
class="language-php"><code>use Nette\Http\IPAddress;

$ip = new IPAddress(&#039;169.254.169.254&#039;);
$ip-&gt;isLinkLocal();                // true (cloud metadata)
$ip-&gt;isInRange(&#039;192.168.0.0/16&#039;);  // false
</code></pre>

<p>Full support for IPv4-mapped IPv6: <code>::ffff:127.0.0.1</code> evaluates as
loopback. A naive check doesn't recognize this form as loopback, so an attacker
easily bypasses its protection through it.</p>

<p>Usable independently of <code>UrlValidator</code> anywhere you work with IPs:
rate limiting, audit logs, trusted proxy validation. The static
<code>IPAddress::isValid()</code> as a quick checker,
<code>IPAddress::tryFrom()</code> as a factory returning <code>?self</code>
without an exception.</p>

<hr>

<p>What this pair <b>doesn't</b> solve: HTTP redirects (your client should have
them disabled, or revalidate every hop) and attacks targeting the content of the
fetched response itself. Validating the address is not validating the
content.</p>

<h2 id="toc-what-else-3-4-brings">What else 3.4 brings</h2>

<p>SSRF protection is the flagship, but version 3.4 brings more:</p>

<ul>
	<li><b>The End of CSRF Tokens</b>: The new <code>Request::isFrom()</code> method
	identifies the origin of a request using <code>Sec-Fetch-*</code> headers, and
	this is such a big topic that we’ve dedicated a <a
	href="https://blog.nette.org/en/quarter-century-of-csrf">separate article</a> to it.</li>

	<li><b>More modern cookies</b>: <code>setCookie()</code> now sends the
	<code>Max-Age</code> attribute, supports partitioned cookies (CHIPS) via the
	<code>partitioned: true</code> parameter and automatically enforces
	<code>Secure</code> for <code>SameSite=None</code> or partitioned cookies.</li>

	<li><b>The <code>SameSite</code> enum</b>: instead of the string constants
	<code>IResponse::SameSiteLax</code> and friends, you now write
	<code>SameSite::Lax</code>. Both <code>setCookie()</code> and
	<code>Session::setCookieParameters()</code> accept it, the old constants are
	deprecated.</li>

	<li><b>Expiration the same everywhere</b>: <code>setCookie()</code>,
	<code>Session::setExpiration()</code> and section expiration all interpret the
	value the same way: a number is a relative count of seconds, a string is an
	interval (<code>'20 minutes'</code>) or a date; <code>setCookie()</code>
	additionally accepts <code>DateTimeInterface</code>. Passing an absolute UNIX
	timestamp is deprecated, and a session cookie is now requested with the value
	<code>null</code> instead of the former <code>0</code>.</li>

	<li><b><code>detectLanguage()</code> understands the wildcard</b>: the
	<code>Accept-Language</code> header may contain <code>*</code> (mainly sent by
	API clients and bots). Previously the method ignored it and returned
	<code>null</code>, now it returns one of the languages the application
	offers.</li>

	<li>The library now requires <b>PHP 8.3+</b>, the deprecated
	<code>Request::getRemoteHost()</code> method returns <code>null</code>, and the
	long-deprecated <code>UserStorage</code> class has been removed.</li>
</ul>

<p>Everything described above ships with <a
href="https://github.com/nette/http/releases/tag/v3.4.0">nette/http
3.4.0</a>.</p>

		]]></content:encoded>
		<comments>https://blog.nette.org/en/nette-http-ssrf-protection#comments</comments>
		<pubDate>Sat, 13 Jun 2026 14:30:00 +0200</pubDate>
		<guid isPermaLink="false">item544@http://blog.nette.org</guid>
	</item>
	<item>
		<title>Tracy Learned to Speak with AI Agents</title>
		<link>https://blog.nette.org/en/tracy-debugger-ai-agents</link>
		<description>Tracy learned a new dialect. When an AI agent sits on the other side, it gets
structured markdown straight into the JS console alongside the usual red screen.
And next to every .html exception in the log/ folder
there&apos;s now a .md sibling.

A human developer still sees BlueScreen, Tracy Bar and dumps in their
familiar form. But when there&apos;s an AI agent in front of the monitor instead of
a human, one that drives your app through a browser, visual tools aren&apos;t built
for it. The carefully
designed red screen, Tracy Bar panels with expandable tables, dumps with
color highlighting – all of that is optimized for the human eye. The agent
often can&apos;t pull out what matters, or it tries to parse the HTML, which is
inefficient and unreliable.

The browser console, on the other hand, is a structured channel an agent
reads with ease. And markdown is an LLM&apos;s native tongue. So Tracy 2.12 adds a
second, parallel track: a human still sees what they&apos;ve always seen, and the
agent gets a markdown version of the same request straight into
console.log() and console.error(). Nothing is
overwritten, nothing is hidden, everything is just added on top.

Two scenarios in practice

Tracy speaks markdown to two different audiences.

1. Development with an agent in the browser. An agent controlled via
Chrome DevTools MCP, Playwright or Puppeteer opens your application. Tracy
detects it and starts sending markdown to the console.

2. Batch fixing of production errors. Your production log is full of
exception-*.html files. The old way: click, read, hunt for the
pattern, fix, next file. With the markdown siblings, things work differently:
you take the whole folder, hand it to an agent with the instructions “go
through these reports and fix what you find”, and it works through them one
by one.

1. Development with an
agent in the browser

This is only active when a browser-driving agent is detected in debug mode.
Here&apos;s what actually lands in the console:

BlueScreen. On an uncaught exception, Tracy sends a markdown version
into the console alongside the standard red screen: the exception, stack trace,
variable values, dump of $_GET / $_POST / $_COOKIE. It works for
synchronous rendering and for AJAX errors.

Tracy Bar. The debug bar in the corner of the screen sends a markdown
summary of selected panels into the console. The SQL panel with the number of
queries and their times, the Errors panel with warnings, the Dumps panel with
plain text dumps captured by bdump().

Dumps. When you call dump($var) in your code, a plain
text variant gets sent to the console alongside the regular HTML output. Dumps
no longer end up buried in the HTML page.

But watch out: an agent doesn&apos;t know on its own that it should be looking in
the console. It will browse the rendered HTML, try to parse the colorful
BlueScreen and guess what actually happened. That&apos;s what the
tracy-debugging skill is for, a guide written directly for the
agent. It tells the agent: after every request, call
list_console_messages(), that&apos;s where you&apos;ll find Tracy Bar and
BlueScreen in markdown, this is how the SQL panel looks, this is the stack
trace, this is how to read dumps. The skill is part of the official Nette plugin for Claude Code.

2. Batch fixing of production
errors

Whenever Tracy logs an exception into a log/exception-*.html
file, it simultaneously writes a .md sibling next to it with the
same content in markdown.

For a human peeking into the directory, nothing changes; the .md
just sits next to the .html and you pick which one you want to
open. It only starts making sense when you hand the directory&apos;s contents to
an agent.

It&apos;s worth writing your own skill for this, telling the agent how to
proceed: compare each exception with the current code (the bug may already be
fixed), group related reports, and present a fix plan for approval before
applying it. Instead of hundreds of HTML files to plow through by hand, you turn
a folder of error reports into input for a single batch action.

For custom panel authors:
getAgentInfo()

If you have your own IBarPanel, say a database panel or a
profiler, and you want to send the agent a markdown version of its content, add
a getAgentInfo(): ?string method to the panel class:

class MyDatabasePanel implements Tracy\IBarPanel
{
	public function getTab(): string { /* ... */ }
	public function getPanel(): string { /* ... */ }

	public function getAgentInfo(): ?string
	{
		return &quot;## Database\n\n- Queries: {$this-&gt;count}\n- Total time: {$this-&gt;time} ms\n&quot;;
	}
}


Tracy puts the returned markdown into the Tracy Bar output for the agent.
When the method is missing or returns null, the panel is skipped in
the markdown output.

How the agent is detected

Let&apos;s peek under the hood. The key to detection is the JavaScript property
navigator.webdriver. Both Chrome and Firefox set it to
true whenever the browser runs under automation: WebDriver, Chrome
DevTools Protocol, Playwright, Puppeteer. In practice this covers common browser
MCP servers, such as Chrome DevTools MCP by Google, Playwright MCP by Microsoft,
mcp-chrome, servers built on top of Puppeteer, or Browser Use. So just spin up
any of them in Claude Code and Tracy 2.12 will recognize it on its own.

Mechanically it works like this: Tracy Bar&apos;s JavaScript reads
navigator.webdriver and, if it&apos;s true, sets the cookie
tracy-webdriver=1. PHP then checks this cookie before sending the
markdown output. If you want to see the markdown output from a regular browser,
say when debugging your own integration, just set the cookie manually in
devtools.

Give it a try

Tracy learned a new dialect, and we&apos;ll keep pushing in this direction. The
future of development belongs to agents that both write and fix applications,
and we&apos;re looking for the best way to talk to them. Markdown in the console,
.md siblings in the log, getAgentInfo() on panels:
that&apos;s the first round. Time will tell what works, where it gets stuck, which
way to head next.

Install Tracy 2.12 via composer require tracy/tracy:^2.12 and
give it a spin, especially those of you running Claude Code with Chrome MCP, or
Playwright/Puppeteer with agents. Feedback most welcome.
</description>
		<content:encoded><![CDATA[
		<p>Tracy learned a new dialect. When an AI agent sits on the other side, it gets
structured markdown straight into the JS console alongside the usual red screen.
And next to every <code>.html</code> exception in the <code>log/</code> folder
there's now a <code>.md</code> sibling.</p>

<p>A human developer still sees BlueScreen, Tracy Bar and dumps in their
familiar form. But when there's an AI agent in front of the monitor instead of
a human, one that drives your app through a browser, visual tools aren't built
for it. The <a href="tracy-2-9-and-evolution-of-the-iconic-screen">carefully
designed red screen</a>, Tracy Bar panels with expandable tables, dumps with
color highlighting – all of that is optimized for the human eye. The agent
often can't pull out what matters, or it tries to parse the HTML, which is
inefficient and unreliable.</p>

<p>The browser console, on the other hand, is a structured channel an agent
reads with ease. And markdown is an LLM's native tongue. So Tracy 2.12 adds a
second, parallel track: a human still sees what they've always seen, and the
agent gets a markdown version of the same request straight into
<code>console.log()</code> and <code>console.error()</code>. Nothing is
overwritten, nothing is hidden, everything is just added on top.</p>

<h2 id="toc-two-scenarios-in-practice">Two scenarios in practice</h2>

<p>Tracy speaks markdown to two different audiences.</p>

<p><b>1. Development with an agent in the browser.</b> An agent controlled via
Chrome DevTools MCP, Playwright or Puppeteer opens your application. Tracy
detects it and starts sending markdown to the console.</p>

<p><b>2. Batch fixing of production errors.</b> Your production log is full of
<code>exception-*.html</code> files. The old way: click, read, hunt for the
pattern, fix, next file. With the markdown siblings, things work differently:
you take the whole folder, hand it to an agent with the instructions “go
through these reports and fix what you find”, and it works through them one
by one.</p>

<h2 id="toc-1-development-with-an-agent-in-the-browser">1. Development with an
agent in the browser</h2>

<p>This is only active when a browser-driving agent is detected in debug mode.
Here's what actually lands in the console:</p>

<p><b>BlueScreen.</b> On an uncaught exception, Tracy sends a markdown version
into the console alongside the standard red screen: the exception, stack trace,
variable values, dump of <code>$_GET / $_POST / $_COOKIE</code>. It works for
synchronous rendering and for AJAX errors.</p>

<p><b>Tracy Bar.</b> The debug bar in the corner of the screen sends a markdown
summary of selected panels into the console. The SQL panel with the number of
queries and their times, the Errors panel with warnings, the Dumps panel with
plain text dumps captured by <code>bdump()</code>.</p>

<p><b>Dumps.</b> When you call <code>dump($var)</code> in your code, a plain
text variant gets sent to the console alongside the regular HTML output. Dumps
no longer end up buried in the HTML page.</p>

<p>But watch out: an agent doesn't know on its own that it should be looking in
the console. It will browse the rendered HTML, try to parse the colorful
BlueScreen and guess what actually happened. That's what the
<code>tracy-debugging</code> skill is for, a guide written directly for the
agent. It tells the agent: after every request, call
<code>list_console_messages()</code>, that's where you'll find Tracy Bar and
BlueScreen in markdown, this is how the SQL panel looks, this is the stack
trace, this is how to read dumps. The skill is part of the official <a
href="https://ai.nette.org/en/claude-code">Nette plugin for Claude Code</a>.</p>

<h2 id="toc-2-batch-fixing-of-production-errors">2. Batch fixing of production
errors</h2>

<p>Whenever Tracy logs an exception into a <code>log/exception-*.html</code>
file, it simultaneously writes a <code>.md</code> sibling next to it with the
same content in markdown.</p>

<p>For a human peeking into the directory, nothing changes; the <code>.md</code>
just sits next to the <code>.html</code> and you pick which one you want to
open. It only starts making sense when you hand the directory's contents to
an agent.</p>

<p>It's worth writing your own skill for this, telling the agent how to
proceed: compare each exception with the current code (the bug may already be
fixed), group related reports, and present a fix plan for approval before
applying it. Instead of hundreds of HTML files to plow through by hand, you turn
a folder of error reports into input for a single batch action.</p>

<h2 id="toc-for-custom-panel-authors-getagentinfo">For custom panel authors:
<code>getAgentInfo()</code></h2>

<p>If you have your own <code>IBarPanel</code>, say a database panel or a
profiler, and you want to send the agent a markdown version of its content, add
a <code>getAgentInfo(): ?string</code> method to the panel class:</p>

<pre
class="language-php"><code>class MyDatabasePanel implements Tracy\IBarPanel
{
	public function getTab(): string { /* ... */ }
	public function getPanel(): string { /* ... */ }

	public function getAgentInfo(): ?string
	{
		return &quot;## Database\n\n- Queries: {$this-&gt;count}\n- Total time: {$this-&gt;time} ms\n&quot;;
	}
}
</code></pre>

<p>Tracy puts the returned markdown into the Tracy Bar output for the agent.
When the method is missing or returns <code>null</code>, the panel is skipped in
the markdown output.</p>

<h2 id="toc-how-the-agent-is-detected">How the agent is detected</h2>

<p>Let's peek under the hood. The key to detection is the JavaScript property
<code>navigator.webdriver</code>. Both Chrome and Firefox set it to
<code>true</code> whenever the browser runs under automation: WebDriver, Chrome
DevTools Protocol, Playwright, Puppeteer. In practice this covers common browser
MCP servers, such as Chrome DevTools MCP by Google, Playwright MCP by Microsoft,
mcp-chrome, servers built on top of Puppeteer, or Browser Use. So just spin up
any of them in Claude Code and Tracy 2.12 will recognize it on its own.</p>

<p>Mechanically it works like this: Tracy Bar's JavaScript reads
<code>navigator.webdriver</code> and, if it's <code>true</code>, sets the cookie
<code>tracy-webdriver=1</code>. PHP then checks this cookie before sending the
markdown output. If you want to see the markdown output from a regular browser,
say when debugging your own integration, just set the cookie manually in
devtools.</p>

<h2 id="toc-give-it-a-try">Give it a try</h2>

<p>Tracy learned a new dialect, and we'll keep pushing in this direction. The
future of development belongs to agents that both write and fix applications,
and we're looking for the best way to talk to them. Markdown in the console,
<code>.md</code> siblings in the log, <code>getAgentInfo()</code> on panels:
that's the first round. Time will tell what works, where it gets stuck, which
way to head next.</p>

<p>Install Tracy 2.12 via <code>composer require tracy/tracy:^2.12</code> and
give it a spin, especially those of you running Claude Code with Chrome MCP, or
Playwright/Puppeteer with agents. Feedback most welcome.</p>

		]]></content:encoded>
		<comments>https://blog.nette.org/en/tracy-debugger-ai-agents#comments</comments>
		<pubDate>Mon, 25 May 2026 19:43:00 +0200</pubDate>
		<guid isPermaLink="false">item542@http://blog.nette.org</guid>
	</item>
	<item>
		<title>Process: running external programs from PHP without the pain</title>
		<link>https://blog.nette.org/en/running-external-programs-in-php</link>
		<description>Running an external program from PHP and reading what it printed?
shell_exec(&apos;git pull&apos;) and you&apos;re done. But that only covers the
simplest case. The moment you need more — the exit code, errors kept separate
from the regular output, a user-supplied argument passed safely, a timeout —
shell_exec() runs out of road. And proc_open(), which
can do all of it, has an API so unwelcoming that most people just avoid it.

Nette Utils 4.1.4 adds the Nette\Utils\Process class that fills
that gap between the two. You start a process, then you ask it questions: is it
still running? what did it print? how did it end? And it takes care of the
pipes, the polling loops, and the differences between operating systems
for you.

How to
Execute a Command and Get the Exit Code in PHP

Want to run git pull and know whether it passed?

use Nette\Utils\Process;

Process::runExecutable(&apos;git&apos;, [&apos;pull&apos;])-&gt;ensureSuccess();


That single line runs git pull, waits for it to finish, and
throws ProcessFailedException if the exit code wasn&apos;t zero. No
juggling exec() and $retval, no
is_resource(), no loop.

And when you want the output?

$process = Process::runExecutable(&apos;git&apos;, [&apos;log&apos;, &apos;-1&apos;, &apos;--format=%H&apos;]);

echo $process-&gt;getStdOutput();  // standard output
echo $process-&gt;getStdError();   // error output, separately
echo $process-&gt;getExitCode();   // 0


getStdOutput() waits for the program to finish and returns
everything it wrote to standard output. The error output you get separately,
which shell_exec() can&apos;t do. The exit code too. And unlike
PHP&apos;s native functions, the class doesn&apos;t return false on errors,
it throws exceptions, so you won&apos;t miss a failure. (Need to send the program
some input? Pass stdin: &apos;data&apos;, or null and feed it
incrementally via writeStdInput().)

runExecutable
vs. runCommand (Preventing Shell Injection)

The class offers two ways to start a process, and the difference is not
cosmetic.

runExecutable() runs one specific program with a list of
arguments. The arguments are handed to the program directly. No shell ever
touches them, so you don&apos;t have to escape anything and, more importantly,
there&apos;s no risk of shell injection:

$file = $_GET[&apos;file&apos;]; // could be anything, even &apos;; rm -rf /&apos;
$process = Process::runExecutable(&apos;wc&apos;, [&apos;-l&apos;, $file]); // perfectly safe


runCommand(), on the other hand, hands the whole string to the
system shell (/bin/sh, or cmd.exe on Windows).
That gives you pipes, redirects, variable expansion, in short everything you&apos;d
expect from a shell:

$process = Process::runCommand(&apos;git log --oneline | head -n 20&apos;);


The price for the convenience: the shell parses that string, so never put
unescaped outside input into it. The rule is simple: anything involving user
input goes through runExecutable().

Streaming and
Reading Process Output in Real-Time

You&apos;re running something that takes minutes (npm install,
composer update, a build) and you want to see the progress, not
wait for the final dump. Pass wait() a callback:

$process = Process::runExecutable(&apos;npm&apos;, [&apos;install&apos;]);

$process-&gt;wait(function (string $stdOut, string $stdErr) {
	echo $stdOut;
	fwrite(STDERR, $stdErr);
});


The callback is invoked every time new output arrives. It gets whatever has
been added to standard and error output since the previous call. No
stream_select(), no switching pipes to non-blocking mode, no risk
of a deadlock when the program spits out more than fits in the pipe buffer. The
class handles all of that.

Don&apos;t want a callback? Pull the output yourself with
consumeStdOutput(), which returns the chunk added since the
previous call:

while ($process-&gt;isRunning()) {
	echo $process-&gt;consumeStdOutput();
	usleep(100_000);
}
echo $process-&gt;consumeStdOutput(); // grab the rest


Writing Large
Process Output Directly to a File

You don&apos;t always want the output in memory. Send a large database dump
straight to a file:

Process::runExecutable(&apos;mysqldump&apos;, [&apos;mydb&apos;], stdout: &apos;backup.sql&apos;)-&gt;ensureSuccess();


The stdout and stderr parameters take a filename, a
writable resource, false (discard), or null (capture
into memory, the default). Handy when a process pours out gigabytes that you
don&apos;t want sitting in RAM.

How to Set a
Timeout for External Processes in PHP

An external program can get stuck. The class has the $timeout
parameter for that (60 seconds by default):

try {
	Process::runExecutable(&apos;slow-tool&apos;, timeout: 5.0)-&gt;wait();
} catch (Nette\Utils\ProcessTimeoutException $e) {
	echo &apos;It took too long and the process was terminated.&apos;;
}


When the limit expires (it&apos;s checked while you wait for the process or read
from it), the process is killed and ProcessTimeoutException is
thrown. And it&apos;s killed for real: SIGKILL on Unix, taskkill /F on
Windows. No SIGTERM that a stubborn process could ignore and leave you hanging
forever in proc_close(). The terminate() method works
just as decisively, and a process is also terminated automatically when its
Process object goes away.

Piping Processes
Together in PHP (stdin / stdout)

Want to connect one process&apos;s output to another&apos;s input, exactly like a
| pipe in the shell, but without a shell? Pass a
Process as the $stdin:

$producer = Process::runExecutable(&apos;cat&apos;, [&apos;big.log&apos;]);
$consumer = Process::runExecutable(&apos;grep&apos;, [&apos;error&apos;], stdin: $producer);

echo $consumer-&gt;getStdOutput();


And you can chain as many as you like: a | b | c. On Windows
this is the one thing that doesn&apos;t work; there, capture the first
process&apos;s output and pass it to the next one as a string. Otherwise the class
behaves the same on Linux, macOS and Windows, handling the differences you&apos;d
rather not know about under the hood.

Process is in Nette Utils 4.1.4 (documentation). Give it a try
and let us know. And proc_open()? You won&apos;t have to touch it.
</description>
		<content:encoded><![CDATA[
		<p>Running an external program from PHP and reading what it printed?
<code>shell_exec('git pull')</code> and you're done. But that only covers the
simplest case. The moment you need more — the exit code, errors kept separate
from the regular output, a user-supplied argument passed safely, a timeout —
<code>shell_exec()</code> runs out of road. And <code>proc_open()</code>, which
can do all of it, has an API so unwelcoming that most people just avoid it.</p>

<p>Nette Utils 4.1.4 adds the <code>Nette\Utils\Process</code> class that fills
that gap between the two. You start a process, then you ask it questions: is it
still running? what did it print? how did it end? And it takes care of the
pipes, the polling loops, and the differences between operating systems
for you.</p>

<h2 id="toc-how-to-execute-a-command-and-get-the-exit-code-in-php">How to
Execute a Command and Get the Exit Code in PHP</h2>

<p>Want to run <code>git pull</code> and know whether it passed?</p>

<pre
class="language-php"><code>use Nette\Utils\Process;

Process::runExecutable(&#039;git&#039;, [&#039;pull&#039;])-&gt;ensureSuccess();
</code></pre>

<p>That single line runs <code>git pull</code>, waits for it to finish, and
throws <code>ProcessFailedException</code> if the exit code wasn't zero. No
juggling <code>exec()</code> and <code>$retval</code>, no
<code>is_resource()</code>, no loop.</p>

<p>And when you want the output?</p>

<pre
class="language-php"><code>$process = Process::runExecutable(&#039;git&#039;, [&#039;log&#039;, &#039;-1&#039;, &#039;--format=%H&#039;]);

echo $process-&gt;getStdOutput();  // standard output
echo $process-&gt;getStdError();   // error output, separately
echo $process-&gt;getExitCode();   // 0
</code></pre>

<p><code>getStdOutput()</code> waits for the program to finish and returns
everything it wrote to standard output. The error output you get separately,
which <code>shell_exec()</code> can't do. The exit code too. And unlike
PHP's native functions, the class doesn't return <code>false</code> on errors,
it throws exceptions, so you won't miss a failure. (Need to send the program
some input? Pass <code>stdin: 'data'</code>, or <code>null</code> and feed it
incrementally via <code>writeStdInput()</code>.)</p>

<h2
id="toc-runexecutable-vs-runcommand-preventing-shell-injection">runExecutable
vs. runCommand (Preventing Shell Injection)</h2>

<p>The class offers two ways to start a process, and the difference is not
cosmetic.</p>

<p><code>runExecutable()</code> runs <b>one specific program</b> with a list of
arguments. The arguments are handed to the program directly. No shell ever
touches them, so you don't have to escape anything and, more importantly,
there's no risk of shell injection:</p>

<pre
class="language-php"><code>$file = $_GET[&#039;file&#039;]; // could be anything, even &#039;; rm -rf /&#039;
$process = Process::runExecutable(&#039;wc&#039;, [&#039;-l&#039;, $file]); // perfectly safe
</code></pre>

<p><code>runCommand()</code>, on the other hand, hands the whole string to the
<b>system shell</b> (<code>/bin/sh</code>, or <code>cmd.exe</code> on Windows).
That gives you pipes, redirects, variable expansion, in short everything you'd
expect from a shell:</p>

<pre
class="language-php"><code>$process = Process::runCommand(&#039;git log --oneline | head -n 20&#039;);
</code></pre>

<p>The price for the convenience: the shell parses that string, so <b>never put
unescaped outside input into it</b>. The rule is simple: anything involving user
input goes through <code>runExecutable()</code>.</p>

<h2 id="toc-streaming-and-reading-process-output-in-real-time">Streaming and
Reading Process Output in Real-Time</h2>

<p>You're running something that takes minutes (<code>npm install</code>,
<code>composer update</code>, a build) and you want to see the progress, not
wait for the final dump. Pass <code>wait()</code> a callback:</p>

<pre
class="language-php"><code>$process = Process::runExecutable(&#039;npm&#039;, [&#039;install&#039;]);

$process-&gt;wait(function (string $stdOut, string $stdErr) {
	echo $stdOut;
	fwrite(STDERR, $stdErr);
});
</code></pre>

<p>The callback is invoked every time new output arrives. It gets whatever has
been added to standard and error output since the previous call. No
<code>stream_select()</code>, no switching pipes to non-blocking mode, no risk
of a deadlock when the program spits out more than fits in the pipe buffer. The
class handles all of that.</p>

<p>Don't want a callback? Pull the output yourself with
<code>consumeStdOutput()</code>, which returns the chunk added since the
previous call:</p>

<pre
class="language-php"><code>while ($process-&gt;isRunning()) {
	echo $process-&gt;consumeStdOutput();
	usleep(100_000);
}
echo $process-&gt;consumeStdOutput(); // grab the rest
</code></pre>

<h2 id="toc-writing-large-process-output-directly-to-a-file">Writing Large
Process Output Directly to a File</h2>

<p>You don't always want the output in memory. Send a large database dump
straight to a file:</p>

<pre
class="language-php"><code>Process::runExecutable(&#039;mysqldump&#039;, [&#039;mydb&#039;], stdout: &#039;backup.sql&#039;)-&gt;ensureSuccess();
</code></pre>

<p>The <code>stdout</code> and <code>stderr</code> parameters take a filename, a
writable resource, <code>false</code> (discard), or <code>null</code> (capture
into memory, the default). Handy when a process pours out gigabytes that you
don't want sitting in RAM.</p>

<h2 id="toc-how-to-set-a-timeout-for-external-processes-in-php">How to Set a
Timeout for External Processes in PHP</h2>

<p>An external program can get stuck. The class has the <code>$timeout</code>
parameter for that (60 seconds by default):</p>

<pre
class="language-php"><code>try {
	Process::runExecutable(&#039;slow-tool&#039;, timeout: 5.0)-&gt;wait();
} catch (Nette\Utils\ProcessTimeoutException $e) {
	echo &#039;It took too long and the process was terminated.&#039;;
}
</code></pre>

<p>When the limit expires (it's checked while you wait for the process or read
from it), the process is killed and <code>ProcessTimeoutException</code> is
thrown. And it's killed for real: SIGKILL on Unix, <code>taskkill /F</code> on
Windows. No SIGTERM that a stubborn process could ignore and leave you hanging
forever in <code>proc_close()</code>. The <code>terminate()</code> method works
just as decisively, and a process is also terminated automatically when its
<code>Process</code> object goes away.</p>

<h2 id="toc-piping-processes-together-in-php-stdin-stdout">Piping Processes
Together in PHP (stdin / stdout)</h2>

<p>Want to connect one process's output to another's input, exactly like a
<code>|</code> pipe in the shell, but without a shell? Pass a
<code>Process</code> as the <code>$stdin</code>:</p>

<pre
class="language-php"><code>$producer = Process::runExecutable(&#039;cat&#039;, [&#039;big.log&#039;]);
$consumer = Process::runExecutable(&#039;grep&#039;, [&#039;error&#039;], stdin: $producer);

echo $consumer-&gt;getStdOutput();
</code></pre>

<p>And you can chain as many as you like: <code>a | b | c</code>. On Windows
this is the one thing that doesn't work; there, capture the first
process's output and pass it to the next one as a string. Otherwise the class
behaves the same on Linux, macOS and Windows, handling the differences you'd
rather not know about under the hood.</p>

<p><code>Process</code> is in Nette Utils 4.1.4 (<a
href="https://doc.nette.org/en/utils/process">documentation</a>). Give it a try
and let us know. And <code>proc_open()</code>? You won't have to touch it.</p>

		]]></content:encoded>
		<comments>https://blog.nette.org/en/running-external-programs-in-php#comments</comments>
		<pubDate>Mon, 11 May 2026 21:41:00 +0200</pubDate>
		<guid isPermaLink="false">item539@http://blog.nette.org</guid>
	</item>
	<item>
		<title>Latte as a Ghost in the Machine: a Template Compiler for Tracy</title>
		<link>https://blog.nette.org/en/latte-template-compiler-for-tracy</link>
		<description>Tracy&apos;s templates have always been hand-written
.phtml pages full of htmlspecialchars and nested
ifs. I&apos;ll admit it bugged me for a long time. And then a heretical
thought hit me: what if Latte wrote them? But Latte in Tracy? Overkill! Or
rather… it could be done, just not the way you&apos;d expect.

Tracy is a debugger. It has to run in every PHP project that pulls it into
composer.json. In startups, in legacy applications, on shared
hosting from 2014. A heavyweight runtime dependency on a templating system has
no business being there. Period.

But those templates. If you&apos;ve ever written your own panel for the Tracy bar,
you know what I mean. A few cells in a table, dynamic CSS classes by state,
conditional attributes, and suddenly you&apos;ve got 35 lines of ugly
.phtml on your hands:

&lt;table class=&quot;tracy-sortable&quot;&gt;
&lt;thead&gt;&lt;tr&gt;&lt;th&gt;Time&lt;/th&gt;&lt;th&gt;Query&lt;/th&gt;&lt;th&gt;Source&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;
&lt;tbody&gt;
&lt;?php foreach ($queries as $q): ?&gt;
	&lt;tr&lt;?php if ($q-&gt;error): ?&gt; class=&quot;tracy-error&quot;&lt;?php elseif ($q-&gt;slow): ?&gt; class=&quot;tracy-warning&quot;&lt;?php endif ?&gt;&gt;
		&lt;td&lt;?php if ($q-&gt;time &gt; 100): ?&gt; title=&quot;&lt;?= htmlspecialchars((string) $q-&gt;time) ?&gt; ms&quot;&lt;?php endif ?&gt;&gt;
			&lt;?= number_format($q-&gt;time, 2) ?&gt; ms
		&lt;/td&gt;
		&lt;td&gt;&lt;code&gt;&lt;?= htmlspecialchars($q-&gt;sql) ?&gt;&lt;/code&gt;&lt;/td&gt;
		&lt;td&gt;&lt;?= htmlspecialchars($q-&gt;source) ?&gt;&lt;/td&gt;
	&lt;/tr&gt;
&lt;?php endforeach ?&gt;
&lt;/tbody&gt;
&lt;/table&gt;


Count the &lt;?php, ?&gt; and
htmlspecialchars tokens in that template. Then imagine adding a
fourth column six months from now. What a treat. And let me not even start on
the fact that every forgotten htmlspecialchars is a potential XSS.
In a debugger. Lovely.

Latte Instead of Raw PHP

One evening I started wondering what the same table would look like
in Latte:

&lt;table class=&quot;tracy-sortable&quot;&gt;
&lt;thead&gt;&lt;tr&gt;&lt;th&gt;Time&lt;/th&gt;&lt;th&gt;Query&lt;/th&gt;&lt;th&gt;Source&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;
&lt;tbody&gt;
	&lt;tr n:foreach=&quot;$queries as $q&quot; class=&quot;{$q-&gt;slow ? tracy-warning, $q-&gt;error ? tracy-error}&quot;&gt;
		&lt;td title={$q-&gt;time &gt; 100 ? $q-&gt;time . &apos; ms&apos;}&gt;{$q-&gt;time|number:2} ms&lt;/td&gt;
		&lt;td&gt;&lt;code&gt;{$q-&gt;sql}&lt;/code&gt;&lt;/td&gt;
		&lt;td&gt;{$q-&gt;source}&lt;/td&gt;
	&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;


Half the characters. Latte knows what HTML context it&apos;s currently
in and escapes accordingly: differently in text than in an attribute,
differently in an attribute than inside a &lt;script&gt;. No manual
htmlspecialchars. No forgetting. No way to get it wrong.

And notice the title attribute. This is Smart
HTML Attributes from Latte 3.1: when the value resolves to
null, the attribute doesn&apos;t appear in the output at all.

Beautiful. And absolutely unacceptable. Tracy must not depend on Latte
at runtime.

Latte as a Build-Time Compiler

And then it hit me. Latte doesn&apos;t have to become part of Tracy. It
just has to be part of building Tracy.

The principle is trivial. Templates are written in .latte. At
build time (locally, before commit) they get turned into static
.phtml files. Those get committed to the repo. At runtime, Tracy
just requires them. Nothing more. Latte never shows up in
composer.json. The developer writing the templates gets readable
templates; the developer pulling Tracy into their project gets the same
lightweight library as before.

In this role, Latte renders nothing. It takes a template apart and produces
PHP that does the same thing. A compiler, not an engine. Once that clicked, the
pieces fell into place.

How Template Compilation Works

Latte fortunately has a clean API. Extension points, custom AST nodes, a
configurable printer. You only need to write three things:


	a custom engine that, instead of producing a class extending the runtime
	template, emits flat standalone PHP: a plain echo-based script that
	needs no object context

	a custom escaper that, in the generated PHP, calls
	Tracy\Helpers::escapeHtml() instead of
	Latte\Runtime\Filters::escapeHtmlText(). The reason is obvious: if
	the generated code called Latte runtime, it would still depend on Latte

	a custom extension that registers only the tags I actually use in the
	templates


Most tags I could take from Latte as they are. {if},
{foreach}, {var}, {do},
{=...}. They live entirely at the AST level and the printer
translates them into PHP if, foreach and echo. They
need no runtime.

But then there are tags in Latte that are systemically tied to the runtime,
because Latte normally produces a template class and they work with that
class. {include} does inheritance and block overriding.
{define} generates blocks bound to the template class.

None of that fits in Tracy. No template classes, no hierarchy. So I rewrote
those tags. And here comes the main point: I didn&apos;t write my own parser, my own
AST, my own traverser. I only wrote my own implementation of the node, one that
behaves the way I need:


	{include &apos;file.phtml&apos;} → a plain
	require __DIR__ . &apos;/file.phtml&apos;. Period.

	{define name}...{/define} + {include name} →
	blocks as closures in a local $_blocks array. No inheritance, no
	template hierarchy, just named functions. A few lines of code.

	{varType Type $var} → /** @var Type $var */
	PHPDoc. The template is type-safe, the generated PHP too, and most importantly,
	PHPStan is happy.


I also added a {use Tracy\Helpers} tag, which Latte doesn&apos;t
have out of the box. A few lines of code with a node class and a
print() method that emits a PHP use at the top of the
generated file.

Bonus: The Dedent Feature
for Clean Output

Since version 2.12, Tracy can export exceptions as plain text (markdown) that
you can hand to your AI agent so it can fix the bug. No HTML, no CSS, just
markdown aligned to the left margin.

The template uses tags like {define}, {foreach},
{if}. I want it indented according to the structure of
those tags, otherwise I won&apos;t find anything in it a few months from now. But
the output has to be clean markdown aligned to the left margin, where every
character before a line means something specific (# is a heading,
and so on). So I need an indented source and at the same time an unindented
output.

How to pull that off? You either align the source to the left margin and give
up the visual structure of nested tags, or you keep the structure and wrap the
whole thing in {strip} plus manual {= &quot;\n&quot;} tricks to
chop the indentation out of the output. Both paths are unpleasant.

Fortunately Latte
3.1 brought a feature called Dedent. At compile time, Latte automatically
strips the common indentation prefix inside each pair tag. The source mirrors
the structure of the control tags, the output is clean. For markdown reports,
where every character of indentation matters, it&apos;s exactly the tool
I needed.

An excerpt from the real agent.latte template in Tracy:

{foreach Helpers::getExceptionChain($exception) as $i =&gt; $ex}
	{if $i === 0}
		# {$title}: {$ex-&gt;getMessage()}{$code}
	{else}
		## Caused by: {$title}: {$ex-&gt;getMessage()}{$code}
	{/if}

	in {$ex-&gt;getFile()}:{$ex-&gt;getLine()}
	{include renderSource $ex-&gt;getFile(), $ex-&gt;getLine()}
{/foreach}


And the corresponding output, aligned to the left margin, the way markdown is
meant to be:

# Exception: The my exception #123

in /path/to/file.php:42

   40 | function third($arg1)
   41 | {
►  42 | 	throw new Exception(&apos;The my exception&apos;, 123);
   43 | }


Indented source, unindented output. A problem that would elsewhere force a
choice between two ugly solutions is a breeze.

Benefits: Security and
Type-Safety

What&apos;s changed, then? Tracy&apos;s templates are shorter, more readable,
type-safe (thanks to {varType} and phpDoc comments that PHPStan and
IDEs understand) and they can&apos;t contain XSS bugs. The generated
.phtml files are flat imperative PHP with no dependencies. Tracy&apos;s
composer.json stayed exactly the same. No one on the outside
notices anything has changed.

And for me as the author? Instead of writing htmlspecialchars
for the four-hundredth time, I write {$x}. That&apos;s all I ever
wanted from a templating system.

Latte isn&apos;t physically present in Tracy. And yet you can feel it in the
resulting code. Latte as a ghost in the machine. Like the best framework
I know: the one that simply isn&apos;t visible in the resulting code. 🙂

You can find the compiler in the Tracy
repository.
</description>
		<content:encoded><![CDATA[
		<p class="perex">Tracy's templates have always been hand-written
<code>.phtml</code> pages full of <code>htmlspecialchars</code> and nested
<code>if</code>s. I'll admit it bugged me for a long time. And then a heretical
thought hit me: what if Latte wrote them? But Latte in Tracy? Overkill! Or
rather… it could be done, just not the way you'd expect.</p>

<p>Tracy is a debugger. It has to run in every PHP project that pulls it into
<code>composer.json</code>. In startups, in legacy applications, on shared
hosting from 2014. A heavyweight runtime dependency on a templating system has
no business being there. Period.</p>

<p>But those templates. If you've ever written your own panel for the Tracy bar,
you know what I mean. A few cells in a table, dynamic CSS classes by state,
conditional attributes, and suddenly you've got 35 lines of ugly
<code>.phtml</code> on your hands:</p>

<pre
class="language-php"><code>&lt;table class=&quot;tracy-sortable&quot;&gt;
&lt;thead&gt;&lt;tr&gt;&lt;th&gt;Time&lt;/th&gt;&lt;th&gt;Query&lt;/th&gt;&lt;th&gt;Source&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;
&lt;tbody&gt;
&lt;?php foreach ($queries as $q): ?&gt;
	&lt;tr&lt;?php if ($q-&gt;error): ?&gt; class=&quot;tracy-error&quot;&lt;?php elseif ($q-&gt;slow): ?&gt; class=&quot;tracy-warning&quot;&lt;?php endif ?&gt;&gt;
		&lt;td&lt;?php if ($q-&gt;time &gt; 100): ?&gt; title=&quot;&lt;?= htmlspecialchars((string) $q-&gt;time) ?&gt; ms&quot;&lt;?php endif ?&gt;&gt;
			&lt;?= number_format($q-&gt;time, 2) ?&gt; ms
		&lt;/td&gt;
		&lt;td&gt;&lt;code&gt;&lt;?= htmlspecialchars($q-&gt;sql) ?&gt;&lt;/code&gt;&lt;/td&gt;
		&lt;td&gt;&lt;?= htmlspecialchars($q-&gt;source) ?&gt;&lt;/td&gt;
	&lt;/tr&gt;
&lt;?php endforeach ?&gt;
&lt;/tbody&gt;
&lt;/table&gt;
</code></pre>

<p>Count the <code>&lt;?php</code>, <code>?&gt;</code> and
<code>htmlspecialchars</code> tokens in that template. Then imagine adding a
fourth column six months from now. What a treat. And let me not even start on
the fact that every forgotten <code>htmlspecialchars</code> is a potential XSS.
In a debugger. Lovely.</p>

<h2 id="toc-latte-instead-of-raw-php">Latte Instead of Raw PHP</h2>

<p>One evening I started wondering what the same table would look like
in Latte:</p>

<pre
class="language-latte"><code>&lt;table class=&quot;tracy-sortable&quot;&gt;
&lt;thead&gt;&lt;tr&gt;&lt;th&gt;Time&lt;/th&gt;&lt;th&gt;Query&lt;/th&gt;&lt;th&gt;Source&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;
&lt;tbody&gt;
	&lt;tr n:foreach=&quot;$queries as $q&quot; class=&quot;{$q-&gt;slow ? tracy-warning, $q-&gt;error ? tracy-error}&quot;&gt;
		&lt;td title={$q-&gt;time &gt; 100 ? $q-&gt;time . &#039; ms&#039;}&gt;{$q-&gt;time|number:2} ms&lt;/td&gt;
		&lt;td&gt;&lt;code&gt;{$q-&gt;sql}&lt;/code&gt;&lt;/td&gt;
		&lt;td&gt;{$q-&gt;source}&lt;/td&gt;
	&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
</code></pre>

<p>Half the characters. Latte knows <a
href="https://latte.nette.org/en/safety-first">what HTML context it's currently
in</a> and escapes accordingly: differently in text than in an attribute,
differently in an attribute than inside a <code>&lt;script&gt;</code>. No manual
<code>htmlspecialchars</code>. No forgetting. No way to get it wrong.</p>

<p>And notice the <code>title</code> attribute. This is <a
href="https://blog.nette.org/en/latte-3-1-when-the-templating-system-truly-understands-html">Smart
HTML Attributes</a> from Latte 3.1: when the value resolves to
<code>null</code>, the attribute doesn't appear in the output at all.</p>

<p><b>Beautiful. And absolutely unacceptable.</b> Tracy must not depend on Latte
at runtime.</p>

<h2 id="toc-latte-as-a-build-time-compiler">Latte as a Build-Time Compiler</h2>

<p>And then it hit me. Latte doesn't have to become <em>part of</em> Tracy. It
just has to be part of <i>building</i> Tracy.</p>

<p>The principle is trivial. Templates are written in <code>.latte</code>. At
build time (locally, before commit) they get turned into static
<code>.phtml</code> files. Those get committed to the repo. At runtime, Tracy
just <code>require</code>s them. Nothing more. Latte never shows up in
<code>composer.json</code>. The developer writing the templates gets readable
templates; the developer pulling Tracy into their project gets the same
lightweight library as before.</p>

<p>In this role, Latte renders nothing. It takes a template apart and produces
PHP that does the same thing. A compiler, not an engine. Once that clicked, the
pieces fell into place.</p>

<h2 id="toc-how-template-compilation-works">How Template Compilation Works</h2>

<p>Latte fortunately has a clean API. Extension points, custom AST nodes, a
configurable printer. You only need to write three things:</p>

<ul>
	<li>a custom engine that, instead of producing a class extending the runtime
	template, emits <em>flat standalone PHP</em>: a plain echo-based script that
	needs no object context</li>

	<li>a custom escaper that, in the generated PHP, calls
	<code>Tracy\Helpers::escapeHtml()</code> instead of
	<code>Latte\Runtime\Filters::escapeHtmlText()</code>. The reason is obvious: if
	the generated code called Latte runtime, it would still depend on Latte</li>

	<li>a custom extension that registers only the tags I actually use in the
	templates</li>
</ul>

<p>Most tags I could take from Latte as they are. <code>{if}</code>,
<code>{foreach}</code>, <code>{var}</code>, <code>{do}</code>,
<code>{=...}</code>. They live entirely at the AST level and the printer
translates them into PHP <code>if</code>, <code>foreach</code> and echo. They
need no runtime.</p>

<p>But then there are tags in Latte that are systemically tied to the runtime,
because Latte normally produces a template <i>class</i> and they work with that
class. <code>{include}</code> does inheritance and block overriding.
<code>{define}</code> generates blocks bound to the template class.</p>

<p>None of that fits in Tracy. No template classes, no hierarchy. So I rewrote
those tags. And here comes the main point: I didn't write my own parser, my own
AST, my own traverser. I only wrote my own implementation of the node, one that
behaves the way I need:</p>

<ul>
	<li><code>{include 'file.phtml'}</code> → a plain
	<code>require __DIR__ . '/file.phtml'</code>. Period.</li>

	<li><code>{define name}...{/define}</code> + <code>{include name}</code> →
	blocks as closures in a local <code>$_blocks</code> array. No inheritance, no
	template hierarchy, just named functions. A few lines of code.</li>

	<li><code>{varType Type $var}</code> → <code>/** @var Type $var */</code>
	PHPDoc. The template is type-safe, the generated PHP too, and most importantly,
	PHPStan is happy.</li>
</ul>

<p>I also added a <code>{use Tracy\Helpers}</code> tag, which Latte doesn't
have out of the box. A few lines of code with a <a
href="https://latte.nette.org/en/custom-tags">node class</a> and a
<code>print()</code> method that emits a PHP <code>use</code> at the top of the
generated file.</p>

<h2 id="toc-bonus-the-dedent-feature-for-clean-output">Bonus: The Dedent Feature
for Clean Output</h2>

<p>Since version 2.12, Tracy can export exceptions as plain text (markdown) that
you can hand to your AI agent so it can fix the bug. No HTML, no CSS, just
markdown aligned to the left margin.</p>

<p>The template uses tags like <code>{define}</code>, <code>{foreach}</code>,
<code>{if}</code>. I want it <b>indented according to the structure</b> of
those tags, otherwise I won't find anything in it a few months from now. But
the output has to be clean markdown aligned to the left margin, where every
character before a line means something specific (<code>#</code> is a heading,
and so on). So I need an <b>indented source and at the same time an unindented
output</b>.</p>

<p>How to pull that off? You either align the source to the left margin and give
up the visual structure of nested tags, or you keep the structure and wrap the
whole thing in <code>{strip}</code> plus manual <code>{= "\n"}</code> tricks to
chop the indentation out of the output. Both paths are unpleasant.</p>

<p>Fortunately <a
href="https://blog.nette.org/en/five-new-features-in-latte-3-1">Latte
3.1 brought a feature called Dedent</a>. At compile time, Latte automatically
strips the common indentation prefix inside each pair tag. The source mirrors
the structure of the control tags, the output is clean. For markdown reports,
where every character of indentation matters, it's exactly the tool
I needed.</p>

<p>An excerpt from the real <code>agent.latte</code> template in Tracy:</p>

<pre
class="language-latte"><code>{foreach Helpers::getExceptionChain($exception) as $i =&gt; $ex}
	{if $i === 0}
		# {$title}: {$ex-&gt;getMessage()}{$code}
	{else}
		## Caused by: {$title}: {$ex-&gt;getMessage()}{$code}
	{/if}

	in {$ex-&gt;getFile()}:{$ex-&gt;getLine()}
	{include renderSource $ex-&gt;getFile(), $ex-&gt;getLine()}
{/foreach}
</code></pre>

<p>And the corresponding output, aligned to the left margin, the way markdown is
meant to be:</p>

<pre><code># Exception: The my exception #123

in /path/to/file.php:42

   40 | function third($arg1)
   41 | {
►  42 | 	throw new Exception(&#039;The my exception&#039;, 123);
   43 | }
</code></pre>

<p>Indented source, unindented output. A problem that would elsewhere force a
choice between two ugly solutions is <em>a breeze</em>.</p>

<h2 id="toc-benefits-security-and-type-safety">Benefits: Security and
Type-Safety</h2>

<p>What's changed, then? Tracy's templates are shorter, more readable,
type-safe (thanks to <code>{varType}</code> and phpDoc comments that PHPStan and
IDEs understand) and they can't contain XSS bugs. The generated
<code>.phtml</code> files are flat imperative PHP with no dependencies. Tracy's
<code>composer.json</code> stayed exactly the same. No one on the outside
notices anything has changed.</p>

<p>And for me as the author? Instead of writing <code>htmlspecialchars</code>
for the four-hundredth time, I write <code>{$x}</code>. That's all I ever
wanted from a templating system.</p>

<p>Latte isn't physically present in Tracy. And yet you can feel it in the
resulting code. Latte as a ghost in the machine. Like the best framework
I know: the one that simply isn't visible in the resulting code. 🙂</p>

<p>You can find the compiler in the <a
href="https://github.com/nette/tracy/tree/master/tools/latte-convert">Tracy
repository</a>.</p>

		]]></content:encoded>
		<comments>https://blog.nette.org/en/latte-template-compiler-for-tracy#comments</comments>
		<pubDate>Sat, 25 Apr 2026 14:04:00 +0200</pubDate>
		<guid isPermaLink="false">item536@http://blog.nette.org</guid>
	</item>
</channel>
</rss>
