From e49a5c61ac8479d55de764adac6a3666299a96fb Mon Sep 17 00:00:00 2001 From: David Grudl Date: Mon, 2 Nov 2026 06:24:02 +0100 Subject: [PATCH 1/7] added maintitle and description to all pages af74fe33-a878-46d6-b93f-2d832004e5c7 --- AGENTS.md | 1 + ai/cs/mcp-inspector.texy | 2 ++ ai/cs/vibe-coding.texy | 1 + ai/en/agent-plugins.texy | 2 ++ ai/en/getting-started.texy | 1 + ai/en/mcp-inspector.texy | 2 ++ ai/en/privacy-policy.texy | 1 + ai/en/vibe-coding.texy | 1 + application/cs/@home.texy | 3 +++ application/cs/ajax.texy | 3 +++ application/cs/bootstrapping.texy | 3 +++ application/cs/components.texy | 3 +++ application/cs/configuration.texy | 3 +++ application/cs/creating-links.texy | 3 +++ application/cs/directory-structure.texy | 3 +++ application/cs/how-it-works.texy | 3 +++ application/cs/multiplier.texy | 3 +++ application/cs/presenters.texy | 3 +++ application/cs/routing.texy | 2 ++ application/cs/templates.texy | 3 +++ application/cs/upgrading.texy | 3 +++ application/en/@home.texy | 3 +++ application/en/ajax.texy | 3 +++ application/en/bootstrapping.texy | 3 +++ application/en/components.texy | 3 +++ application/en/configuration.texy | 3 +++ application/en/creating-links.texy | 3 +++ application/en/directory-structure.texy | 3 +++ application/en/how-it-works.texy | 3 +++ application/en/multiplier.texy | 3 +++ application/en/presenters.texy | 3 +++ application/en/routing.texy | 2 ++ application/en/templates.texy | 3 +++ application/en/upgrading.texy | 3 +++ assets/cs/@home.texy | 3 +++ assets/cs/configuration.texy | 3 +++ assets/cs/vite.texy | 3 +++ assets/en/@home.texy | 3 +++ assets/en/configuration.texy | 3 +++ assets/en/vite.texy | 3 +++ best-practices/cs/@home.texy | 3 +++ best-practices/cs/attribute-requires.texy | 3 +++ best-practices/cs/composer.texy | 3 +++ best-practices/cs/creating-editing-form.texy | 2 ++ best-practices/cs/dynamic-snippets.texy | 2 ++ best-practices/cs/form-reuse.texy | 3 +++ best-practices/cs/inject-method-attribute.texy | 3 +++ best-practices/cs/lets-create-contact-form.texy | 3 +++ best-practices/cs/microsites.texy | 3 +++ best-practices/cs/pagination.texy | 2 ++ best-practices/cs/passing-settings-to-presenters.texy | 3 +++ best-practices/cs/post-links.texy | 3 +++ best-practices/cs/presenter-traits.texy | 3 +++ best-practices/cs/pretty-urls.texy | 3 +++ best-practices/cs/restore-request.texy | 2 ++ best-practices/en/@home.texy | 3 +++ best-practices/en/attribute-requires.texy | 3 +++ best-practices/en/composer.texy | 3 +++ best-practices/en/creating-editing-form.texy | 2 ++ best-practices/en/dynamic-snippets.texy | 2 ++ best-practices/en/form-reuse.texy | 3 +++ best-practices/en/inject-method-attribute.texy | 3 +++ best-practices/en/lets-create-contact-form.texy | 3 +++ best-practices/en/microsites.texy | 3 +++ best-practices/en/pagination.texy | 2 ++ best-practices/en/passing-settings-to-presenters.texy | 3 +++ best-practices/en/post-links.texy | 3 +++ best-practices/en/presenter-traits.texy | 3 +++ best-practices/en/pretty-urls.texy | 3 +++ best-practices/en/restore-request.texy | 2 ++ bootstrap/cs/@home.texy | 3 +++ bootstrap/cs/upgrading.texy | 3 +++ bootstrap/en/@home.texy | 3 +++ bootstrap/en/upgrading.texy | 3 +++ caching/cs/@home.texy | 3 +++ caching/cs/upgrading.texy | 3 +++ caching/en/@home.texy | 3 +++ caching/en/upgrading.texy | 3 +++ command-line/cs/@home.texy | 4 ++-- command-line/cs/arguments.texy | 3 ++- command-line/cs/console.texy | 3 ++- command-line/en/@home.texy | 4 ++-- command-line/en/arguments.texy | 3 ++- command-line/en/console.texy | 3 ++- component-model/cs/@home.texy | 3 +++ component-model/cs/upgrading.texy | 3 +++ component-model/en/@home.texy | 3 +++ component-model/en/upgrading.texy | 3 +++ contributing/cs/@home.texy | 3 +++ contributing/cs/code.texy | 2 ++ contributing/cs/coding-standard.texy | 2 ++ contributing/cs/documentation.texy | 3 +++ contributing/cs/syntax.texy | 2 ++ contributing/en/@home.texy | 3 +++ contributing/en/code.texy | 2 ++ contributing/en/coding-standard.texy | 2 ++ contributing/en/documentation.texy | 3 +++ contributing/en/syntax.texy | 2 ++ database/cs/@home.texy | 6 ++---- database/cs/configuration.texy | 3 +++ database/cs/exceptions.texy | 3 +++ database/cs/explorer.texy | 3 +++ database/cs/guide.texy | 3 +++ database/cs/reflection.texy | 3 +++ database/cs/security.texy | 3 +++ database/cs/sql-way.texy | 3 +++ database/cs/transactions.texy | 3 +++ database/cs/type-conversion.texy | 3 +++ database/cs/upgrading.texy | 3 +++ database/en/@home.texy | 6 ++---- database/en/configuration.texy | 3 +++ database/en/exceptions.texy | 3 +++ database/en/explorer.texy | 3 +++ database/en/guide.texy | 3 +++ database/en/reflection.texy | 3 +++ database/en/security.texy | 3 +++ database/en/sql-way.texy | 3 +++ database/en/transactions.texy | 3 +++ database/en/type-conversion.texy | 3 +++ database/en/upgrading.texy | 3 +++ dependency-injection/cs/@home.texy | 3 +++ dependency-injection/cs/autowiring.texy | 3 +++ dependency-injection/cs/compilation-internals.texy | 3 +++ dependency-injection/cs/configuration.texy | 3 ++- dependency-injection/cs/container.texy | 2 +- dependency-injection/cs/extensions.texy | 3 +++ dependency-injection/cs/factory.texy | 3 +++ dependency-injection/cs/faq.texy | 3 +++ dependency-injection/cs/global-state.texy | 3 +++ dependency-injection/cs/introduction.texy | 3 +++ dependency-injection/cs/nette-container.texy | 3 +++ dependency-injection/cs/passing-dependencies.texy | 3 +++ dependency-injection/cs/services.texy | 3 +++ dependency-injection/cs/upgrading.texy | 3 +++ dependency-injection/en/@home.texy | 3 +++ dependency-injection/en/autowiring.texy | 3 +++ dependency-injection/en/compilation-internals.texy | 3 +++ dependency-injection/en/configuration.texy | 3 ++- dependency-injection/en/container.texy | 2 +- dependency-injection/en/extensions.texy | 3 +++ dependency-injection/en/factory.texy | 3 +++ dependency-injection/en/faq.texy | 3 +++ dependency-injection/en/global-state.texy | 3 +++ dependency-injection/en/introduction.texy | 3 +++ dependency-injection/en/nette-container.texy | 3 +++ dependency-injection/en/passing-dependencies.texy | 3 +++ dependency-injection/en/services.texy | 3 +++ dependency-injection/en/upgrading.texy | 3 +++ forms/cs/@home.texy | 3 +++ forms/cs/configuration.texy | 3 +++ forms/cs/controls.texy | 3 +++ forms/cs/custom-controls.texy | 3 +++ forms/cs/in-presenter.texy | 3 +++ forms/cs/rendering.texy | 3 +++ forms/cs/standalone.texy | 3 +++ forms/cs/upgrading.texy | 3 +++ forms/cs/validation.texy | 3 +++ forms/en/@home.texy | 3 +++ forms/en/configuration.texy | 3 +++ forms/en/controls.texy | 3 +++ forms/en/custom-controls.texy | 3 +++ forms/en/in-presenter.texy | 3 +++ forms/en/rendering.texy | 3 +++ forms/en/standalone.texy | 3 +++ forms/en/upgrading.texy | 3 +++ forms/en/validation.texy | 3 +++ http/cs/@home.texy | 3 +++ http/cs/configuration.texy | 3 +++ http/cs/request.texy | 3 +++ http/cs/response.texy | 3 +++ http/cs/sessions.texy | 3 +++ http/cs/ssrf.texy | 3 +++ http/cs/upgrading.texy | 3 +++ http/cs/urls.texy | 3 +++ http/en/@home.texy | 3 +++ http/en/configuration.texy | 3 +++ http/en/request.texy | 3 +++ http/en/response.texy | 3 +++ http/en/sessions.texy | 3 +++ http/en/ssrf.texy | 3 +++ http/en/upgrading.texy | 3 +++ http/en/urls.texy | 3 +++ latte/cs/@home.texy | 4 ++-- latte/cs/compiler-passes.texy | 3 +++ latte/cs/cookbook/@home.texy | 3 +++ latte/cs/cookbook/grouping.texy | 3 +++ latte/cs/cookbook/how-to-write-sql-queries-in-latte.texy | 3 +++ latte/cs/cookbook/migration-from-latte-30.texy | 3 +++ latte/cs/cookbook/migration-from-latte2.texy | 2 ++ latte/cs/cookbook/migration-from-php.texy | 3 +++ latte/cs/cookbook/migration-from-twig.texy | 3 +++ latte/cs/cookbook/passing-variables.texy | 3 +++ latte/cs/cookbook/slim-framework.texy | 2 ++ latte/cs/custom-filters.texy | 3 +++ latte/cs/custom-functions.texy | 3 +++ latte/cs/custom-tags.texy | 3 +++ latte/cs/develop.texy | 3 +++ latte/cs/extending-latte.texy | 3 +++ latte/cs/filters.texy | 3 +++ latte/cs/functions.texy | 3 +++ latte/cs/guide.texy | 4 ++-- latte/cs/html-attributes.texy | 3 +++ latte/cs/loaders.texy | 3 +++ latte/cs/recipes.texy | 3 +++ latte/cs/safety-first.texy | 3 +++ latte/cs/sandbox.texy | 3 +++ latte/cs/syntax.texy | 3 +++ latte/cs/tags.texy | 3 +++ latte/cs/template-inheritance.texy | 3 +++ latte/cs/type-system.texy | 3 +++ latte/cs/why-use.texy | 3 +++ latte/en/@home.texy | 4 ++-- latte/en/compiler-passes.texy | 3 +++ latte/en/cookbook/@home.texy | 3 +++ latte/en/cookbook/grouping.texy | 3 +++ latte/en/cookbook/how-to-write-sql-queries-in-latte.texy | 3 +++ latte/en/cookbook/migration-from-latte-30.texy | 3 +++ latte/en/cookbook/migration-from-latte2.texy | 2 ++ latte/en/cookbook/migration-from-php.texy | 3 +++ latte/en/cookbook/migration-from-twig.texy | 3 +++ latte/en/cookbook/passing-variables.texy | 3 +++ latte/en/cookbook/slim-framework.texy | 2 ++ latte/en/custom-filters.texy | 3 +++ latte/en/custom-functions.texy | 3 +++ latte/en/custom-tags.texy | 3 +++ latte/en/develop.texy | 3 +++ latte/en/extending-latte.texy | 3 +++ latte/en/filters.texy | 3 +++ latte/en/functions.texy | 3 +++ latte/en/guide.texy | 4 ++-- latte/en/html-attributes.texy | 3 +++ latte/en/loaders.texy | 3 +++ latte/en/recipes.texy | 3 +++ latte/en/safety-first.texy | 3 +++ latte/en/sandbox.texy | 3 +++ latte/en/syntax.texy | 3 +++ latte/en/tags.texy | 3 +++ latte/en/template-inheritance.texy | 3 +++ latte/en/type-system.texy | 3 +++ latte/en/why-use.texy | 3 +++ mail/cs/@home.texy | 3 +++ mail/cs/upgrading.texy | 3 +++ mail/en/@home.texy | 3 +++ mail/en/upgrading.texy | 3 +++ migrations/cs/@home.texy | 3 +++ migrations/en/@home.texy | 3 +++ neon/cs/@home.texy | 3 +++ neon/cs/format.texy | 4 ++-- neon/cs/upgrading.texy | 3 +++ neon/en/@home.texy | 3 +++ neon/en/format.texy | 4 ++-- neon/en/upgrading.texy | 3 +++ nette/cs/@home.texy | 4 ++-- nette/cs/configuring.texy | 3 ++- nette/cs/glossary.texy | 2 ++ nette/cs/installation.texy | 3 ++- nette/cs/introduction-to-object-oriented-programming.texy | 3 +++ nette/cs/troubleshooting.texy | 3 ++- nette/cs/vulnerability-protection.texy | 2 ++ nette/en/@home.texy | 4 ++-- nette/en/configuring.texy | 3 ++- nette/en/glossary.texy | 2 ++ nette/en/installation.texy | 3 ++- nette/en/introduction-to-object-oriented-programming.texy | 3 +++ nette/en/troubleshooting.texy | 3 ++- nette/en/vulnerability-protection.texy | 2 ++ php-generator/cs/@home.texy | 3 +++ php-generator/cs/upgrading.texy | 3 +++ php-generator/en/@home.texy | 3 +++ php-generator/en/upgrading.texy | 3 +++ quickstart/cs/@home.texy | 2 ++ quickstart/cs/authentication.texy | 2 ++ quickstart/cs/comments.texy | 2 ++ quickstart/cs/creating-posts.texy | 2 ++ quickstart/cs/home-page.texy | 2 ++ quickstart/cs/model.texy | 2 ++ quickstart/cs/single-post.texy | 2 ++ quickstart/en/@home.texy | 2 ++ quickstart/en/authentication.texy | 2 ++ quickstart/en/comments.texy | 2 ++ quickstart/en/creating-posts.texy | 2 ++ quickstart/en/home-page.texy | 2 ++ quickstart/en/model.texy | 2 ++ quickstart/en/single-post.texy | 2 ++ robot-loader/cs/@home.texy | 2 ++ robot-loader/cs/upgrading.texy | 3 +++ robot-loader/en/@home.texy | 2 ++ robot-loader/en/upgrading.texy | 3 +++ safe-stream/cs/@home.texy | 2 ++ safe-stream/cs/upgrading.texy | 3 +++ safe-stream/en/@home.texy | 2 ++ safe-stream/en/upgrading.texy | 3 +++ schema/cs/@home.texy | 3 +++ schema/en/@home.texy | 3 +++ security/cs/@home.texy | 3 +++ security/cs/acl.texy | 3 +++ security/cs/authentication.texy | 3 +++ security/cs/configuration.texy | 3 +++ security/cs/passwords.texy | 3 +++ security/cs/upgrading.texy | 3 +++ security/en/@home.texy | 3 +++ security/en/acl.texy | 3 +++ security/en/authentication.texy | 3 +++ security/en/configuration.texy | 3 +++ security/en/passwords.texy | 3 +++ security/en/upgrading.texy | 3 +++ tester/cs/@home.texy | 4 ++-- tester/cs/assertions.texy | 3 +++ tester/cs/guide.texy | 3 +++ tester/cs/helpers.texy | 3 +++ tester/cs/running-tests.texy | 3 +++ tester/cs/test-annotations.texy | 3 +++ tester/cs/testcase.texy | 3 +++ tester/cs/writing-tests.texy | 3 +++ tester/en/@home.texy | 4 ++-- tester/en/assertions.texy | 3 +++ tester/en/guide.texy | 3 +++ tester/en/helpers.texy | 3 +++ tester/en/running-tests.texy | 3 +++ tester/en/test-annotations.texy | 3 +++ tester/en/testcase.texy | 3 +++ tester/en/writing-tests.texy | 3 +++ tokenizer/cs/@home.texy | 2 ++ tokenizer/en/@home.texy | 2 ++ tools/cs/@home.texy | 3 +++ tools/cs/code-checker.texy | 3 +++ tools/cs/coding-standard.texy | 3 +++ tools/cs/ide.texy | 3 +++ tools/cs/phpstan-rules.texy | 3 +++ tools/cs/xray.texy | 3 +++ tools/en/@home.texy | 3 +++ tools/en/code-checker.texy | 3 +++ tools/en/coding-standard.texy | 3 +++ tools/en/ide.texy | 3 +++ tools/en/phpstan-rules.texy | 3 +++ tools/en/xray.texy | 3 +++ tracy/cs/@home.texy | 4 ++-- tracy/cs/configuring.texy | 3 +++ tracy/cs/dumper.texy | 3 +++ tracy/cs/extensions.texy | 3 +++ tracy/cs/guide.texy | 3 +++ tracy/cs/open-files-in-ide.texy | 3 +++ tracy/cs/recipes.texy | 3 +++ tracy/cs/stopwatch.texy | 3 +++ tracy/cs/upgrading.texy | 3 +++ tracy/en/@home.texy | 4 ++-- tracy/en/configuring.texy | 3 +++ tracy/en/dumper.texy | 3 +++ tracy/en/extensions.texy | 3 +++ tracy/en/guide.texy | 3 +++ tracy/en/open-files-in-ide.texy | 3 +++ tracy/en/recipes.texy | 3 +++ tracy/en/stopwatch.texy | 3 +++ tracy/en/upgrading.texy | 3 +++ utils/cs/@home.texy | 3 +++ utils/cs/arrays.texy | 3 +++ utils/cs/callback.texy | 3 +++ utils/cs/datetime.texy | 3 +++ utils/cs/filesystem.texy | 3 +++ utils/cs/finder.texy | 3 +++ utils/cs/floats.texy | 3 +++ utils/cs/helpers.texy | 3 +++ utils/cs/html-elements.texy | 3 +++ utils/cs/images.texy | 3 +++ utils/cs/iterables.texy | 3 +++ utils/cs/json.texy | 3 +++ utils/cs/paginator.texy | 3 +++ utils/cs/process.texy | 3 +++ utils/cs/random.texy | 3 +++ utils/cs/reflection.texy | 3 +++ utils/cs/smartobject.texy | 3 +++ utils/cs/staticclass.texy | 3 +++ utils/cs/strings.texy | 3 +++ utils/cs/type.texy | 3 +++ utils/cs/upgrading.texy | 3 +++ utils/cs/validators.texy | 3 +++ utils/en/@home.texy | 3 +++ utils/en/arrays.texy | 3 +++ utils/en/callback.texy | 3 +++ utils/en/datetime.texy | 3 +++ utils/en/filesystem.texy | 3 +++ utils/en/finder.texy | 3 +++ utils/en/floats.texy | 3 +++ utils/en/helpers.texy | 3 +++ utils/en/html-elements.texy | 3 +++ utils/en/images.texy | 3 +++ utils/en/iterables.texy | 3 +++ utils/en/json.texy | 3 +++ utils/en/paginator.texy | 3 +++ utils/en/process.texy | 3 +++ utils/en/random.texy | 3 +++ utils/en/reflection.texy | 3 +++ utils/en/smartobject.texy | 3 +++ utils/en/staticclass.texy | 3 +++ utils/en/strings.texy | 3 +++ utils/en/type.texy | 3 +++ utils/en/upgrading.texy | 3 +++ utils/en/validators.texy | 3 +++ www/cs/10-reasons-why-nette.texy | 3 ++- www/cs/@home.texy | 4 ++-- www/cs/donate.texy | 3 +++ www/cs/history.texy | 2 ++ www/cs/license.texy | 2 ++ www/cs/logo.texy | 2 ++ www/cs/maintenance.texy | 3 ++- www/cs/packages.texy | 2 ++ www/cs/security-warning.texy | 3 +++ www/cs/terms-of-use.texy | 2 ++ www/en/10-reasons-why-nette.texy | 3 ++- www/en/@home.texy | 4 ++-- www/en/donate.texy | 3 +++ www/en/history.texy | 2 ++ www/en/license.texy | 2 ++ www/en/logo.texy | 2 ++ www/en/maintenance.texy | 3 ++- www/en/packages.texy | 2 ++ www/en/security-warning.texy | 3 +++ www/en/terms-of-use.texy | 2 ++ 418 files changed, 1149 insertions(+), 58 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 8d27d02341..6f6b53c17f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -307,6 +307,7 @@ The good example explains what the tool does and why it matters. The bad example - Break complex topics into digestible sections - Use code examples liberally – they're often clearer than prose - End sections with "What's Next" links when appropriate +- Put the `{{maintitle}}` and `{{description}}` directives at the very end of the page, in this order, after a blank line ## Mandatory Self-Review After Every Change diff --git a/ai/cs/mcp-inspector.texy b/ai/cs/mcp-inspector.texy index 355d9dca67..90a4755d4c 100644 --- a/ai/cs/mcp-inspector.texy +++ b/ai/cs/mcp-inspector.texy @@ -324,3 +324,5 @@ AI teď může volat `blog_get_post` jako kterýkoli vestavěný nástroj. Vyzko {{composer: nette/mcp-inspector}} {{repo: nette/mcp-inspector}} +{{maintitle: Nette MCP Inspector: AI vidí přímo do vaší aplikace}} +{{description: MCP Inspector umožní AI asistentovi podívat se přímo do vaší Nette aplikace: služby v DI kontejneru, databázové tabulky, routy a logy Tracy. Žádné hádání.}} diff --git a/ai/cs/vibe-coding.texy b/ai/cs/vibe-coding.texy index fac5320a42..25a3b210bb 100644 --- a/ai/cs/vibe-coding.texy +++ b/ai/cs/vibe-coding.texy @@ -295,4 +295,5 @@ A pamatujte: AI je váš asistent. Vývojář jste pořád vy. Vy rozhodujete, v Hodně zdaru! +{{maintitle: Vibe coding v PHP s Nette: prompty a osvědčené postupy}} {{description: Praktické rady pro vibe coding v PHP s Nette: jak psát prompty, které fungují, jak využít MCP Inspector, osvědčené postupy a čeho se vyvarovat.}} diff --git a/ai/en/agent-plugins.texy b/ai/en/agent-plugins.texy index 9d1ac8e198..8c860d81c7 100644 --- a/ai/en/agent-plugins.texy +++ b/ai/en/agent-plugins.texy @@ -473,3 +473,5 @@ Privacy The plugins collect no data. They run locally and have no servers, telemetry or analytics. See the [privacy policy |privacy-policy] for details. {{repo: nette/agent-plugins}} +{{maintitle: Nette Plugins for Claude Code and Codex: AI Agent Skills}} +{{description: Give Claude Code and Codex deep knowledge of Nette. Instead of generic PHP advice, you get recommendations that follow Nette conventions.}} diff --git a/ai/en/getting-started.texy b/ai/en/getting-started.texy index b265d09e84..3fa8b4f4ae 100644 --- a/ai/en/getting-started.texy +++ b/ai/en/getting-started.texy @@ -257,4 +257,5 @@ You're now ready for AI-assisted Nette development! Here's where to go from here - [Agent Plugins |agent-plugins] - Explore all the skills (Claude Code and Codex users) - [Vibe Coding in Practice |vibe-coding] - Get the most out of your AI assistant +{{maintitle: Vibe Coding with Nette: Getting Started with Claude Code}} {{description: Set up vibe coding with Nette in about ten minutes: install Claude Code, add the Nette plugin, and connect MCP Inspector to your application.}} diff --git a/ai/en/mcp-inspector.texy b/ai/en/mcp-inspector.texy index c75ee4aae7..500d1fcfc2 100644 --- a/ai/en/mcp-inspector.texy +++ b/ai/en/mcp-inspector.texy @@ -324,3 +324,5 @@ The AI can now call `blog_get_post` like any built-in tool. Try it first from th {{composer: nette/mcp-inspector}} {{repo: nette/mcp-inspector}} +{{maintitle: Nette MCP Inspector: Let AI See Inside Your Application}} +{{description: MCP Inspector lets an AI assistant look directly into your Nette application: DI services, database tables, routes and Tracy logs, instead of guessing.}} diff --git a/ai/en/privacy-policy.texy b/ai/en/privacy-policy.texy index 37ca5d2c12..c7ed219f76 100644 --- a/ai/en/privacy-policy.texy +++ b/ai/en/privacy-policy.texy @@ -61,4 +61,5 @@ Contact The plugins are maintained by David Grudl and the Nette Foundation. If you have a question about this policy or about the plugins, please open an issue at "github.com/nette/agent-plugins":https://github.com/nette/agent-plugins/issues. +{{maintitle: Privacy Policy for Nette Agent Plugins}} {{description: The Nette plugins for Claude Code and Codex collect no data. They run locally and have no servers, telemetry or analytics.}} diff --git a/ai/en/vibe-coding.texy b/ai/en/vibe-coding.texy index 1c7788484b..a79da50c08 100644 --- a/ai/en/vibe-coding.texy +++ b/ai/en/vibe-coding.texy @@ -295,4 +295,5 @@ And remember: the AI is your assistant. You're still the developer. You make the Happy coding! +{{maintitle: Vibe Coding in PHP with Nette: Prompts and Best Workflows}} {{description: Practical advice for vibe coding in PHP with Nette: writing prompts that work, using MCP Inspector well, proven workflows, and mistakes to avoid.}} diff --git a/application/cs/@home.texy b/application/cs/@home.texy index 88228c1487..04526db5f2 100644 --- a/application/cs/@home.texy +++ b/application/cs/@home.texy @@ -83,3 +83,6 @@ Kompatibilita s PHP | Nette Application 2.4 | PHP 5.6 - 8.0 Platí pro poslední patch verze. + +{{maintitle: Nette Application: PHP framework pro webové aplikace}} +{{description: Jádro frameworku Nette: obousměrný router, presentery, znovupoužitelné komponenty se signály a bezpečné šablony Latte pro moderní webové aplikace.}} diff --git a/application/cs/ajax.texy b/application/cs/ajax.texy index 1e5f8bd9e5..8174051dc0 100644 --- a/application/cs/ajax.texy +++ b/application/cs/ajax.texy @@ -263,3 +263,6 @@ Další četba =========== - [Dynamické snippety |best-practices:dynamic-snippets] + +{{maintitle: AJAX a snippety v Nette: překreslení části stránky}} +{{description: Překreslete jen to, co se změnilo, bez načtení celé stránky: snippety v šablonách Latte, AJAXové požadavky s knihovnou Naja a předávání parametrů z prohlížeče.}} diff --git a/application/cs/bootstrapping.texy b/application/cs/bootstrapping.texy index c40a9ea5ac..b5af5d8fd5 100644 --- a/application/cs/bootstrapping.texy +++ b/application/cs/bootstrapping.texy @@ -310,3 +310,6 @@ public function bootConsoleApplication(): Nette\DI\Container return $this->configurator->createContainer(); } ``` + +{{maintitle: Bootstrapping aplikace v Nette: od index.php po DI kontejner}} +{{description: Jak se aplikace v Nette spouští: od index.php a třídy Configurator přes vývojářský režim, Tracy a dočasné soubory až po konfiguraci v NEON.}} diff --git a/application/cs/components.texy b/application/cs/components.texy index 08f8f8df35..d249f2fcdb 100644 --- a/application/cs/components.texy +++ b/application/cs/components.texy @@ -502,3 +502,6 @@ if ($this->isSignalReceiver($this, 'paging') || $this->isSignalReceiver($this, ' ``` Tím je signál provedený předčasně a už se nebude znovu volat. + +{{maintitle: Interaktivní komponenty v Nette: signály a AJAX}} +{{description: Formulář, datagrid nebo anketu napíšete jednou a použijete kdekoliv. Tovární metody, vykreslení, signály, AJAX, flash zprávy a persistentní parametry.}} diff --git a/application/cs/configuration.texy b/application/cs/configuration.texy index 84d79b50a3..1ce20ce3f3 100644 --- a/application/cs/configuration.texy +++ b/application/cs/configuration.texy @@ -184,3 +184,6 @@ Tyto služby se přidávají do DI kontejneru: | `routing.router` | [api:Nette\Routing\Router] | směrovač | `latte.latteFactory` | [api:Nette\Bridges\ApplicationLatte\LatteFactory] | továrna objektu `Latte\Engine` | `latte.templateFactory` | [api:Nette\Application\UI\TemplateFactory] | továrna pro [`$this->template` |templates] + +{{maintitle: Konfigurace Nette Application: volby v NEON}} +{{description: Konfigurace Nette Application v NEON: error presenter, mapování presenterů, šablony Latte, routování, konstanty, nastavení PHP a služby DI.}} diff --git a/application/cs/creating-links.texy b/application/cs/creating-links.texy index 703a1206ea..6cc1a6fdef 100644 --- a/application/cs/creating-links.texy +++ b/application/cs/creating-links.texy @@ -317,3 +317,6 @@ LinkGenerator je služba, kterou si můžete nechat předat přes konstruktor a Oproti presenterům je tu rozdíl. LinkGenerator vytváří všechny odkazy rovnou jako absolutní URL. A dále neexistuje žádný "aktuální presenter", takže nelze jako cíl uvést jen název akce `link('default')` nebo uvádět relativní cesty k modulům. Neplatné odkazy vždy vyhazují `Nette\Application\UI\InvalidLinkException`. + +{{maintitle: Odkazy v Nette: šablony, presentery a LinkGenerator}} +{{description: Odkazy na presentery, akce a signály pomocí n:href a link(), zvýraznění aktuální stránky v menu, odhalení neplatných odkazů a generování URL mimo presenter.}} diff --git a/application/cs/directory-structure.texy b/application/cs/directory-structure.texy index c1620c48bf..bf42818d93 100644 --- a/application/cs/directory-structure.texy +++ b/application/cs/directory-structure.texy @@ -524,3 +524,6 @@ application: *: [App\Presentation, *, **Presenter] Api: [App\Api, '', *Presenter] ``` + +{{maintitle: Adresářová struktura projektu v Nette: jak uspořádat kód}} +{{description: Přehledná a škálovatelná adresářová struktura projektů v Nette: kam patří presentery, šablony, model a infrastrukturní kód a jak funguje mapování presenterů.}} diff --git a/application/cs/how-it-works.texy b/application/cs/how-it-works.texy index 63516d0459..58d62dcb4c 100644 --- a/application/cs/how-it-works.texy +++ b/application/cs/how-it-works.texy @@ -198,3 +198,6 @@ Prošli jsme si základní principy aplikací v Nette. Zatím velmi povrchně, a Kromě výše popsaného disponuje Nette celým arzenálem [užitečných tříd|utils:], [databázovou vrstvou|database:], atd. Zkuste si schválně jen tak proklikat dokumentaci. Nebo [blog|https://blog.nette.org]. Objevíte spoustu zajímavého. Ať vám framework přináší spoustu radosti 💙 + +{{maintitle: Jak fungují aplikace v Nette: od požadavku k odpovědi}} +{{description: Základní kapitola dokumentace Nette: krok za krokem sledujete cestu webové aplikace od HTTP požadavku přes router a presenter až po vykreslení šablony.}} diff --git a/application/cs/multiplier.texy b/application/cs/multiplier.texy index dddd5f573a..c1553453bb 100644 --- a/application/cs/multiplier.texy +++ b/application/cs/multiplier.texy @@ -61,3 +61,6 @@ protected function createComponentShopForm(): Multiplier }); } ``` + +{{maintitle: Multiplier v Nette: dynamické vytváření komponent}} +{{description: Potřebujete u každého produktu formulář Přidat do košíku? Multiplier vytvoří tolik samostatných komponent, kolik je třeba, takže každá položka má tu svou.}} diff --git a/application/cs/presenters.texy b/application/cs/presenters.texy index a867660fb6..186bf5777f 100644 --- a/application/cs/presenters.texy +++ b/application/cs/presenters.texy @@ -593,3 +593,6 @@ Další četba - [Skládání presenterů z trait |best-practices:presenter-traits] - [Předání nastavení do presenterů |best-practices:passing-settings-to-presenters] - [Jak se vrátit k dřívější stránce |best-practices:restore-request] + +{{maintitle: Presentery v Nette: životní cyklus, akce a parametry}} +{{description: Jak presenter v Nette zpracuje požadavek, od životního cyklu a vykreslení šablony přes přesměrování a chybové stránky po JSON a persistentní parametry.}} diff --git a/application/cs/routing.texy b/application/cs/routing.texy index e7f69b6cb7..37a1602524 100644 --- a/application/cs/routing.texy +++ b/application/cs/routing.texy @@ -747,3 +747,5 @@ $url = $router->constructUrl($params, $httpRequest->getUrl()); {{composer: nette/routing}} {{repo: nette/routing}} {{api: https://api.nette.org/routing/}} +{{maintitle: Routování v PHP s Nette: hezké URL a SEO}} +{{description: Všechny URL definujete na jednom místě a kdykoliv je změníte bez zásahu do šablon. Masky rout, automatická kanonizace, vlastní router i samostatné použití.}} diff --git a/application/cs/templates.texy b/application/cs/templates.texy index b5ae830d67..e2bee7f9c8 100644 --- a/application/cs/templates.texy +++ b/application/cs/templates.texy @@ -417,3 +417,6 @@ protected function beforeRender(): void ``` Statickým textem je myšleno třeba `{_'hello'}` nebo `{translate}hello{/translate}`. Nestatické texty, jako třeba `{_$foo}`, se nadále budou překládat za běhu. + +{{maintitle: Šablony v Nette: jak presentery používají Latte}} +{{description: Jak presentery v Nette pracují se šablonami Latte: hledání šablon a layoutu, proměnné, typově bezpečné šablony, odkazy, vlastní filtry a tagy, překlady.}} diff --git a/application/cs/upgrading.texy b/application/cs/upgrading.texy index d4b144c738..c9b57d0f6c 100644 --- a/application/cs/upgrading.texy +++ b/application/cs/upgrading.texy @@ -45,3 +45,6 @@ Upgrade na verzi 2.3 - routy a názvy presenterů jsou **case-sensitive**. Nette vás upozorní, pokud v názvu presenteru použijete špatnou velikost písmen; masku routy z výkonnostních důvodů nekontroluje, ověřte si ji tedy ručně. - `Route::addStyle()` a `Route::setStyleProperty()` jsou zastaralé a nyní vyvolají `E_USER_DEPRECATED`. - přípona šablony `.phtml` a stará syntaxe odkazů se již nepodporují. + +{{maintitle: Upgrade Nette Application: změny v jednotlivých verzích}} +{{description: Co se změnilo v Nette Application 3.0, 2.4 a 2.3 a jak upravit kód: typehinty, rozhraní routeru, same-origin kontrola signálů a další.}} diff --git a/application/en/@home.texy b/application/en/@home.texy index 6552aab1eb..b7407ce96a 100644 --- a/application/en/@home.texy +++ b/application/en/@home.texy @@ -83,3 +83,6 @@ PHP Compatibility | Nette Application 2.4 | PHP 5.6 - 8.0 Valid for the latest patch versions. + +{{maintitle: Nette Application: PHP Framework for Web Applications}} +{{description: The core of the Nette framework: a bidirectional router, presenters, reusable components with signals and secure Latte templates for modern web applications.}} diff --git a/application/en/ajax.texy b/application/en/ajax.texy index e6a0919e4a..50a618f208 100644 --- a/application/en/ajax.texy +++ b/application/en/ajax.texy @@ -263,3 +263,6 @@ Further Reading =============== - [Dynamic Snippets |best-practices:dynamic-snippets] + +{{maintitle: AJAX and Snippets in Nette: Update Parts of a Page}} +{{description: Redraw only what changed, without reloading the page: snippets in Latte templates, AJAX requests with the Naja library and passing parameters from the browser.}} diff --git a/application/en/bootstrapping.texy b/application/en/bootstrapping.texy index 1fcef2414c..84644a836d 100644 --- a/application/en/bootstrapping.texy +++ b/application/en/bootstrapping.texy @@ -310,3 +310,6 @@ public function bootConsoleApplication(): Nette\DI\Container return $this->configurator->createContainer(); } ``` + +{{maintitle: Bootstrapping a Nette App: From index.php to DI Container}} +{{description: See how a Nette application starts, from index.php and the Configurator class through development mode, Tracy and temporary files to the NEON configuration.}} diff --git a/application/en/components.texy b/application/en/components.texy index 28bbf8dac7..b0da2bfe5f 100644 --- a/application/en/components.texy +++ b/application/en/components.texy @@ -502,3 +502,6 @@ if ($this->isSignalReceiver($this, 'paging') || $this->isSignalReceiver($this, ' ``` This executes the signal prematurely, and it will not be called again. + +{{maintitle: Nette Components: Reusable UI with Signals and AJAX}} +{{description: Write a form, data grid or poll once and reuse it on any page. Factory methods, rendering, signals, AJAX snippets, flash messages and persistent parameters.}} diff --git a/application/en/configuration.texy b/application/en/configuration.texy index 09fed449ef..2fe9536e5d 100644 --- a/application/en/configuration.texy +++ b/application/en/configuration.texy @@ -184,3 +184,6 @@ These services are added to the DI container: | `routing.router` | [api:Nette\Routing\Router] | router | `latte.latteFactory` | [api:Nette\Bridges\ApplicationLatte\LatteFactory] | factory for `Latte\Engine` object | `latte.templateFactory` | [api:Nette\Application\UI\TemplateFactory] | factory for [`$this->template` |templates] + +{{maintitle: Nette Application Configuration: Options in NEON}} +{{description: Configure Nette Application in NEON: the error presenter, presenter mapping, Latte templates, routing, constants, PHP settings and DI services.}} diff --git a/application/en/creating-links.texy b/application/en/creating-links.texy index c841e96c2b..625ee37bcf 100644 --- a/application/en/creating-links.texy +++ b/application/en/creating-links.texy @@ -317,3 +317,6 @@ LinkGenerator is a service that you can have passed via the constructor and then There is a difference compared to presenters. LinkGenerator creates all links directly as absolute URLs. Furthermore, there is no "current presenter", so it is not possible to specify only the action name `link('default')` as the target or use relative paths to modules. Invalid links always throw `Nette\Application\UI\InvalidLinkException`. + +{{maintitle: Creating Links in Nette: Templates, Presenters, LinkGenerator}} +{{description: Link to presenters, actions and signals with n:href and link(), highlight the current page in a menu, catch invalid links and generate URLs outside presenters.}} diff --git a/application/en/directory-structure.texy b/application/en/directory-structure.texy index 9f837dc25f..2c60db28d2 100644 --- a/application/en/directory-structure.texy +++ b/application/en/directory-structure.texy @@ -524,3 +524,6 @@ application: *: [App\Presentation, *, **Presenter] Api: [App\Api, '', *Presenter] ``` + +{{maintitle: Nette Directory Structure: Organize Your PHP Project}} +{{description: A clear, scalable structure for Nette projects: where presenters, templates, the model and infrastructure code belong, and how presenter mapping works.}} diff --git a/application/en/how-it-works.texy b/application/en/how-it-works.texy index 0f2a627fdc..5917431664 100644 --- a/application/en/how-it-works.texy +++ b/application/en/how-it-works.texy @@ -198,3 +198,6 @@ We've covered the fundamental principles of Nette applications. While it's been In addition to what's described above, Nette offers a whole arsenal of [useful classes|utils:], a [database layer|database:], etc. Try clicking through the documentation. Or visit the [blog|https://blog.nette.org]. You'll discover many interesting things. May the framework bring you much joy 💙 + +{{maintitle: How Nette Applications Work: From Request to Response}} +{{description: The foundational chapter of the Nette docs: follow a web application step by step from the HTTP request through router and presenter to the rendered template.}} diff --git a/application/en/multiplier.texy b/application/en/multiplier.texy index 3f8e6dcbac..d459ebda66 100644 --- a/application/en/multiplier.texy +++ b/application/en/multiplier.texy @@ -61,3 +61,6 @@ protected function createComponentShopForm(): Multiplier }); } ``` + +{{maintitle: Nette Multiplier: Create Components Dynamically}} +{{description: Need an Add to Cart form for every product? Multiplier creates as many independent components as you need, so each list item gets its own form or control.}} diff --git a/application/en/presenters.texy b/application/en/presenters.texy index 15e69e8988..50f580bbaa 100644 --- a/application/en/presenters.texy +++ b/application/en/presenters.texy @@ -593,3 +593,6 @@ Further Reading - [Composing presenters from traits |best-practices:presenter-traits] - [Passing settings to presenters |best-practices:passing-settings-to-presenters] - [How to Return to a Previous Page |best-practices:restore-request] + +{{maintitle: Nette Presenters: Life Cycle, Actions and Parameters}} +{{description: How a presenter handles a request in Nette, from its life cycle and template rendering to redirects, error pages, JSON responses and persistent parameters.}} diff --git a/application/en/routing.texy b/application/en/routing.texy index 4c6c32aa86..fa2b148882 100644 --- a/application/en/routing.texy +++ b/application/en/routing.texy @@ -747,3 +747,5 @@ $url = $router->constructUrl($params, $httpRequest->getUrl()); {{composer: nette/routing}} {{repo: nette/routing}} {{api: https://api.nette.org/routing/}} +{{maintitle: PHP Routing with Nette Router: Clean URLs and SEO}} +{{description: Define all URLs in one place and change them anytime without touching templates. Route masks, automatic canonicalization, custom routers and standalone use.}} diff --git a/application/en/templates.texy b/application/en/templates.texy index 8466900e39..e51a220d1d 100644 --- a/application/en/templates.texy +++ b/application/en/templates.texy @@ -417,3 +417,6 @@ protected function beforeRender(): void ``` Static text means, for example, `{_'hello'}` or `{translate}hello{/translate}`. Non-static texts, like `{_$foo}`, will continue to be translated at runtime. + +{{maintitle: Nette Templates: Using Latte in Presenters}} +{{description: How Nette presenters work with Latte templates: template and layout lookup, variables, type-safe templates, links, custom filters and tags, and translations.}} diff --git a/application/en/upgrading.texy b/application/en/upgrading.texy index f95527093f..ae8b8e8a91 100644 --- a/application/en/upgrading.texy +++ b/application/en/upgrading.texy @@ -45,3 +45,6 @@ Upgrading to Version 2.3 - routes and presenter names are **case-sensitive**. Nette warns you if you use the wrong case in a presenter name; for performance reasons the Route mask is not checked, so verify it manually. - `Route::addStyle()` and `Route::setStyleProperty()` are deprecated and now trigger `E_USER_DEPRECATED`. - the template extension `.phtml` and the old link syntax are no longer supported. + +{{maintitle: Upgrading Nette Application: What Changed in Each Version}} +{{description: What changed in Nette Application 3.0, 2.4 and 2.3, and how to update your code: type hints, the router interface, same-origin signals and more.}} diff --git a/assets/cs/@home.texy b/assets/cs/@home.texy index 608dc76068..9409d66d2b 100644 --- a/assets/cs/@home.texy +++ b/assets/cs/@home.texy @@ -473,3 +473,6 @@ Další četba =========== - [Nette Assets: Konečně jednotné API pro vše od obrázků po Vite |https://blog.nette.org/cs/predstaveni-nette-assets] + +{{maintitle: Nette Assets: správa statických souborů v PHP aplikacích}} +{{description: Žádné natvrdo zapsané cesty ani starosti se zneplatněním cache. Nette Assets spravuje obrázky, styly a skripty ve vaší PHP aplikaci, v kódu i v šablonách Latte.}} diff --git a/assets/cs/configuration.texy b/assets/cs/configuration.texy index 25ff87c45b..1db1a731d9 100644 --- a/assets/cs/configuration.texy +++ b/assets/cs/configuration.texy @@ -194,3 +194,6 @@ Kterýkoli zaregistrovaný mapper můžete také získat podle jména metodou `g $mapper = $registry->getMapper('images'); // vrátí zaregistrovaný mapper $default = $registry->getMapper(); // vrátí mapper 'default' ``` + +{{maintitle: Konfigurace Nette Assets: mappery, cesty a verzování}} +{{description: Konfigurace Nette Assets v NEON: základní cesta a URL, globální verzování a mappery, které určují, kde jsou vaše statické soubory, včetně Vite.}} diff --git a/assets/cs/vite.texy b/assets/cs/vite.texy index 79a67b0497..f1d984507b 100644 --- a/assets/cs/vite.texy +++ b/assets/cs/vite.texy @@ -619,3 +619,6 @@ export default defineConfig({ Pozor na cesty ke vstupním bodům v `rollupOptions.input` výše: Rollup resolvuje relativní cesty vůči aktuálnímu pracovnímu adresáři (kořeni projektu), **ne** vůči `root: 'assets'`. Holé `'app.js'` proto při buildu neexistuje. Buď použijte volbu pluginu `entry` (ta řeší cesty relativně ke `root`), nebo cesty pište relativně ke kořeni projektu, např. `'assets/app.js'`. To je vše! Nyní máte moderní build systém integrovaný s Nette Assets. + +{{maintitle: Vite v PHP s Nette Assets: HMR a produkční buildy}} +{{description: Prvotřídní integrace Vite pro PHP aplikace: bleskový vývoj s Hot Module Replacement, optimalizované produkční buildy, vstupní body a TypeScript.}} diff --git a/assets/en/@home.texy b/assets/en/@home.texy index 51f1c015ea..e7bffb6cb0 100644 --- a/assets/en/@home.texy +++ b/assets/en/@home.texy @@ -473,3 +473,6 @@ Further Reading =============== - [Nette Assets: Finally unified API for everything from images to Vite |https://blog.nette.org/en/introducing-nette-assets] + +{{maintitle: Nette Assets: Manage Static Files in PHP Applications}} +{{description: Stop hardcoding paths and worrying about cache invalidation. Nette Assets manages images, styles and scripts in your PHP app, in code and in Latte templates.}} diff --git a/assets/en/configuration.texy b/assets/en/configuration.texy index d3e5224db5..b18b3586f7 100644 --- a/assets/en/configuration.texy +++ b/assets/en/configuration.texy @@ -194,3 +194,6 @@ You can also retrieve any registered mapper by name using the `getMapper()` meth $mapper = $registry->getMapper('images'); // returns the registered mapper $default = $registry->getMapper(); // returns the 'default' mapper ``` + +{{maintitle: Nette Assets Configuration: Mappers, Paths and Versioning}} +{{description: Configure Nette Assets in NEON: the base path and URL, global versioning and the mappers that say where your static files live, including Vite.}} diff --git a/assets/en/vite.texy b/assets/en/vite.texy index 30e11c154b..2508b8d4a7 100644 --- a/assets/en/vite.texy +++ b/assets/en/vite.texy @@ -619,3 +619,6 @@ export default defineConfig({ Watch out for the entry paths in `rollupOptions.input` above: Rollup resolves relative paths against the current working directory (your project root), **not** against `root: 'assets'`. So a bare `'app.js'` won't exist at build time. Either use the plugin's `entry` option (which resolves entry paths relative to `root`), or write the paths relative to the project root, e.g. `'assets/app.js'`. That's it! You now have a modern build system integrated with Nette Assets. + +{{maintitle: Vite in PHP with Nette Assets: HMR and Production Builds}} +{{description: First-class Vite integration for PHP apps: lightning-fast development with Hot Module Replacement, optimized production builds, entry points and TypeScript.}} diff --git a/best-practices/cs/@home.texy b/best-practices/cs/@home.texy index e95aa101a3..5fae2af477 100644 --- a/best-practices/cs/@home.texy +++ b/best-practices/cs/@home.texy @@ -67,3 +67,6 @@ Stovky záznamů z Posledních sobot a videí o Nette naleznete pod jednou stře + +{{maintitle: Návody a best practices pro Nette: řešení častých úloh}} +{{description: Návody, řešení častých úloh a best practices pro Nette: formuláře, stránkování, hezké URL, presentery, Composer a další.}} diff --git a/best-practices/cs/attribute-requires.texy b/best-practices/cs/attribute-requires.texy index 8effbed720..ff1e795871 100644 --- a/best-practices/cs/attribute-requires.texy +++ b/best-practices/cs/attribute-requires.texy @@ -175,3 +175,6 @@ Závěr ----- Atribut `#[Requires]` vám dává velkou flexibilitu a kontrolu nad tím, jak jsou vaše webové stránky přístupné. Pomocí jednoduchých, ale mocných pravidel můžete zvýšit bezpečnost a správné fungování vaší aplikace. Jak vidíte, použití atributů v Nette může vaši práci nejen usnadnit, ale i zabezpečit. + +{{maintitle: Atribut #[Requires] v Nette: omezení přístupu k presenterům}} +{{description: Omezte presenter nebo akci jen na požadavky POST, AJAX, stejný původ nebo přístup přes forward, a to jediným atributem #[Requires].}} diff --git a/best-practices/cs/composer.texy b/best-practices/cs/composer.texy index 15a0534723..fafd158920 100644 --- a/best-practices/cs/composer.texy +++ b/best-practices/cs/composer.texy @@ -280,3 +280,6 @@ Composer je úzce propojený s verzovacím nástrojem [Git |https://git-scm.com] ```shell composer -g config preferred-install dist ``` + +{{maintitle: Composer v PHP: instalace a správa závislostí}} +{{description: Nainstalujte Composer, přidejte do PHP projektu knihovny, aktualizujte je a využijte autoloading. Praktické tipy k verzím PHP, Packagistu a planým hlášením.}} diff --git a/best-practices/cs/creating-editing-form.texy b/best-practices/cs/creating-editing-form.texy index c47c9f7535..fd2927f35a 100644 --- a/best-practices/cs/creating-editing-form.texy +++ b/best-practices/cs/creating-editing-form.texy @@ -202,3 +202,5 @@ class RecordPresenter extends Nette\Application\UI\Presenter ``` {{priority: -1}} +{{maintitle: Jeden formulář pro přidání i editaci záznamu v Nette}} +{{description: Jak v Nette správně implementovat přidání i editaci záznamu v databázi pomocí jednoho společného formuláře, včetně výchozích hodnot a zpracování.}} diff --git a/best-practices/cs/dynamic-snippets.texy b/best-practices/cs/dynamic-snippets.texy index fb05bbd60f..5e5821f8a8 100644 --- a/best-practices/cs/dynamic-snippets.texy +++ b/best-practices/cs/dynamic-snippets.texy @@ -174,3 +174,5 @@ protected function createComponentLikeControl() Máme téměř hotovo: aplikace nyní bude fungovat AJAXově. I zde nás čeká aplikaci optimalizovat, protože vzhledem k použití Nette Database se při zpracování signálu zbytečně načtou všechny články z databáze namísto jednoho. Výhodou však je, že nedojde k jejich vykreslování, protože se vyrenderuje skutečně jen naše komponenta. {{priority: -1}} +{{maintitle: Dynamické snippety v Nette: obnova položek seznamu přes AJAX}} +{{description: Obnovte přes AJAX jen to, co se opravdu změnilo, třeba jednu položku seznamu. Dva způsoby v Nette: dynamické snippety v Latte a komponenty.}} diff --git a/best-practices/cs/form-reuse.texy b/best-practices/cs/form-reuse.texy index 5a7a520878..29f101405c 100644 --- a/best-practices/cs/form-reuse.texy +++ b/best-practices/cs/form-reuse.texy @@ -346,3 +346,6 @@ class MyPresenter extends Nette\Application\UI\Presenter } } ``` + +{{maintitle: Znovupoužití formulářů v Nette: továrny a komponenty}} +{{description: Použijte stejný formulář na více místech bez duplikace kódu: továrny a komponenty s formulářem a také řešení, kterým je lepší se vyhnout, jako je dědění.}} diff --git a/best-practices/cs/inject-method-attribute.texy b/best-practices/cs/inject-method-attribute.texy index d22dafecbd..9d29772a68 100644 --- a/best-practices/cs/inject-method-attribute.texy +++ b/best-practices/cs/inject-method-attribute.texy @@ -59,3 +59,6 @@ class MyPresenter extends Nette\Application\UI\Presenter Výhodou tohoto způsobu předávání závislostí byla velice úsporná podoba zápisu. Nicméně s příchodem [constructor property promotion |https://blog.nette.org/cs/php-8-0-kompletni-prehled-novinek#toc-constructor-property-promotion] se jeví snazší použít konstruktor. Naopak tento způsob trpí stejnými nedostatky, jako předávání závislosti do properties obecně: nemáme kontrolu nad změnami v proměnné a zároveň se proměnná stává součástí veřejného rozhraní třídy, což je nežádoucí. + +{{maintitle: Metody a atributy inject v presenterech Nette}} +{{description: Způsoby předávání závislostí do presenterů v Nette: preferovaný konstruktor v porovnání s metodami inject a atributem Inject.}} diff --git a/best-practices/cs/lets-create-contact-form.texy b/best-practices/cs/lets-create-contact-form.texy index 573befbc70..f2f06be156 100644 --- a/best-practices/cs/lets-create-contact-form.texy +++ b/best-practices/cs/lets-create-contact-form.texy @@ -216,3 +216,6 @@ parameters: ``` A je hotovo! + +{{maintitle: Kontaktní formulář v PHP s Nette: odeslání na e-mail}} +{{description: Vytvořte krok za krokem kontaktní formulář v Nette, od samotného formuláře až po odeslání dat na e-mail pomocí šablony Latte.}} diff --git a/best-practices/cs/microsites.texy b/best-practices/cs/microsites.texy index fb27c0ce3b..29fc8e5379 100644 --- a/best-practices/cs/microsites.texy +++ b/best-practices/cs/microsites.texy @@ -61,3 +61,6 @@ Proč používat Nette pro microsite? - Někdy se vám může hodit [kešování|caching:], například pokud stahujete a zobrazujete feedy. V dnešní době, kdy je rychlost a efektivita klíčová, je důležité mít nástroje, které vám umožní dosáhnout výsledků bez zbytečného zdržování. Nette framework vám nabízí právě to - rychlý vývoj, bezpečnost a širokou škálu nástrojů, jako je Tracy a Latte, které zjednodušují proces. Stačí nainstalovat pár Nette balíčků a vybudovat takovou microsite je najednou úplná hračka. A víte, že se nikde neskrývá žádná bezpečnostní díra. + +{{maintitle: Mikroweby v Nette: malý web v jednom PHP souboru}} +{{description: Potřebujete rychle malý web? Celý jeho kód se vejde do jednoho index.php s routováním Nette a šablonami Latte a přitom máte Tracy i další vymoženosti.}} diff --git a/best-practices/cs/pagination.texy b/best-practices/cs/pagination.texy index b472525c7b..ed02e65eb5 100644 --- a/best-practices/cs/pagination.texy +++ b/best-practices/cs/pagination.texy @@ -271,3 +271,5 @@ Protože do šablony nyní neposíláme Paginator, upravíme část zobrazujíc Tímto způsobem jsme implementovali stránkovací mechanismus bez použití Paginatoru. {{priority: -1}} +{{maintitle: Stránkování výsledků z databáze v PHP s Nette}} +{{description: Výpis výsledků z databáze po stránkách v Nette: metoda v repozitáři, třída Paginator, odkazy v šabloně a jednodušší cesta s Nette Database Explorerem.}} diff --git a/best-practices/cs/passing-settings-to-presenters.texy b/best-practices/cs/passing-settings-to-presenters.texy index 941783e97d..f52e891163 100644 --- a/best-practices/cs/passing-settings-to-presenters.texy +++ b/best-practices/cs/passing-settings-to-presenters.texy @@ -47,3 +47,6 @@ class MyPresenter extends Nette\Application\UI\Presenter } } ``` + +{{maintitle: Předání nastavení do presenterů v Nette: objekt Settings}} +{{description: Potřebujete do presenterů předat hodnoty, které nejsou objekty, třeba debug režim nebo cesty k adresářům? Autowiring to neumí, zabalte je do objektu Settings.}} diff --git a/best-practices/cs/post-links.texy b/best-practices/cs/post-links.texy index 1de8883a78..5926f5a880 100644 --- a/best-practices/cs/post-links.texy +++ b/best-practices/cs/post-links.texy @@ -54,3 +54,6 @@ public function handleDelete(int $id): void ``` Tento přístup nejenže zlepšuje bezpečnost vaší aplikace, ale také přispívá k dodržování správných webových standardů a praxe. Využitím metod POST pro akce měnící stav dosáhnete robustnější a bezpečnější aplikace. + +{{maintitle: POST odkazy v Nette: neměňte stav serveru přes GET}} +{{description: Akce měnící stav serveru nesmí používat GET. Jak v Nette vytvořit POST odkazy pomocí Latte a zabezpečit je atributem #[Requires].}} diff --git a/best-practices/cs/presenter-traits.texy b/best-practices/cs/presenter-traits.texy index b9a6bdc77b..95f05f53db 100644 --- a/best-practices/cs/presenter-traits.texy +++ b/best-practices/cs/presenter-traits.texy @@ -45,3 +45,6 @@ class ArticlePresenter extends Nette\Application\UI\Presenter use RequireLoggedUser; } ``` + +{{maintitle: Skládání presenterů v Nette z trait}} +{{description: Sdílejte kód, jako je ověření přihlášení, napříč presentery pomocí jednoúčelových trait místo společného předka, včetně toho, jak se trait zapojí do startu.}} diff --git a/best-practices/cs/pretty-urls.texy b/best-practices/cs/pretty-urls.texy index 397ec995f1..ca1c7bda0f 100644 --- a/best-practices/cs/pretty-urls.texy +++ b/best-practices/cs/pretty-urls.texy @@ -202,3 +202,6 @@ Shrnutí - Krátké URL jen s ID dál fungují, což se hodí pro QR kódy a SMS. Více o filtrech a kanonizaci najdete v dokumentaci [routování |application:routing#obecne-filtry] a [presenterů |application:presenters#kanonizace]. + +{{maintitle: Hezké URL se slugem v Nette: routování přátelské k SEO}} +{{description: Z adresy /clanek/123 udělejte /clanek/123-jak-upect-chleba přímo v routeru, bez zásahu do šablon, a staré adresy přesměrujte na tu správnou.}} diff --git a/best-practices/cs/restore-request.texy b/best-practices/cs/restore-request.texy index c5f6c94511..887e045417 100644 --- a/best-practices/cs/restore-request.texy +++ b/best-practices/cs/restore-request.texy @@ -60,3 +60,5 @@ Metodě `restoreRequest()` předáme klíč uloženého požadavku a ona přesm Pokud je ale klíč neplatný (například už v session neexistuje), metoda neudělá nic. Následuje tedy volání `$this->redirect('Admin:')`, které přesměruje na `AdminPresenter`. {{priority: -1}} +{{maintitle: Návrat na předchozí stránku v Nette: obnovení požadavku}} +{{description: Uživateli vyprší přihlášení při vyplňování formuláře? Uložte aktuální požadavek do session, přesměrujte na přihlášení a poté ho obnovte, aniž by přišel o data.}} diff --git a/best-practices/en/@home.texy b/best-practices/en/@home.texy index 630ab6a882..2a8cb1b0d5 100644 --- a/best-practices/en/@home.texy +++ b/best-practices/en/@home.texy @@ -67,3 +67,6 @@ Hundreds of recordings from Last Saturday meetups and videos about Nette can all + +{{maintitle: Nette Tutorials and Best Practices: Common Tasks Solved}} +{{description: Tutorials, solutions to common tasks and best practices for Nette: forms, pagination, pretty URLs, presenters, Composer and more.}} diff --git a/best-practices/en/attribute-requires.texy b/best-practices/en/attribute-requires.texy index 129c6f6563..f19a254de1 100644 --- a/best-practices/en/attribute-requires.texy +++ b/best-practices/en/attribute-requires.texy @@ -175,3 +175,6 @@ Conclusion ---------- The `#[Requires]` attribute gives you great flexibility and control over how your web pages are accessed. Using simple, yet powerful rules, you can enhance the security and proper functioning of your application. As you can see, using attributes in Nette can not only simplify your work but also secure it. + +{{maintitle: Nette #[Requires] Attribute: Restrict Access to Presenters}} +{{description: Restrict a presenter or action to POST requests, AJAX calls, the same origin or forward-only access with a single #[Requires] attribute.}} diff --git a/best-practices/en/composer.texy b/best-practices/en/composer.texy index ab81e44d8a..0432b9c9bd 100644 --- a/best-practices/en/composer.texy +++ b/best-practices/en/composer.texy @@ -280,3 +280,6 @@ Composer is closely integrated with the version control tool [Git |https://git-s ```shell composer -g config preferred-install dist ``` + +{{maintitle: Composer for PHP: Install It and Manage Dependencies}} +{{description: Install Composer, add libraries to your PHP project, update them and use autoloading. Practical tips on PHP versions, Packagist and false reports.}} diff --git a/best-practices/en/creating-editing-form.texy b/best-practices/en/creating-editing-form.texy index 86003dffc6..24a8f21f9a 100644 --- a/best-practices/en/creating-editing-form.texy +++ b/best-practices/en/creating-editing-form.texy @@ -202,3 +202,5 @@ class RecordPresenter extends Nette\Application\UI\Presenter ``` {{priority: -1}} +{{maintitle: One Form for Adding and Editing a Record in Nette}} +{{description: How to properly implement adding and editing a database record in Nette with one shared form, including default values and form processing.}} diff --git a/best-practices/en/dynamic-snippets.texy b/best-practices/en/dynamic-snippets.texy index 499b0c70c4..28e52df8d9 100644 --- a/best-practices/en/dynamic-snippets.texy +++ b/best-practices/en/dynamic-snippets.texy @@ -174,3 +174,5 @@ The view's template shrinks to the bare minimum (and is completely free of snipp We're almost finished: the application will now function with AJAX. Here too, optimization is needed because, due to the use of Nette Database, signal processing unnecessarily loads all articles from the database instead of just the relevant one. The advantage, however, is that no unnecessary rendering occurs, as only the specific component instance is rendered. {{priority: -1}} +{{maintitle: Nette Dynamic Snippets: Refresh List Items with AJAX}} +{{description: Use AJAX to refresh only what actually changes, such as a single item in a list. Two ways to do it in Nette: Latte dynamic snippets and components.}} diff --git a/best-practices/en/form-reuse.texy b/best-practices/en/form-reuse.texy index 466dd11301..9ad6e2bff9 100644 --- a/best-practices/en/form-reuse.texy +++ b/best-practices/en/form-reuse.texy @@ -346,3 +346,6 @@ class MyPresenter extends Nette\Application\UI\Presenter } } ``` + +{{maintitle: Reusing Forms in Nette: Factories and Form Components}} +{{description: Use the same form in multiple places without duplicating code: form factories and form components, plus solutions such as inheritance that you should avoid.}} diff --git a/best-practices/en/inject-method-attribute.texy b/best-practices/en/inject-method-attribute.texy index f37c76402b..6909d824d0 100644 --- a/best-practices/en/inject-method-attribute.texy +++ b/best-practices/en/inject-method-attribute.texy @@ -59,3 +59,6 @@ class MyPresenter extends Nette\Application\UI\Presenter The advantage of this dependency passing method was its very concise syntax. However, with the introduction of [constructor property promotion |https://blog.nette.org/en/php-8-0-complete-overview-of-news#toc-constructor-property-promotion], using the constructor often appears simpler. Conversely, this method suffers from the same drawbacks as property injection in general: we lack control over changes to the variable, and the variable becomes part of the class's public interface, which is generally undesirable. + +{{maintitle: Inject Methods and Attributes in Nette Presenters}} +{{description: Ways to pass dependencies into Nette presenters: the preferred constructor injection compared with inject methods and the Inject attribute.}} diff --git a/best-practices/en/lets-create-contact-form.texy b/best-practices/en/lets-create-contact-form.texy index 52a0df88c1..11ce861d6e 100644 --- a/best-practices/en/lets-create-contact-form.texy +++ b/best-practices/en/lets-create-contact-form.texy @@ -216,3 +216,6 @@ parameters: ``` And it's done! + +{{maintitle: Contact Form in PHP with Nette: Send Data by Email}} +{{description: Build a contact form in Nette step by step, from the form itself to sending the submitted data by email using a Latte template.}} diff --git a/best-practices/en/microsites.texy b/best-practices/en/microsites.texy index cd9c96b841..c80c4a2893 100644 --- a/best-practices/en/microsites.texy +++ b/best-practices/en/microsites.texy @@ -61,3 +61,6 @@ Why use Nette for Microsites? - Sometimes, [caching|caching:] might be useful, for example, when downloading and displaying feeds. In today's fast-paced world, where speed and efficiency are crucial, having tools that enable you to achieve results without unnecessary delays is vital. The Nette Framework offers precisely that - rapid development, security, and a wide array of tools like Tracy and Latte that streamline the process. Just install a few Nette packages, and building such a microsite becomes incredibly easy. And you can be confident there are no hidden security vulnerabilities. + +{{maintitle: Nette Microsites: A Small Website in One PHP File}} +{{description: Need a small website fast? Keep all its code in a single index.php with Nette routing and Latte, and still get Tracy, safe templates and other conveniences.}} diff --git a/best-practices/en/pagination.texy b/best-practices/en/pagination.texy index 04622fe991..82cab1ede2 100644 --- a/best-practices/en/pagination.texy +++ b/best-practices/en/pagination.texy @@ -271,3 +271,5 @@ Since we are no longer passing the Paginator object to the template, we need to This way, we've implemented the pagination mechanism without explicitly using the Paginator utility. {{priority: -1}} +{{maintitle: PHP Database Pagination with Nette: Paginator and Explorer}} +{{description: List database results page by page in Nette: a repository method, the Paginator class, links in the template and a simpler way with Nette Database Explorer.}} diff --git a/best-practices/en/passing-settings-to-presenters.texy b/best-practices/en/passing-settings-to-presenters.texy index 4a4bc51594..4432186ff7 100644 --- a/best-practices/en/passing-settings-to-presenters.texy +++ b/best-practices/en/passing-settings-to-presenters.texy @@ -47,3 +47,6 @@ class MyPresenter extends Nette\Application\UI\Presenter } } ``` + +{{maintitle: Passing Settings to Nette Presenters: Settings Object}} +{{description: Need to pass non-object values such as debug mode or directory paths to presenters? Autowiring can't do it, so wrap them in a dedicated Settings object.}} diff --git a/best-practices/en/post-links.texy b/best-practices/en/post-links.texy index 3bcb6628a7..5a6461963d 100644 --- a/best-practices/en/post-links.texy +++ b/best-practices/en/post-links.texy @@ -54,3 +54,6 @@ public function handleDelete(int $id): void ``` This approach not only enhances your application's security but also promotes adherence to proper web standards and practices. Using POST methods for state-changing actions results in a more robust and secure application. + +{{maintitle: POST Links in Nette: Never Change State with GET}} +{{description: Actions that change server state must not use GET. How to create POST links in Nette with Latte and secure them with the #[Requires] attribute.}} diff --git a/best-practices/en/presenter-traits.texy b/best-practices/en/presenter-traits.texy index 2db62c1dce..fb79690558 100644 --- a/best-practices/en/presenter-traits.texy +++ b/best-practices/en/presenter-traits.texy @@ -45,3 +45,6 @@ class ArticlePresenter extends Nette\Application\UI\Presenter use RequireLoggedUser; } ``` + +{{maintitle: Composing Nette Presenters from Traits}} +{{description: Share code such as a login check across presenters with single-purpose PHP traits instead of a common parent class, including how traits hook into startup.}} diff --git a/best-practices/en/pretty-urls.texy b/best-practices/en/pretty-urls.texy index 8dd3d9addc..7d37ef557e 100644 --- a/best-practices/en/pretty-urls.texy +++ b/best-practices/en/pretty-urls.texy @@ -202,3 +202,6 @@ Summary - Short ID-only URLs keep working, which is handy for QR codes and SMS. You'll find more about filters and canonization in the [routing |application:routing#general-filters] and [presenters |application:presenters#canonization] documentation. + +{{maintitle: Pretty URLs with Slugs in Nette: SEO-Friendly PHP Routing}} +{{description: Turn /article/123 into /article/123-how-to-bake-bread right in the router, without touching a single template, and redirect old URLs to the correct one.}} diff --git a/best-practices/en/restore-request.texy b/best-practices/en/restore-request.texy index f374e7be20..4af0670e96 100644 --- a/best-practices/en/restore-request.texy +++ b/best-practices/en/restore-request.texy @@ -60,3 +60,5 @@ We pass the key (`$this->backlink`) of the stored request to the `restoreRequest However, if the key is invalid (e.g., it has expired from the session), the method does nothing. Therefore, the subsequent call `$this->redirect('Admin:')` acts as a fallback, redirecting to a default page like `AdminPresenter`. {{priority: -1}} +{{maintitle: Return to an Earlier Page in Nette: Restore the Request}} +{{description: A user's login expires while filling out a form? Save the current request to the session before redirecting to sign-in and restore it with no data lost.}} diff --git a/bootstrap/cs/@home.texy b/bootstrap/cs/@home.texy index 1265c7c451..193044b514 100644 --- a/bootstrap/cs/@home.texy +++ b/bootstrap/cs/@home.texy @@ -97,3 +97,6 @@ Na parametr `remoteIp` se lze v konfiguraci odkázat zápisem `%remoteIp%`. Pokud aktualizujete balíček na novější verzi, podívejte se na stránku [upgrade|upgrading]. + +{{maintitle: Nette Bootstrap: načtení konfigurace a sestavení kontejneru}} +{{description: Načtěte konfigurační soubory pomocí třídy Configurator a vytvořte z nich DI kontejner. Včetně vývojářského a produkčního režimu a parametrů.}} diff --git a/bootstrap/cs/upgrading.texy b/bootstrap/cs/upgrading.texy index 240cf0e828..40c092fc58 100644 --- a/bootstrap/cs/upgrading.texy +++ b/bootstrap/cs/upgrading.texy @@ -16,3 +16,6 @@ Upgrade na verzi 2.3 - odstraněny zastaralé konstanty `Configurator::DEVELOPMENT` a `PRODUCTION` - `Configurator::setDebugMode()` přijímá pouze bool / string / array - v konfiguračním souboru můžete všechny sekce umístěné pod `nette` posunout o úroveň výš; pokud posunete sekci `container`, `mailer` nebo `debugger`, přejmenujte ji na `di`, `mail` a `tracy` + +{{maintitle: Upgrade Nette Bootstrap: změny v jednotlivých verzích}} +{{description: Co se změnilo v Nette Bootstrap 3.1 a 2.3 a jak upravit kód: přejmenovaná třída Configurator, statické parametry a další.}} diff --git a/bootstrap/en/@home.texy b/bootstrap/en/@home.texy index af370ff707..7358e055f4 100644 --- a/bootstrap/en/@home.texy +++ b/bootstrap/en/@home.texy @@ -97,3 +97,6 @@ The `remoteIp` parameter can be referenced in the configuration using the `%remo If you are upgrading to a newer version, see the [upgrading] page. + +{{maintitle: Nette Bootstrap: Load NEON Config and Build DI Container}} +{{description: Load configuration files with the Configurator class and create a DI container from them. Also covers development and production mode and parameters.}} diff --git a/bootstrap/en/upgrading.texy b/bootstrap/en/upgrading.texy index 03b81d17f5..9afc283762 100644 --- a/bootstrap/en/upgrading.texy +++ b/bootstrap/en/upgrading.texy @@ -16,3 +16,6 @@ Upgrading to Version 2.3 - the deprecated constants `Configurator::DEVELOPMENT` and `PRODUCTION` were removed - `Configurator::setDebugMode()` accepts only bool / string / array - in the config file you can move all sections placed under `nette` one level up; if you move up the `container`, `mailer` or `debugger` section, rename it to `di`, `mail` and `tracy` + +{{maintitle: Upgrading Nette Bootstrap: What Changed in Each Version}} +{{description: What changed in Nette Bootstrap 3.1 and 2.3 and how to update your code: the renamed Configurator class, static parameters and more.}} diff --git a/caching/cs/@home.texy b/caching/cs/@home.texy index 79c370bad2..b8af5ba974 100644 --- a/caching/cs/@home.texy +++ b/caching/cs/@home.texy @@ -500,3 +500,6 @@ Toto nastavení nemá vliv na kešování šablon v Latte nebo DI kontejneru, pr Pokud aktualizujete balíček na novější verzi, podívejte se na stránku [upgrade|upgrading]. + +{{maintitle: Cache v PHP s Nette: úložiště, expirace a invalidace}} +{{description: Zrychlete aplikaci tím, že náročně získaná data uložíte pro příští použití. Cache z Nette v PHP i Latte, změna úložiště a správná invalidace.}} diff --git a/caching/cs/upgrading.texy b/caching/cs/upgrading.texy index 198a5953be..01f8e08f6f 100644 --- a/caching/cs/upgrading.texy +++ b/caching/cs/upgrading.texy @@ -18,3 +18,6 @@ Upgrade na verzi 2.3 ==================== - prastará a zastaralá ArrayAccess syntaxe `$val = $cache[$key]` nebo `$cache[$key] = $val` vyvolá `E_USER_DEPRECATED`; použijte místo ní `$cache->load($key)` a `$cache->save($key, $val)` + +{{maintitle: Upgrade Nette Caching: změny v jednotlivých verzích}} +{{description: Co se změnilo v Nette Caching 3.1, 2.4 a 2.3 a jak upravit kód při přechodu na novější verzi.}} diff --git a/caching/en/@home.texy b/caching/en/@home.texy index 922d42f91f..2f6793b527 100644 --- a/caching/en/@home.texy +++ b/caching/en/@home.texy @@ -500,3 +500,6 @@ This setting does not affect the caching of Latte templates or the DI container, If you are upgrading to a newer version, see the [upgrading] page. + +{{maintitle: PHP Caching with Nette: Storages, Expiration, Invalidation}} +{{description: Speed up your application by storing expensive results for later. Use the Nette cache in PHP and Latte, change storages and invalidate data correctly.}} diff --git a/caching/en/upgrading.texy b/caching/en/upgrading.texy index 5547b32483..724705f192 100644 --- a/caching/en/upgrading.texy +++ b/caching/en/upgrading.texy @@ -18,3 +18,6 @@ Upgrading to Version 2.3 ======================== - the ancient and deprecated ArrayAccess syntax `$val = $cache[$key]` or `$cache[$key] = $val` triggers `E_USER_DEPRECATED`; use `$cache->load($key)` and `$cache->save($key, $val)` instead + +{{maintitle: Upgrading Nette Caching: What Changed in Each Version}} +{{description: What changed in Nette Caching 3.1, 2.4 and 2.3, and how to update your code when moving to a newer version.}} diff --git a/command-line/cs/@home.texy b/command-line/cs/@home.texy index d479dfd72b..a9cec8256c 100644 --- a/command-line/cs/@home.texy +++ b/command-line/cs/@home.texy @@ -244,6 +244,6 @@ Verze 2.0 je nové API bez vrstvy zpětné kompatibility: v 1.x držel jediný ` [Plugin Nette pro Claude Code a Codex |ai:agent-plugins] obsahuje návod, podle kterého váš kódovací agent kód z 1.x věrně přepíše na 2.0 a nahlásí každé místo, kde se 2.0 chová jinak. -{{maintitle: Nette Command-Line - konzolové skripty a zpracování argumentů v PHP}} -{{description: Konzolové skripty v PHP: volby, argumenty a příkazy, nápověda a srozumitelné chybové hlášky, barevný výstup a výpis průběhu. Bez závislostí.}} {{sitename: Nette Dokumentace}} +{{maintitle: Nette Command-Line: konzolové skripty a argumenty v PHP}} +{{description: Konzolové skripty v PHP: volby, argumenty a příkazy, nápověda a srozumitelné chybové hlášky, barevný výstup a výpis průběhu. Bez závislostí.}} diff --git a/command-line/cs/arguments.texy b/command-line/cs/arguments.texy index 8588c079bd..93112216a6 100644 --- a/command-line/cs/arguments.texy +++ b/command-line/cs/arguments.texy @@ -689,5 +689,6 @@ Assert::matchFile(__DIR__ . '/help.txt', $renderer->renderToString($program)); Soubor `help.txt` poprvé vytvoříte tak, že do něj uložíte, co `renderToString()` vrátí, a zkontrolujete, že je to správně. -{{description: Zpracování argumentů příkazové řádky v PHP: příznaky, volby a argumenty s kontrolou hodnot, příkazy a podpříkazy, handlery, generovaná nápověda, srozumitelné chybové hlášky a testování.}} {{sitename: Nette Dokumentace}} +{{maintitle: Argumenty příkazové řádky v PHP s Nette: volby a příkazy}} +{{description: Zpracování argumentů příkazové řádky v PHP: příznaky, volby a argumenty s kontrolou hodnot, příkazy a podpříkazy, generovaná nápověda a chybové hlášky.}} diff --git a/command-line/cs/console.texy b/command-line/cs/console.texy index e2ab0704b3..004f9d6325 100644 --- a/command-line/cs/console.texy +++ b/command-line/cs/console.texy @@ -191,5 +191,6 @@ Když vstup skončí, třeba protože uživatel stiskl Ctrl+D, vrátí `choose() Prompt se ptá jen tehdy, když vstup i konzole vedou do terminálu, takže nikdy nevezme odpověď z roury, u které nikdo nesedí. Jinak `choose()` vyhodí `LogicException` dřív, než cokoli vypíše nebo přečte. Proto se nejdřív zeptejte `isInteractive()` a rozhodněte, co skript udělá bez člověka, třeba skončí s radou použít volbu příkazové řádky, jako `--overwrite`. Předejte promptu konzoli, která kreslí stavový řádek: otázka ho pak smaže a další stav se po odpovědi nakreslí na čistý řádek. -{{description: Barevný výstup do terminálu v PHP, který se v rouře a v CI sám vypne, klikací odkazy, řádek s průběhem a dotazy na uživatele.}} {{sitename: Nette Dokumentace}} +{{maintitle: Barevný výstup do terminálu v PHP s Nette: odkazy a průběh}} +{{description: Barevný výstup do terminálu v PHP, který se v rouře a v CI sám vypne, klikací odkazy, řádek s průběhem a dotazy na uživatele.}} diff --git a/command-line/en/@home.texy b/command-line/en/@home.texy index 70f2820716..c4dcaee2c7 100644 --- a/command-line/en/@home.texy +++ b/command-line/en/@home.texy @@ -244,6 +244,6 @@ Version 2.0 is a new API with no compatibility layer: in 1.x a single `Parser` h The [Nette plugin for Claude Code and Codex |ai:agent-plugins] includes a guide by which your coding agent rewrites 1.x code to 2.0 faithfully and reports every place where 2.0 behaves differently. -{{maintitle: Nette Command-Line - command-line scripts and argument parsing in PHP}} -{{description: Command-line scripts in PHP: options, arguments and commands, help and clear error messages, colored output and progress lines. No dependencies.}} {{sitename: Nette Documentation}} +{{maintitle: Nette Command-Line: PHP CLI Scripts and Argument Parsing}} +{{description: Command-line scripts in PHP: options, arguments and commands, help and clear error messages, colored output and progress lines. No dependencies.}} diff --git a/command-line/en/arguments.texy b/command-line/en/arguments.texy index cfa8d58c0e..4b6f0dcc04 100644 --- a/command-line/en/arguments.texy +++ b/command-line/en/arguments.texy @@ -689,5 +689,6 @@ Assert::matchFile(__DIR__ . '/help.txt', $renderer->renderToString($program)); You create the file `help.txt` the first time by saving into it what `renderToString()` returns, and checking that it is right. -{{description: Parse command-line arguments in PHP: flags, options and arguments with checked values, commands and subcommands, handlers, generated help, clear error messages and testing.}} {{sitename: Nette Documentation}} +{{maintitle: PHP Command-Line Arguments with Nette: Options, Commands}} +{{description: Parse command-line arguments in PHP: flags, options and arguments with checked values, commands and subcommands, generated help and clear error messages.}} diff --git a/command-line/en/console.texy b/command-line/en/console.texy index de624f7e1d..926c59ffe3 100644 --- a/command-line/en/console.texy +++ b/command-line/en/console.texy @@ -191,5 +191,6 @@ When the input ends, for example because the user pressed Ctrl+D, `choose()` ret The prompt asks only when both the input and the console lead to a terminal, so it never takes an answer from a pipe nobody is sitting at. Otherwise `choose()` throws `LogicException` before it prints or reads anything. So first ask `isInteractive()` and decide what the script does without a person, for example stop with a hint to use a command-line option such as `--overwrite`. Give the prompt the console that draws the status line: the question then erases it, and the next status is drawn on a clean line after the answer. -{{description: Colored terminal output in PHP that switches off in a pipe and in CI, clickable links, a progress line and questions for the user.}} {{sitename: Nette Documentation}} +{{maintitle: Colored Terminal Output in PHP with Nette: Links, Progress}} +{{description: Colored terminal output in PHP that switches off in a pipe and in CI, clickable links, a progress line and questions for the user.}} diff --git a/component-model/cs/@home.texy b/component-model/cs/@home.texy index 98c903366c..fac3687867 100644 --- a/component-model/cs/@home.texy +++ b/component-model/cs/@home.texy @@ -123,3 +123,6 @@ Komponenty nelze serializovat; `serialize()` vyhodí `Nette\NotImplementedExcept Pokud aktualizujete balíček na novější verzi, podívejte se na stránku [upgrade|upgrading]. + +{{maintitle: Komponentový model Nette: třídy Component a Container}} +{{description: Formuláře, jejich prvky i vizuální komponenty v Nette dědí od tříd Component a Container. Jak funguje pojmenování, monitorování předků a klonování.}} diff --git a/component-model/cs/upgrading.texy b/component-model/cs/upgrading.texy index aef1820db1..d67026371e 100644 --- a/component-model/cs/upgrading.texy +++ b/component-model/cs/upgrading.texy @@ -18,3 +18,6 @@ Upgrade na verzi 3.0 ==================== Konstruktor `Nette\ComponentModel\Component` nebyl roky používán a byl odstraněn ve verzi 3.0. Je to BC break: pokud voláte rodičovský konstruktor v komponentě nebo presenteru, musíte volání odstranit. + +{{maintitle: Upgrade Nette Component Model: co se změnilo}} +{{description: Co se změnilo v Nette Component Model 4.0 a 3.0 a jak upravit kód při přechodu na novější verzi.}} diff --git a/component-model/en/@home.texy b/component-model/en/@home.texy index 8ae27cb14d..5ecbdd07f5 100644 --- a/component-model/en/@home.texy +++ b/component-model/en/@home.texy @@ -123,3 +123,6 @@ Components cannot be serialized; `serialize()` throws `Nette\NotImplementedExcep If you are upgrading to a newer version, see the [upgrading] page. + +{{maintitle: Nette Component Model: Component and Container Classes}} +{{description: Forms, their controls and visual components in Nette all inherit from the Component and Container classes. How naming, monitoring ancestors and cloning work.}} diff --git a/component-model/en/upgrading.texy b/component-model/en/upgrading.texy index 02c9795461..b9993873e1 100644 --- a/component-model/en/upgrading.texy +++ b/component-model/en/upgrading.texy @@ -18,3 +18,6 @@ Upgrading to Version 3.0 ======================== The constructor of `Nette\ComponentModel\Component` has not been used for years and was removed in version 3.0. It is a BC break: if you call the parent constructor in a component or presenter, you must remove the call. + +{{maintitle: Upgrading Nette Component Model: What Changed}} +{{description: What changed in Nette Component Model 4.0 and 3.0, and how to update your code when moving to a newer version.}} diff --git a/contributing/cs/@home.texy b/contributing/cs/@home.texy index 9dd139a2f7..7c1b46225e 100644 --- a/contributing/cs/@home.texy +++ b/contributing/cs/@home.texy @@ -15,3 +15,6 @@ Zjistěte, jak se můžete zapojit do našeho open source projektu. Osvojte si p - [Jak přispět do dokumentace? |documentation] - [Dokumentační syntax |syntax] - "Náhledový editor":https://editor.nette.org + +{{maintitle: Jak přispět do Nette: staňte se přispěvatelem}} +{{description: Zjistěte, jak se zapojit do open source projektu Nette: přispívejte do zdrojového kódu a dokumentace a staňte se součástí komunity vývojářů.}} diff --git a/contributing/cs/code.texy b/contributing/cs/code.texy index 5791c39742..6a74181751 100644 --- a/contributing/cs/code.texy +++ b/contributing/cs/code.texy @@ -104,3 +104,5 @@ Zobrazí se také záhlaví, kde uveďte, zda se jedná o novou funkci nebo opra {{priority: -1}} +{{maintitle: Jak přispět do kódu Nette: pull request krok za krokem}} +{{description: Průvodce přispíváním do kódu Nette pro začátečníky: repozitáře, nová větev, coding standards a jak popsat komity a pull requesty.}} diff --git a/contributing/cs/coding-standard.texy b/contributing/cs/coding-standard.texy index 9c142bae22..ad96d06c60 100644 --- a/contributing/cs/coding-standard.texy +++ b/contributing/cs/coding-standard.texy @@ -146,3 +146,5 @@ Pro nevidomé programátory, kteří používají braillské displeje, představ {{priority: -1}} +{{maintitle: Kódovací standard Nette: pravidla pro PHP kód}} +{{description: Pravidla pro psaní kódu v Nette: pojmenovací konvence, zalamování a závorky, phpDoc, globální funkce a konstanty a tabulátory místo mezer.}} diff --git a/contributing/cs/documentation.texy b/contributing/cs/documentation.texy index b644eee0a9..5e3754072b 100644 --- a/contributing/cs/documentation.texy +++ b/contributing/cs/documentation.texy @@ -66,3 +66,6 @@ Struktura dokumentace Celá dokumentace je umístěna na GitHubu v repozitáři [nette/docs |https://github.com/nette/docs]. Aktuální verze je v masteru, starší verze jsou umístěny ve větvích jako `doc-3.x`, `doc-2.x`. Obsah každé větve se dělí do hlavních složek představujících jednotlivé oblasti dokumentace. Například `application/` odpovídá https://doc.nette.org/cs/application, `latte/` odpovídá https://latte.nette.org atd. Každá tato složka obsahuje podsložky představující jazykové mutace (`cs`, `en`, ...) a případně podsložku `files` s obrázky, které je možné do stránek v dokumentaci vkládat. + +{{maintitle: Jak přispět do dokumentace Nette}} +{{description: Přispívání do dokumentace pomáhá druhým porozumět frameworku. Jak psát pro nováčky, které jazykové verze upravovat a jak si text předem prohlédnout.}} diff --git a/contributing/cs/syntax.texy b/contributing/cs/syntax.texy index f6106cc06c..6308019d94 100644 --- a/contributing/cs/syntax.texy +++ b/contributing/cs/syntax.texy @@ -141,3 +141,5 @@ Meta značky - určení levého menu `{{leftbar: utils:@left-menu}}` či jeho vypnutí `{{leftbar: no}}` {{priority: -1}} +{{maintitle: Syntax dokumentace Nette: značkování stránek v Texy}} +{{description: Značkování dokumentace Nette: odkazy, zdrojový kód, nadpisy, rámečky a styly, obsah stránky a meta značky.}} diff --git a/contributing/en/@home.texy b/contributing/en/@home.texy index 8816352b0f..73cb24e686 100644 --- a/contributing/en/@home.texy +++ b/contributing/en/@home.texy @@ -15,3 +15,6 @@ Find out how you can get involved in our open source project. Learn the procedur - [Contributing to Documentation |documentation] - [Documentation Syntax |syntax] - "Preview editor":https://editor.nette.org + +{{maintitle: Contributing to Nette: Become a Contributor}} +{{description: Find out how to get involved in the Nette open source project: contribute to the source code and documentation and join the community of developers.}} diff --git a/contributing/en/code.texy b/contributing/en/code.texy index 662b3aa921..76c94255db 100644 --- a/contributing/en/code.texy +++ b/contributing/en/code.texy @@ -104,3 +104,5 @@ Also, specify in the header whether it is a new feature or a bug fix and whether {{priority: -1}} +{{maintitle: Contributing Code to Nette: Pull Requests Step by Step}} +{{description: A beginner's guide to contributing code to Nette: repositories, a new branch, coding standards, and how to describe commits and pull requests.}} diff --git a/contributing/en/coding-standard.texy b/contributing/en/coding-standard.texy index 0c1588d651..373f4cc4e6 100644 --- a/contributing/en/coding-standard.texy +++ b/contributing/en/coding-standard.texy @@ -146,3 +146,5 @@ For blind programmers who use braille displays, each space represents a braille {{priority: -1}} +{{maintitle: Nette Coding Standard Rules for PHP Code}} +{{description: The rules for writing code in Nette: naming conventions, wrapping and braces, phpDoc, global functions and constants, and tabs instead of spaces.}} diff --git a/contributing/en/documentation.texy b/contributing/en/documentation.texy index e89c20c648..18ed7a89e7 100644 --- a/contributing/en/documentation.texy +++ b/contributing/en/documentation.texy @@ -66,3 +66,6 @@ Documentation Structure The entire documentation is located on GitHub in the [nette/docs |https://github.com/nette/docs] repository. The current version is in the `master` branch, while older versions are located in branches like `doc-3.x`, `doc-2.x`. The content of each branch is divided into main folders representing individual documentation areas. For example, `application/` corresponds to `https://doc.nette.org/en/application`, `latte/` corresponds to `https://latte.nette.org`, etc. Each of these folders contains subfolders representing language versions (`cs`, `en`, ...) and optionally a `files` subfolder with images that can be included in the documentation pages. + +{{maintitle: Contributing to Nette Documentation: How to Help}} +{{description: Contributing to the documentation helps others understand the framework. How to write for newcomers, which language versions to edit and how to preview text.}} diff --git a/contributing/en/syntax.texy b/contributing/en/syntax.texy index e62c9fc4bc..d8b1c3753b 100644 --- a/contributing/en/syntax.texy +++ b/contributing/en/syntax.texy @@ -141,3 +141,5 @@ Meta Tags - Set the left menu `{{leftbar: utils:@left-menu}}` or disable it `{{leftbar: no}}`. {{priority: -1}} +{{maintitle: Nette Documentation Syntax: Texy Markup for Pages}} +{{description: The markup used in the Nette documentation: links, source code, headings, boxes and styles, tables of contents and meta tags.}} diff --git a/database/cs/@home.texy b/database/cs/@home.texy index c989fd1820..1ca7af906a 100644 --- a/database/cs/@home.texy +++ b/database/cs/@home.texy @@ -12,7 +12,5 @@ Nette podporuje následující databáze: | MS SQL (PDO_DBLIB) | mssql | ANO | - | ODBC | odbc | ANO | - - - -{{maintitle: Nette Database - awesome database layer for PHP}} -{{description: Nette Database zásadním způsobem zjednodušuje získávání dat z databáze bez nutnosti psát SQL dotazy. Pokládá efektivní dotazy a nepřenáší zbytečná data.}} +{{maintitle: Nette Database: jednoduchá a chytrá databázová vrstva pro PHP}} +{{description: Nette Database zásadním způsobem zjednodušuje získávání dat bez nutnosti psát SQL dotazy. Pokládá efektivní dotazy a nepřenáší zbytečná data.}} diff --git a/database/cs/configuration.texy b/database/cs/configuration.texy index 726fb15291..34d8bf384c 100644 --- a/database/cs/configuration.texy +++ b/database/cs/configuration.texy @@ -108,3 +108,6 @@ Neautowirované služby předáváme explicitně odkazem na jejich název: services: - UserFacade(@database.another.connection) ``` + +{{maintitle: Konfigurace Nette Database: připojení v NEON}} +{{description: Nastavte jedno nebo více připojení k databázi v konfiguraci NEON: DSN, přihlašovací údaje, volby pro ladění a služby DI, které Nette Database registruje.}} diff --git a/database/cs/exceptions.texy b/database/cs/exceptions.texy index f06d44a561..6f47eb1026 100644 --- a/database/cs/exceptions.texy +++ b/database/cs/exceptions.texy @@ -35,3 +35,6 @@ try { echo 'Došlo k chybě při registraci: ' . $e->getMessage(); } ``` + +{{maintitle: Výjimky v Nette Database: hierarchie a zpracování chyb}} +{{description: Hierarchie výjimek v Nette Database: jak rozpoznat selhání připojení, porušení omezení nebo deadlock a zjistit kód chyby ovladače, SQLSTATE a původní dotaz.}} diff --git a/database/cs/explorer.texy b/database/cs/explorer.texy index 5138d5e97a..595bd2ab36 100644 --- a/database/cs/explorer.texy +++ b/database/cs/explorer.texy @@ -910,3 +910,6 @@ $tags = $explorer->table('tag') ``` Všimněte si, že zatímco metoda `where()` přidává podmínky do klauzule `WHERE`, metoda `joinWhere()` rozšiřuje podmínky v klauzuli `ON` při spojování tabulek. + +{{maintitle: Nette Database Explorer: práce s tabulkami bez psaní SQL}} +{{description: Pracujte s databází bez psaní SQL: filtrujte, řaďte a agregujte data, vkládejte a upravujte řádky a vazby mezi tabulkami nechte na Exploreru.}} diff --git a/database/cs/guide.texy b/database/cs/guide.texy index 68bde63e38..94ffc8bd57 100644 --- a/database/cs/guide.texy +++ b/database/cs/guide.texy @@ -216,3 +216,6 @@ Tracy Debug Bar Pokud používáte [Tracy |tracy:], aktivuje se automaticky panel Database v Debug baru, který zobrazuje všechny provedené dotazy, jejich parametry, dobu vykonání a místo v kódu, kde byly zavolány. [* db-panel.webp *] + +{{maintitle: Začínáme s Nette Database: Explorer, nebo SQL}} +{{description: Nainstalujte Nette Database, připojte se k MySQL, PostgreSQL, SQLite nebo MS SQL a vyberte si přístup: Explorer pro rychlý vývoj, nebo SQL pro plnou kontrolu.}} diff --git a/database/cs/reflection.texy b/database/cs/reflection.texy index 1242dcb163..963224446e 100644 --- a/database/cs/reflection.texy +++ b/database/cs/reflection.texy @@ -125,3 +125,6 @@ foreach ($table->foreignKeys as $fk) { echo " $localCols -> {$fk->foreignTable->name}($foreignCols)\n"; } ``` + +{{maintitle: Reflexe databáze v Nette: tabulky, sloupce a indexy}} +{{description: Zjistěte strukturu databáze přímo z PHP: seznam tabulek a informace o sloupcích, indexech a cizích klíčích pomocí reflexe v Nette Database.}} diff --git a/database/cs/security.texy b/database/cs/security.texy index f651e315b5..cd27787347 100644 --- a/database/cs/security.texy +++ b/database/cs/security.texy @@ -183,3 +183,6 @@ Důležité: symbol `?name` používejte pouze pro důvěryhodné hodnoty defino // ❌ NEBEZPEČNÉ - nikdy nepoužívejte vstup od uživatele $database->query('SELECT ?name FROM users', $_GET['column']); ``` + +{{maintitle: Ochrana před SQL injection v PHP a Nette Database}} +{{description: Co je SQL injection a jak mu v Nette Database předejít: parametrizované dotazy, validace vstupů, bezpečná práce se sloupci a dynamické identifikátory.}} diff --git a/database/cs/sql-way.texy b/database/cs/sql-way.texy index 83bcba1534..5105765444 100644 --- a/database/cs/sql-way.texy +++ b/database/cs/sql-way.texy @@ -511,3 +511,6 @@ $database->onQuery[] = function ($database, $result) use ($logger) { } }; ``` + +{{maintitle: SQL přístup v Nette Database: plná kontrola nad dotazy}} +{{description: Pište SQL dotazy sami a Nette Database se postará o jejich bezpečnost: parametry proti SQL injection, techniky dotazování, získání dat a informace o dotazech.}} diff --git a/database/cs/transactions.texy b/database/cs/transactions.texy index 442d34e196..ddd95386d5 100644 --- a/database/cs/transactions.texy +++ b/database/cs/transactions.texy @@ -43,3 +43,6 @@ $count = $database->transaction(function ($database) { return $result->getRowCount(); // vrátí počet aktualizovaných řádků }); ``` + +{{maintitle: Databázové transakce v PHP a Nette Database}} +{{description: Více operací jako jeden celek: provedou se všechny, nebo žádná. Stačí beginTransaction(), commit() a rollBack(), nebo jednodušší transaction() s callbackem.}} diff --git a/database/cs/type-conversion.texy b/database/cs/type-conversion.texy index aed7eadadc..c1e9b1ee9b 100644 --- a/database/cs/type-conversion.texy +++ b/database/cs/type-conversion.texy @@ -53,3 +53,6 @@ $database->setRowNormalizer(function(array $row, ResultSet $resultSet): array { return $row; }); ``` + +{{maintitle: Konverze typů v Nette Database: z databáze do PHP}} +{{description: Nette Database automaticky převádí hodnoty z databáze na typy PHP: celá a desetinná čísla, boolean a objekty DateTime a DateInterval.}} diff --git a/database/cs/upgrading.texy b/database/cs/upgrading.texy index 692d783db9..b38003085d 100644 --- a/database/cs/upgrading.texy +++ b/database/cs/upgrading.texy @@ -34,3 +34,6 @@ Upgrade na verzi 2.3 - `MySqlDriver` používá ve výchozím nastavení pro MySQL >= 5.5.3 kódování `utf8mb4` místo `utf8` - `IReflection` bylo rozděleno na dvojici rozhraní `IStructure` a `IConventions` + +{{maintitle: Upgrade Nette Database: změny v jednotlivých verzích}} +{{description: Co se změnilo v Nette Database 3.2, 3.1, 3.0 a 2.3 a jak upravit kód při přechodu na novější verzi.}} diff --git a/database/en/@home.texy b/database/en/@home.texy index 330104209f..ffb5a172d1 100644 --- a/database/en/@home.texy +++ b/database/en/@home.texy @@ -12,7 +12,5 @@ These database servers are supported: | MS SQL (PDO_DBLIB) | mssql | YES | - | ODBC | odbc | YES | - - - -{{maintitle: Nette Database - awesome database layer for PHP}} -{{description: Nette Database significantly simplifies retrieving data from the database without writing SQL queries. It executes efficient queries and does not transfer unnecessary data.}} +{{maintitle: Nette Database: Simple and Smart Database Layer for PHP}} +{{description: Nette Database simplifies retrieving data without writing SQL queries. It executes efficient queries and does not transfer unnecessary data.}} diff --git a/database/en/configuration.texy b/database/en/configuration.texy index 003eba4b26..f31f551525 100644 --- a/database/en/configuration.texy +++ b/database/en/configuration.texy @@ -108,3 +108,6 @@ We pass non-autowired services explicitly by referencing their name: services: - UserFacade(@database.another.connection) ``` + +{{maintitle: Nette Database Configuration: Connections in NEON}} +{{description: Set up one or more database connections in NEON configuration: DSN, credentials, debugging options and the DI services Nette Database registers.}} diff --git a/database/en/exceptions.texy b/database/en/exceptions.texy index 650eaabb55..fbd770c917 100644 --- a/database/en/exceptions.texy +++ b/database/en/exceptions.texy @@ -35,3 +35,6 @@ try { echo 'An error occurred during registration: ' . $e->getMessage(); } ``` + +{{maintitle: Nette Database Exceptions: Error Hierarchy and Handling}} +{{description: The exception hierarchy of Nette Database: how to tell a connection failure, constraint violation or deadlock, and read the driver error code and SQLSTATE.}} diff --git a/database/en/explorer.texy b/database/en/explorer.texy index 60002a1dc8..c0c931257b 100644 --- a/database/en/explorer.texy +++ b/database/en/explorer.texy @@ -910,3 +910,6 @@ $tags = $explorer->table('tag') ``` Note that while the `where()` method adds conditions to the `WHERE` clause, the `joinWhere()` method extends the conditions in the `ON` clause when joining tables. + +{{maintitle: Nette Database Explorer: Query Tables Without Writing SQL}} +{{description: Work with your database without writing SQL: filter, sort and aggregate data, insert and update rows, and let Explorer handle relationships between tables.}} diff --git a/database/en/guide.texy b/database/en/guide.texy index 51562d638d..f58541cd0a 100644 --- a/database/en/guide.texy +++ b/database/en/guide.texy @@ -216,3 +216,6 @@ Tracy Debug Bar If you use [Tracy |tracy:], the Database panel in the Debug Bar is automatically activated. It displays all executed queries, their parameters, execution time, and the location in the code where they were called. [* db-panel.webp *] + +{{maintitle: Getting Started with Nette Database: Explorer or SQL}} +{{description: Install Nette Database, connect to MySQL, PostgreSQL, SQLite or MS SQL and choose your approach: the Explorer for rapid development or SQL for full control.}} diff --git a/database/en/reflection.texy b/database/en/reflection.texy index 31662529e3..86a687812f 100644 --- a/database/en/reflection.texy +++ b/database/en/reflection.texy @@ -125,3 +125,6 @@ foreach ($table->foreignKeys as $fk) { echo " $localCols -> {$fk->foreignTable->name}($foreignCols)\n"; } ``` + +{{maintitle: Nette Database Reflection: Tables, Columns and Indexes}} +{{description: Inspect your database structure from PHP: list tables and read information about their columns, indexes and foreign keys with Nette Database reflection.}} diff --git a/database/en/security.texy b/database/en/security.texy index ac9c42bcda..2c1b6b48d7 100644 --- a/database/en/security.texy +++ b/database/en/security.texy @@ -183,3 +183,6 @@ Important: Use the `?name` symbol only for trusted values defined in the applica // ❌ DANGEROUS - never use user input $database->query('SELECT ?name FROM users', $_GET['column']); ``` + +{{maintitle: PHP SQL Injection Protection in Nette Database}} +{{description: What SQL injection is and how to prevent it in Nette Database: parameterized queries, input validation, safe work with columns and dynamic identifiers.}} diff --git a/database/en/sql-way.texy b/database/en/sql-way.texy index a87292d684..62a72cfdf3 100644 --- a/database/en/sql-way.texy +++ b/database/en/sql-way.texy @@ -511,3 +511,6 @@ $database->onQuery[] = function ($database, $result) use ($logger) { } }; ``` + +{{maintitle: Nette Database SQL Way: Safe Queries with Full Control}} +{{description: Write SQL queries yourself while Nette Database keeps them safe: parameters against SQL injection, query techniques, fetching data and query information.}} diff --git a/database/en/transactions.texy b/database/en/transactions.texy index bb404cead2..6103213ba9 100644 --- a/database/en/transactions.texy +++ b/database/en/transactions.texy @@ -43,3 +43,6 @@ $count = $database->transaction(function ($database) { return $result->getRowCount(); // returns the number of updated rows }); ``` + +{{maintitle: PHP Database Transactions in Nette Database}} +{{description: Run several operations as one: either all succeed or none do. Use beginTransaction(), commit() and rollBack(), or the simpler transaction() with a callback.}} diff --git a/database/en/type-conversion.texy b/database/en/type-conversion.texy index 3a4162363d..6afa03eb77 100644 --- a/database/en/type-conversion.texy +++ b/database/en/type-conversion.texy @@ -53,3 +53,6 @@ $database->setRowNormalizer(function(array $row, ResultSet $resultSet): array { return $row; }); ``` + +{{maintitle: Nette Database Type Conversion: From SQL to PHP Types}} +{{description: Nette Database automatically converts database values to PHP types: integers, floats, booleans, and DateTime and DateInterval objects.}} diff --git a/database/en/upgrading.texy b/database/en/upgrading.texy index 700bbc41ba..2c12506410 100644 --- a/database/en/upgrading.texy +++ b/database/en/upgrading.texy @@ -34,3 +34,6 @@ Upgrading to Version 2.3 - the `MySqlDriver` uses `utf8mb4` encoding by default for MySQL >= 5.5.3 instead of `utf8` - `IReflection` was split into the twin interfaces `IStructure` and `IConventions` + +{{maintitle: Upgrading Nette Database: What Changed in Each Version}} +{{description: What changed in Nette Database 3.2, 3.1, 3.0 and 2.3, and how to update your code when moving to a newer version.}} diff --git a/dependency-injection/cs/@home.texy b/dependency-injection/cs/@home.texy index cda285320d..be7a748b7b 100644 --- a/dependency-injection/cs/@home.texy +++ b/dependency-injection/cs/@home.texy @@ -20,3 +20,6 @@ Balíček `nette/di` poskytuje nesmírně pokročilý kompilovaný DI kontejner - [Generované továrny |factory] - [Tvorba rozšíření pro Nette DI |extensions] - [Kompilace kontejneru do hloubky |compilation-internals] + +{{maintitle: Nette DI: Dependency Injection kontejner pro PHP}} +{{description: Zjistěte, co je dependency injection a proč změní váš pohled na kód, a pak využijte Nette DI, vyspělý kompilovaný DI kontejner pro PHP.}} diff --git a/dependency-injection/cs/autowiring.texy b/dependency-injection/cs/autowiring.texy index 04e4691507..baea4a2a6f 100644 --- a/dependency-injection/cs/autowiring.texy +++ b/dependency-injection/cs/autowiring.texy @@ -277,3 +277,6 @@ services: parentDep: ParentDependent # autowiring předá do konstruktoru child childDep: ChildDependent # autowiring předá do konstruktoru child ``` + +{{maintitle: Autowiring v Nette DI: automatické předávání služeb}} +{{description: Nette DI za vás předá služby do konstruktorů a dalších metod. Jak autowiring vypnout nebo zúžit, upřednostnit některou službu a předat kolekci služeb.}} diff --git a/dependency-injection/cs/compilation-internals.texy b/dependency-injection/cs/compilation-internals.texy index 0c6958e52f..4c353646c1 100644 --- a/dependency-injection/cs/compilation-internals.texy +++ b/dependency-injection/cs/compilation-internals.texy @@ -220,3 +220,6 @@ Nejčastější omyly - "Reference `@Type` je hned jméno služby." Není - je to typová reference, na konkrétní jméno se vyřeší autowiringem až v kroku complete. - "Moje rozšíření čte pomocný soubor, ale změny se neprojeví." Registrujte ho přes `$builder->addDependency($file)`, jinak o něm cache neví a nepřekompiluje se. - "Během `resolve()` můžu volat `getByType()`." Ne - vyhodí výjimku. Hledání podle typu patří do `beforeCompile()` nebo později, nikdy ne doprostřed resolvingu. + +{{maintitle: Kompilace DI kontejneru v Nette: jednotlivé fáze}} +{{description: Co se děje, když Nette sestavuje DI kontejner: jeho fáze, kdy se rozbalují parametry, kdy se řetězec @service mění na referenci a kdy lze bezpečně hledat služby.}} diff --git a/dependency-injection/cs/configuration.texy b/dependency-injection/cs/configuration.texy index f85094b931..7a60f0c926 100644 --- a/dependency-injection/cs/configuration.texy +++ b/dependency-injection/cs/configuration.texy @@ -332,4 +332,5 @@ items: -{{maintitle: Konfigurace Dependency Injection}} +{{maintitle: Konfigurace DI kontejneru v Nette: služby a parametry}} +{{description: Konfigurace DI kontejneru Nette v NEON: parametry, služby, decorator, rozšíření, vkládání souborů, vyhledávání služeb a slučování konfigurací.}} diff --git a/dependency-injection/cs/container.texy b/dependency-injection/cs/container.texy index b364003571..e226195134 100644 --- a/dependency-injection/cs/container.texy +++ b/dependency-injection/cs/container.texy @@ -138,5 +138,5 @@ Jak vidíte, napsat DIC není nic složitého. Za připomenutí stojí, že samo Ruční vytváření a údržba třídy kontejneru se může poměrně rychle stát noční můrou. V další kapitole si proto povíme o [Nette DI Containeru|nette-container], který se umí generovat a aktualizovat téměř sám. - {{maintitle: Co je dependency injection kontejner?}} +{{description: DI kontejner vytváří a konfiguruje vaše služby. Podívejte se, co umí, jak snadno si ho napíšete ručně a proč budete brzy chtít, aby se generoval sám.}} diff --git a/dependency-injection/cs/extensions.texy b/dependency-injection/cs/extensions.texy index ba3dee165b..18a4c15e3d 100644 --- a/dependency-injection/cs/extensions.texy +++ b/dependency-injection/cs/extensions.texy @@ -441,3 +441,6 @@ public function loadConfiguration(): void ``` Obě metody metadata pouze přidávají; nikdy nepřepíšou nastavení `di › export` z aplikace. Když tedy aplikace omezí export na výčet, tagy a typy, které vaše rozšíření potřebuje, zůstanou zachovány; jen úplné vypnutí exportu tagů (`tags: false`) je zahodí spolu se vším ostatním. + +{{maintitle: Tvorba rozšíření pro Nette DI: registrace služeb v kódu}} +{{description: Napište rozšíření pro Nette DI, které v kódu registruje služby, validuje vlastní sekci konfigurace, upravuje cizí služby a mění vygenerovaný kontejner.}} diff --git a/dependency-injection/cs/factory.texy b/dependency-injection/cs/factory.texy index 1fae06c265..a15d45b7f3 100644 --- a/dependency-injection/cs/factory.texy +++ b/dependency-injection/cs/factory.texy @@ -231,3 +231,6 @@ services: - MultiFactory(tagged: multi) ``` + +{{maintitle: Generované továrny v Nette DI: kód podle rozhraní}} +{{description: Stačí napsat rozhraní a Nette DI vygeneruje kód továrny za vás. Parametrizované továrny, accessory, vícenásobné továrny a pokročilé definice.}} diff --git a/dependency-injection/cs/faq.texy b/dependency-injection/cs/faq.texy index f2a9006bb8..7f3c54a195 100644 --- a/dependency-injection/cs/faq.texy +++ b/dependency-injection/cs/faq.texy @@ -121,3 +121,6 @@ Krátký slovníček slov, která se kolem Nette DI často objevují, většina - **Tag** - štítek připojený k definici (volitelně s hodnotou); rozšíření pak všechny služby s ním najde přes `findByTag()`. - **Setup** - další volání provedená na službě hned po jejím vytvoření - volání metod nebo nastavení vlastností, přidávaná přes `addSetup()`. - **Alias** - alternativní název existující služby. + +{{maintitle: Dependency Injection: časté otázky, IoC a service locator}} +{{description: Je DI jiný název pro IoC? Co je service locator? Kdy je lepší DI nepoužívat? Srozumitelné odpovědi na nejčastější otázky o dependency injection.}} diff --git a/dependency-injection/cs/global-state.texy b/dependency-injection/cs/global-state.texy index 6860252421..38e3b992fe 100644 --- a/dependency-injection/cs/global-state.texy +++ b/dependency-injection/cs/global-state.texy @@ -294,3 +294,6 @@ Během tohoto procesu možná zjistíte, že je třeba třídu rozdělit, proto Chcete si to všechno raději zažít, než o tom jen číst? Kurz [Dependency Injection by Example |https://github.com/nette-examples/di-by-example] má kapitolu, ve které nevinně vypadající test potichu odčerpá peníze z účtu, a ten test si můžete spustit. *Rád bych poděkoval Miškovi Heverymu, jehož články, jako je [Flaw: Brittle Global State & Singletons |https://web.archive.org/web/20230321084133/http://misko.hevery.com/code-reviewers-guide/flaw-brittle-global-state-singletons/], jsou základem této kapitoly.* + +{{maintitle: Singleton a globální stav v PHP: proč se jim vyhnout}} +{{description: Singletony, statické metody a globální konstanty jsou příznakem špatného návrhu. Proč je kód s globálním stavem křehký a špatně se testuje a kdy to nevadí.}} diff --git a/dependency-injection/cs/introduction.texy b/dependency-injection/cs/introduction.texy index b31b4c5f53..41a9b6df63 100644 --- a/dependency-injection/cs/introduction.texy +++ b/dependency-injection/cs/introduction.texy @@ -523,3 +523,6 @@ Na začátku této kapitoly jsme slibovali, že si ukážeme postup, jak navrhov Nemusí se to tak na první pohled zdát, ale tato tři pravidla mají dalekosáhlé důsledky. Vedou k radikálně jinému pohledu na návrh kódu. Stojí to za to? Programátoři, kteří zahodili staré zvyky a začali důsledně používat dependency injection, považují tento krok za zásadní moment v profesním životě. Otevřel se jim svět přehledných a udržitelných aplikací. Co když ale kód důsledně dependency injection nepoužívá? Co když je postaven na statických metodách nebo singletonech? Přináší to nějaké problémy? [Přináší a velmi zásadní |global-state]. + +{{maintitle: Co je Dependency Injection? Návod pro PHP s příklady}} +{{description: Dependency injection vysvětlené od začátku na příkladech v PHP: tři jednoduchá pravidla, která vás dovedou k čistému, srozumitelnému a udržitelnému kódu.}} diff --git a/dependency-injection/cs/nette-container.texy b/dependency-injection/cs/nette-container.texy index 1842d5a543..dad1d3eaf5 100644 --- a/dependency-injection/cs/nette-container.texy +++ b/dependency-injection/cs/nette-container.texy @@ -140,3 +140,6 @@ Použití s frameworkem Nette --------------------------- Jak jsme si ukázali, použití Nette DI není omezené na aplikace psané v Nette Frameworku, můžete jej pomocí pouhých 3 řádků kódu nasadit kdekoliv. Pokud však vyvíjíte aplikace v Nette Framework, konfiguraci a vytvoření kontejneru má na starosti [Bootstrap |application:bootstrapping#Konfigurace DI kontejneru]. + +{{maintitle: Nette DI Container: rychlý kompilovaný kontejner pro PHP}} +{{description: Nette DI generuje a automaticky aktualizuje kompilované kontejnery, které jsou extrémně rychlé a snadno se konfigurují v NEON. Podívejte se, jak ho použít.}} diff --git a/dependency-injection/cs/passing-dependencies.texy b/dependency-injection/cs/passing-dependencies.texy index f182be3f93..990d38a148 100644 --- a/dependency-injection/cs/passing-dependencies.texy +++ b/dependency-injection/cs/passing-dependencies.texy @@ -213,3 +213,6 @@ Jaký způsob zvolit? - konstruktor je vhodný pro povinné závislosti, které třída nezbytně potřebuje ke své funkci - setter je naopak vhodný pro nepovinné závislosti, nebo závislosti, u kterých chceme mít možnost je dále měnit - veřejné proměnné vhodné nejsou + +{{maintitle: Předávání závislostí v PHP: konstruktor, setter a proměnná}} +{{description: Jak předávat závislosti do třídy: konstruktorem, setterem, nastavením proměnné nebo metodou inject. Čím se způsoby liší a který zvolit.}} diff --git a/dependency-injection/cs/services.texy b/dependency-injection/cs/services.texy index 5b6df08cf2..e7695babdb 100644 --- a/dependency-injection/cs/services.texy +++ b/dependency-injection/cs/services.texy @@ -478,3 +478,6 @@ Pokud chcete odstranit službu přidanou rozšířením, můžete to udělat tak services: cache.journal: false ``` + +{{maintitle: Definice služeb v Nette DI: konfigurace v NEON}} +{{description: Naučte DI kontejner, jak vytvářet služby a propojovat je se závislostmi: argumenty, setup, výrazové prostředky, lazy služby, tagy a režim inject.}} diff --git a/dependency-injection/cs/upgrading.texy b/dependency-injection/cs/upgrading.texy index b4f9c5f614..20996307d8 100644 --- a/dependency-injection/cs/upgrading.texy +++ b/dependency-injection/cs/upgrading.texy @@ -47,3 +47,6 @@ Upgrade na verzi 2.3 - byla odstraněna podpora pro umisťování služeb do sekce extension v konfiguračním souboru - byla odstraněna podpora dynamicky přidávaných rozšíření - při dynamické výměně služby (přes `removeService()`, `addService()`) musí být nová služba instancí stejného rozhraní/třídy jako původní + +{{maintitle: Upgrade Nette DI: změny v jednotlivých verzích}} +{{description: Co se změnilo v Nette DI 3.1, 3.0, 2.4 a 2.3 a jak upravit kód a konfiguraci v NEON: autowiring parametrů s null, přejmenované klíče a další.}} diff --git a/dependency-injection/en/@home.texy b/dependency-injection/en/@home.texy index 06fd53c5e5..a743741116 100644 --- a/dependency-injection/en/@home.texy +++ b/dependency-injection/en/@home.texy @@ -20,3 +20,6 @@ The `nette/di` package provides an extremely advanced compiled DI container for - [Generated Factories |factory] - [Creating Extensions for Nette DI |extensions] - [Container Compilation Explained |compilation-internals] + +{{maintitle: Nette DI: Dependency Injection Container for PHP}} +{{description: Learn what dependency injection is and why it changes how you write code, then use Nette DI, an advanced compiled DI container for PHP.}} diff --git a/dependency-injection/en/autowiring.texy b/dependency-injection/en/autowiring.texy index 3e9efc9b76..b6a77b517f 100644 --- a/dependency-injection/en/autowiring.texy +++ b/dependency-injection/en/autowiring.texy @@ -277,3 +277,6 @@ services: parentDep: ParentDependent # autowiring passes the child service to the constructor childDep: ChildDependent # autowiring passes the child service to the constructor ``` + +{{maintitle: PHP Autowiring in Nette DI: Pass Services Automatically}} +{{description: Let Nette DI pass services to constructors and other methods for you. Disable or narrow autowiring, set a preferred service and collect services into an array.}} diff --git a/dependency-injection/en/compilation-internals.texy b/dependency-injection/en/compilation-internals.texy index 2ea48d8fec..0f8af18d72 100644 --- a/dependency-injection/en/compilation-internals.texy +++ b/dependency-injection/en/compilation-internals.texy @@ -220,3 +220,6 @@ Common Misconceptions - "A `@Type` reference is already a service name." It isn't - it is a type reference, resolved to a concrete name by autowiring only in the complete step. - "My extension reads a helper file, but changes don't show up." Register it with `$builder->addDependency($file)`, otherwise the cache doesn't know about it and won't rebuild. - "During `resolve()` I can call `getByType()`." No - it throws `NotAllowedDuringResolvingException`. Searching by type belongs in `beforeCompile()` or later, never in the middle of resolving. + +{{maintitle: Nette DI Container Compilation: Phases Explained}} +{{description: What happens when Nette compiles a DI container: its phases, when parameters expand, when @service becomes a reference and when you can safely find services.}} diff --git a/dependency-injection/en/configuration.texy b/dependency-injection/en/configuration.texy index ece63f23ef..c3bbbb8238 100644 --- a/dependency-injection/en/configuration.texy +++ b/dependency-injection/en/configuration.texy @@ -332,4 +332,5 @@ items: -{{maintitle: Dependency Injection Configuration}} +{{maintitle: Nette DI Container Configuration: Services and Parameters}} +{{description: Configure the Nette DI container in NEON: parameters, services, the decorator, extensions, including files, searching for services and merging.}} diff --git a/dependency-injection/en/container.texy b/dependency-injection/en/container.texy index 8cd0cc2e5b..df4dc113c0 100644 --- a/dependency-injection/en/container.texy +++ b/dependency-injection/en/container.texy @@ -138,5 +138,5 @@ As you can see, writing a DIC isn't difficult. It's worth noting that the object Manually creating and maintaining the container class can quickly become a nightmare. Therefore, in the next chapter, we will discuss the [Nette DI Container|nette-container], which can generate and update itself almost automatically. - {{maintitle: What Is a Dependency Injection Container?}} +{{description: A DI container creates and configures your services. See what it does, how easy it is to write one by hand and why you will soon want one generated.}} diff --git a/dependency-injection/en/extensions.texy b/dependency-injection/en/extensions.texy index e14637bfe2..a20fe23637 100644 --- a/dependency-injection/en/extensions.texy +++ b/dependency-injection/en/extensions.texy @@ -441,3 +441,6 @@ public function loadConfiguration(): void ``` Both methods only add to the exported metadata; they never override the application's `di › export` configuration. So when the application restricts the export to a list, the tags and types your extension needs stay included; only switching the tags export off entirely (`tags: false`) discards them along with everything else. + +{{maintitle: Creating Nette DI Extensions: Register Services in Code}} +{{description: Write a Nette DI extension that registers services in code, validates its own configuration section, modifies other services and alters the generated container.}} diff --git a/dependency-injection/en/factory.texy b/dependency-injection/en/factory.texy index aa91328f90..5a760350ce 100644 --- a/dependency-injection/en/factory.texy +++ b/dependency-injection/en/factory.texy @@ -231,3 +231,6 @@ services: - MultiFactory(tagged: multi) ``` + +{{maintitle: Nette DI Generated Factories: From Interface to Code}} +{{description: Write only an interface and Nette DI generates the factory code for you. Parameterized factories, accessors, multifactories and advanced definitions.}} diff --git a/dependency-injection/en/faq.texy b/dependency-injection/en/faq.texy index 65a27df0a3..2e9b2b6d05 100644 --- a/dependency-injection/en/faq.texy +++ b/dependency-injection/en/faq.texy @@ -121,3 +121,6 @@ A short vocabulary of the words that keep coming up around Nette DI, most of the - **Tag** - a label attached to a definition (optionally with a value); an extension can then find all services carrying it with `findByTag()`. - **Setup** - additional calls performed on a service right after it is created - method calls or property assignments, added with `addSetup()`. - **Alias** - an alternative name for an existing service. + +{{maintitle: Dependency Injection FAQ: IoC, Service Locator and More}} +{{description: Is DI another name for IoC? What is a service locator? When is it better not to use DI? Clear answers to the most frequent dependency injection questions.}} diff --git a/dependency-injection/en/global-state.texy b/dependency-injection/en/global-state.texy index adae065c9f..706c957ea5 100644 --- a/dependency-injection/en/global-state.texy +++ b/dependency-injection/en/global-state.texy @@ -294,3 +294,6 @@ During this process, you might discover the need to split classes that have mult Would you rather experience all this than just read about it? The course [Dependency Injection by Example |https://github.com/nette-examples/di-by-example] has a chapter where an innocent-looking test quietly drains an account, and you can run it yourself. *I would like to thank Miško Hevery, whose articles such as [Flaw: Brittle Global State & Singletons |https://web.archive.org/web/20230321084133/http://misko.hevery.com/code-reviewers-guide/flaw-brittle-global-state-singletons/] form the basis of this chapter.* + +{{maintitle: PHP Singleton and Global State: Why to Avoid Them}} +{{description: Singletons, static methods and global constants are symptoms of poor design. See why global state makes code fragile and hard to test, and when it is fine.}} diff --git a/dependency-injection/en/introduction.texy b/dependency-injection/en/introduction.texy index ea731b1a35..2237ad36f4 100644 --- a/dependency-injection/en/introduction.texy +++ b/dependency-injection/en/introduction.texy @@ -523,3 +523,6 @@ At the beginning of this chapter, we promised to show a process for designing cl It might not seem apparent at first glance, but these three rules have far-reaching consequences. They lead to a radically different perspective on code design. Is it worthwhile? Programmers who have abandoned old habits and started consistently using Dependency Injection consider this step a defining moment in their professional careers. It opened up a world of clear and maintainable applications for them. But what if the code doesn't consistently use Dependency Injection? What if it's built upon static methods or singletons? Does this lead to problems? [Yes, it does, and very significant ones |global-state]. + +{{maintitle: What Is Dependency Injection? PHP Guide with Examples}} +{{description: Dependency injection explained from scratch with PHP examples: three simple rules that lead you to clean, understandable and maintainable code.}} diff --git a/dependency-injection/en/nette-container.texy b/dependency-injection/en/nette-container.texy index eb91e58878..c5c11f59bf 100644 --- a/dependency-injection/en/nette-container.texy +++ b/dependency-injection/en/nette-container.texy @@ -140,3 +140,6 @@ Using with Nette Framework -------------------------- As we have shown, the use of Nette DI is not restricted to applications built with Nette Framework; you can integrate it anywhere with just three lines of code. However, if you are developing applications using the Nette Framework, the configuration and creation of the container are handled by [Bootstrap |application:bootstrapping#DI Container Configuration]. + +{{maintitle: Nette DI Container: Fast Compiled Container for PHP}} +{{description: Nette DI generates and automatically updates compiled containers that are extremely fast and easy to configure in NEON. See how to use it in practice.}} diff --git a/dependency-injection/en/passing-dependencies.texy b/dependency-injection/en/passing-dependencies.texy index 70539dea5e..0f151961ab 100644 --- a/dependency-injection/en/passing-dependencies.texy +++ b/dependency-injection/en/passing-dependencies.texy @@ -213,3 +213,6 @@ Which Method to Choose? - The constructor is suitable for mandatory dependencies that the class absolutely requires for its operation. - The setter, conversely, is suitable for optional dependencies, or dependencies that might need to be changed later. - Public properties are generally not recommended. + +{{maintitle: PHP Constructor, Setter and Property Injection Compared}} +{{description: How to pass dependencies to a class: constructor injection, setter injection, property injection and the inject method. How they differ and which one to choose.}} diff --git a/dependency-injection/en/services.texy b/dependency-injection/en/services.texy index 2a38d75fc1..1a2b4235b2 100644 --- a/dependency-injection/en/services.texy +++ b/dependency-injection/en/services.texy @@ -478,3 +478,6 @@ If you want to remove a service added by an extension, you can do so as follows: services: cache.journal: false ``` + +{{maintitle: Nette DI Service Definitions: Configure Services in NEON}} +{{description: Tell the DI container how to create your services and connect their dependencies: arguments, setup, expression language, lazy services, tags and inject mode.}} diff --git a/dependency-injection/en/upgrading.texy b/dependency-injection/en/upgrading.texy index c50c1905d2..8e6b452c21 100644 --- a/dependency-injection/en/upgrading.texy +++ b/dependency-injection/en/upgrading.texy @@ -47,3 +47,6 @@ Upgrading to Version 2.3 - support for placing services inside the extension section of the configuration file was removed - support for dynamically added extensions was removed - when replacing a service dynamically (via `removeService()`, `addService()`), the new service must be an instance of the same interface/class as the original + +{{maintitle: Upgrading Nette DI: What Changed in Each Version}} +{{description: What changed in Nette DI 3.1, 3.0, 2.4 and 2.3, and how to update your code and NEON configuration: autowiring of nullable parameters, renamed keys and more.}} diff --git a/forms/cs/@home.texy b/forms/cs/@home.texy index 8fe918e6ff..6a7af6791a 100644 --- a/forms/cs/@home.texy +++ b/forms/cs/@home.texy @@ -30,3 +30,6 @@ Knihovnu stáhnete a nainstalujete pomocí nástroje [Composer|best-practices:co ```shell composer require nette/forms ``` + +{{maintitle: Nette Forms: knihovna pro formuláře v PHP s validací}} +{{description: Bezpečné webové formuláře v PHP na pár řádků kódu. Nette Forms se postarají o vykreslení, validaci v prohlížeči i na serveru a ochranu před útoky.}} diff --git a/forms/cs/configuration.texy b/forms/cs/configuration.texy index cdd7fd2de6..3c313d6e3b 100644 --- a/forms/cs/configuration.texy +++ b/forms/cs/configuration.texy @@ -61,3 +61,6 @@ forms: ``` Pokud nepoužíváte celý framework a tedy ani konfigurační soubory, můžete změnit výchozí chybové hlášky přímo v poli `Nette\Forms\Validator::$messages`. + +{{maintitle: Konfigurace Nette Forms: výchozí chybové hlášky}} +{{description: Výchozí chybové hlášky Nette Forms změníte na jednom místě v konfiguraci NEON, takže je nemusíte nastavovat u každého formuláře nebo prvku zvlášť.}} diff --git a/forms/cs/controls.texy b/forms/cs/controls.texy index 776ecf1c17..93876d3fbe 100644 --- a/forms/cs/controls.texy +++ b/forms/cs/controls.texy @@ -549,3 +549,6 @@ $data = $form->getHttpData($form::DataText | $form::DataKeys, 'sel[]'); kde první parametr je typ elementu (`DataFile` pro `type=file`, `DataLine` pro jednořádkové vstupy jako `text`, `password`, `email` apod. a `DataText` pro všechny ostatní) a druhý parametr `sel[]` odpovídá HTML atributu name. Typ elementu můžeme kombinovat s hodnotou `DataKeys`, která zachová klíče prvků. To se hodí zejména pro `select`, `radioList` a `checkboxList`. Podstatné je, že `getHttpData()` vrací sanitizovanou hodnotu, v tomto případě to bude vždy pole validních UTF-8 řetězců, ať už by se pokusil útočník serveru podstrčit cokoliv. Jde o obdobu přímé práce s `$_POST` nebo `$_GET`, avšak s tím podstatným rozdílem, že vždy vrací čistá data, tak, jak jste zvyklí u standardních prvků Nette formulářů. + +{{maintitle: Formulářové prvky v Nette: text, select, upload, datum}} +{{description: Všechny standardní prvky Nette Forms a jejich nastavení: textová a číselná pole, checkboxy, selectboxy, nahrávání souborů, datum a čas i tlačítka.}} diff --git a/forms/cs/custom-controls.texy b/forms/cs/custom-controls.texy index 1075017627..284f5d67f1 100644 --- a/forms/cs/custom-controls.texy +++ b/forms/cs/custom-controls.texy @@ -266,3 +266,6 @@ final class ZipInput ZipInput::addTo($form, 'zip', 'PSČ:'); ``` + +{{maintitle: Vlastní formulářové prvky v PHP s Nette Forms}} +{{description: Když vestavěné prvky nestačí, napište si vlastní: načtete odeslanou hodnotu, vykreslíte HTML a přidáte validaci. Včetně kompletního příkladu DateInput.}} diff --git a/forms/cs/in-presenter.texy b/forms/cs/in-presenter.texy index 937003bf7b..cb4311c0c0 100644 --- a/forms/cs/in-presenter.texy +++ b/forms/cs/in-presenter.texy @@ -437,3 +437,6 @@ class SignInFormFactory ``` Tak, máme za sebou rychlý úvod do formulářů v Nette. Zkuste se ještě podívat do adresáře [examples|https://github.com/nette/forms/tree/master/examples] v distribuci, kde najdete další inspiraci. + +{{maintitle: Formuláře v presenterech Nette: vytvoření a zpracování}} +{{description: Krok za krokem vytvoříte první formulář v presenteru Nette: validační pravidla, výchozí hodnoty, vykreslení, mapování na třídy a ochrana před CSRF a XSS.}} diff --git a/forms/cs/rendering.texy b/forms/cs/rendering.texy index 7ed6638545..237e397c01 100644 --- a/forms/cs/rendering.texy +++ b/forms/cs/rendering.texy @@ -608,3 +608,6 @@ $form->onRender[] = function ($form) { BootstrapCSS::initialize($form); }; ``` + +{{maintitle: Vykreslování formulářů v Nette: Latte, renderer a Bootstrap}} +{{description: Vykreslete formulář automaticky, nebo mějte jeho HTML plně pod kontrolou: tagy Latte, renderer, šablony pro Bootstrap, HTML atributy a překlady popisků.}} diff --git a/forms/cs/standalone.texy b/forms/cs/standalone.texy index d38efd762d..c08889e065 100644 --- a/forms/cs/standalone.texy +++ b/forms/cs/standalone.texy @@ -335,3 +335,6 @@ Ochrana se opírá o hlavičku `Sec-Fetch-Site` (Fetch Metadata), kterou prohlí Dřívější ochrana pomocí autorizačního tokenu ukládaného do session, kterou aktivovala metoda `$form->addProtection()`, už není potřeba a od verze 3.3 je zavržená. Tak, máme za sebou rychlý úvod do formulářů v Nette. Zkuste se ještě podívat do adresáře [examples|https://github.com/nette/forms/tree/master/examples] v distribuci, kde najdete další inspiraci. + +{{maintitle: Formuláře v PHP bez frameworku: samostatné Nette Forms}} +{{description: Nette Forms fungují v libovolném PHP skriptu i bez zbytku frameworku. Ukážeme si instalaci, definici a validaci formuláře, jeho vykreslení a ochranu před útoky.}} diff --git a/forms/cs/upgrading.texy b/forms/cs/upgrading.texy index 229f15a5a9..393269ecc7 100644 --- a/forms/cs/upgrading.texy +++ b/forms/cs/upgrading.texy @@ -52,3 +52,6 @@ Upgrade na verzi 2.3 - tlačítka a skrytá pole se generují bez HTML ID; pokud ID chcete, nastavte ho přes `setHtmlId()` - položky RadioListu se rovněž generují bez ID; můžete ho zapnout přes `$radioList->generateId = true` - filtry přidané přes `TextBase::addFilter()` se zpracovávají během validace a filtry nyní můžete přidávat i k podmínkám: `$input->addCondition(...)->addFilter(...)` + +{{maintitle: Upgrade Nette Forms: změny v jednotlivých verzích}} +{{description: Co se změnilo v Nette Forms 3.3, 3.1, 3.0, 2.4 a 2.3 a jak upravit kód, aby přechod na novější verzi proběhl hladce.}} diff --git a/forms/cs/validation.texy b/forms/cs/validation.texy index f460ae94d3..41a5269950 100644 --- a/forms/cs/validation.texy +++ b/forms/cs/validation.texy @@ -390,3 +390,6 @@ $form->addSubmit('send5') `setValidationScope` neovlivní [#událost onValidate] u formuláře, která bude zavolána vždy. Událost `onValidate` u kontejneru bude vyvolána pouze tehdy, pokud je tento kontejner označen pro částečnou validaci. Částečná validace ovlivňuje i hodnoty vrácené metodou `getValues()`: výsledek obsahuje pouze hodnoty prvků, které spadají do rozsahu validace. Hodnoty prvků mimo tento rozsah jsou z výsledku vynechány. + +{{maintitle: Validace formulářů v PHP s Nette Forms}} +{{description: Jedna sada pravidel ověří formulář na serveru i v prohlížeči. Povinná pole, podmínky mezi prvky, vlastní pravidla, chybové hlášky a další možnosti.}} diff --git a/forms/en/@home.texy b/forms/en/@home.texy index a9b2549490..b44a2ba402 100644 --- a/forms/en/@home.texy +++ b/forms/en/@home.texy @@ -30,3 +30,6 @@ Download and install the package using [Composer|best-practices:composer]: ```shell composer require nette/forms ``` + +{{maintitle: Nette Forms: PHP Form Library with Built-in Validation}} +{{description: Build secure PHP web forms in a few lines of code. Nette Forms handle rendering, browser and server validation, and protection against attacks.}} diff --git a/forms/en/configuration.texy b/forms/en/configuration.texy index 76d09bcf03..463d9b42b0 100644 --- a/forms/en/configuration.texy +++ b/forms/en/configuration.texy @@ -61,3 +61,6 @@ forms: \-- If you are not using the whole framework and therefore not even the configuration files, you can change the default error messages directly in the `Nette\Forms\Validator::$messages` array. + +{{maintitle: Nette Forms Configuration: Default Error Messages}} +{{description: Change the default error messages of Nette Forms in one place in your NEON configuration, without having to set them for each form or control separately.}} diff --git a/forms/en/controls.texy b/forms/en/controls.texy index 23e428724f..51660eee74 100644 --- a/forms/en/controls.texy +++ b/forms/en/controls.texy @@ -549,3 +549,6 @@ $data = $form->getHttpData($form::DataText | $form::DataKeys, 'sel[]'); where the first parameter is the element type (`DataFile` for `type=file`, `DataLine` for single-line inputs like `text`, `password`, `email`, etc., and `DataText` for all others) and the second parameter `sel[]` corresponds to the HTML name attribute. We can combine the element type with the `DataKeys` value, which preserves the keys of the elements. This is particularly useful for `select`, `radioList`, and `checkboxList`. Crucially, `getHttpData()` returns a sanitized value. In this case, it will always be an array of valid UTF-8 strings, regardless of what an attacker might try to submit to the server. This is analogous to working directly with `$_POST` or `$_GET`, but with the significant difference that it always returns clean data, just as you are accustomed to with standard Nette form controls. + +{{maintitle: Nette Form Controls: Text, Select, Upload, Date and More}} +{{description: All standard form controls in Nette Forms and how to set them up: text and number inputs, checkboxes, selects, file uploads, date and time inputs and buttons.}} diff --git a/forms/en/custom-controls.texy b/forms/en/custom-controls.texy index 52fb56c5d1..2c730dadf8 100644 --- a/forms/en/custom-controls.texy +++ b/forms/en/custom-controls.texy @@ -266,3 +266,6 @@ final class ZipInput ZipInput::addTo($form, 'zip', 'ZIP code:'); ``` + +{{maintitle: Custom Form Controls in PHP with Nette Forms}} +{{description: When the built-in controls aren't enough, write your own: read the submitted value, render the HTML and add validation. Includes a complete DateInput example.}} diff --git a/forms/en/in-presenter.texy b/forms/en/in-presenter.texy index 79d29f6c38..6420eac2c5 100644 --- a/forms/en/in-presenter.texy +++ b/forms/en/in-presenter.texy @@ -437,3 +437,6 @@ class SignInFormFactory ``` So, we've covered a quick introduction to forms in Nette. Try looking in the [examples |https://github.com/nette/forms/tree/master/examples] directory in the distribution for more inspiration. + +{{maintitle: Forms in Nette Presenters: Create and Process a Form}} +{{description: Create your first form in a Nette presenter step by step, with validation rules, default values, rendering, mapping to classes and CSRF and XSS protection.}} diff --git a/forms/en/rendering.texy b/forms/en/rendering.texy index 90cc780e37..0b85220479 100644 --- a/forms/en/rendering.texy +++ b/forms/en/rendering.texy @@ -608,3 +608,6 @@ $form->onRender[] = function ($form) { BootstrapCSS::initialize($form); }; ``` + +{{maintitle: Rendering Nette Forms: Latte, Renderer and Bootstrap}} +{{description: Render a form automatically or take full control of its HTML: Latte tags, the form renderer, Bootstrap templates, HTML attributes and translated labels.}} diff --git a/forms/en/standalone.texy b/forms/en/standalone.texy index 57f0efc234..0527f30af7 100644 --- a/forms/en/standalone.texy +++ b/forms/en/standalone.texy @@ -335,3 +335,6 @@ The protection relies on the browser's `Sec-Fetch-Site` header (Fetch Metadata), The earlier protection using an authorization token stored in the session, activated by `$form->addProtection()`, is no longer needed and is deprecated since version 3.3. So, we've had a quick introduction to forms in Nette. Try looking in the [examples |https://github.com/nette/forms/tree/master/examples] directory in the distribution for more inspiration. + +{{maintitle: PHP Forms Without a Framework: Standalone Nette Forms}} +{{description: Use Nette Forms in any PHP script, no framework needed: install them with Composer, define and validate a form, render it and protect it from attacks.}} diff --git a/forms/en/upgrading.texy b/forms/en/upgrading.texy index 160581e327..39ce67ae26 100644 --- a/forms/en/upgrading.texy +++ b/forms/en/upgrading.texy @@ -52,3 +52,6 @@ Upgrading to Version 2.3 - Buttons and Hidden fields are generated without an HTML ID; if you want an ID, set it via `setHtmlId()` - RadioList items are generated without an ID too; you can enable it via `$radioList->generateId = true` - filters added via `TextBase::addFilter()` are processed during validation, and you can now add filters to conditions: `$input->addCondition(...)->addFilter(...)` + +{{maintitle: Upgrading Nette Forms: What Changed in Each Version}} +{{description: What changed in Nette Forms 3.3, 3.1, 3.0, 2.4 and 2.3, and how to update your code so that moving to a newer version goes smoothly.}} diff --git a/forms/en/validation.texy b/forms/en/validation.texy index 98de0cf807..791483947c 100644 --- a/forms/en/validation.texy +++ b/forms/en/validation.texy @@ -390,3 +390,6 @@ $form->addSubmit('send5') `setValidationScope` does not affect the [#Event onValidate] on the form, which will always be called. The `onValidate` event on a container will only be triggered if that container is marked for partial validation. Partial validation also affects the values returned by `getValues()`: the result contains only the values of controls that fall within the validation scope. Values of controls outside this scope are omitted. + +{{maintitle: PHP Form Validation with Nette Forms}} +{{description: One set of rules validates a form on the server and in the browser. Required fields, conditions between controls, custom rules, error messages and more.}} diff --git a/http/cs/@home.texy b/http/cs/@home.texy index c37533596e..14d4163a0e 100644 --- a/http/cs/@home.texy +++ b/http/cs/@home.texy @@ -22,3 +22,6 @@ composer require nette/http ``` Balíček vyžaduje PHP verze 8.3 až 8.6. + +{{maintitle: Nette HTTP: požadavek, odpověď, sessions a URL v PHP}} +{{description: Srozumitelné objektové API nad HTTP požadavkem a odpovědí v PHP, které usnadňuje práci se sessions a URL a stará se i o bezpečnost.}} diff --git a/http/cs/configuration.texy b/http/cs/configuration.texy index e42f5796db..04f6889130 100644 --- a/http/cs/configuration.texy +++ b/http/cs/configuration.texy @@ -208,3 +208,6 @@ Tyto služby se přidávají do DI kontejneru: | `http.response` | [api:Nette\Http\Response] | [HTTP response| response] | `session.session` | [api:Nette\Http\Session] | [správa session| sessions] | `http.requestFactory`| [api:Nette\Http\RequestFactory] | továrna vytvářející HTTP request + +{{maintitle: Konfigurace Nette HTTP: hlavičky, CSP, cookies a session}} +{{description: Konfigurace Nette HTTP v NEON: hlavičky odpovědi, Content Security Policy, cookies, proxy, vynucení HTTPS, základní URL a nastavení session.}} diff --git a/http/cs/request.texy b/http/cs/request.texy index 7c2c6eb45e..5ef150679d 100644 --- a/http/cs/request.texy +++ b/http/cs/request.texy @@ -468,3 +468,6 @@ Vrací dvojici `[šířka, výška]` s rozměry uploadovaného obrázku. V pří toImage(): Nette\Utils\Image .[method] -------------------------------------- Načte obrázek jako objekt [Image|utils:images]. V případě, že upload nebyl úspěšný nebo nejde o platný obrázek, vyhodí výjimku `Nette\Utils\ImageException`. + +{{maintitle: HTTP požadavek v Nette: parametry, hlavičky a nahrané soubory}} +{{description: Čtěte data z POST a GET, hlavičky, cookies a nahrané soubory přes srozumitelné API. Nette navíc ze vstupu odstraní řídicí znaky a neplatné UTF-8.}} diff --git a/http/cs/response.texy b/http/cs/response.texy index c83eb952b1..9b0fb1f374 100644 --- a/http/cs/response.texy +++ b/http/cs/response.texy @@ -182,3 +182,6 @@ public function send(Nette\Http\IRequest $request, Nette\Http\IResponse $respons ``` Oba parametry jsou volitelné. Pokud čas změny obsahu neznáte, použijte jen ETag, a naopak. + +{{maintitle: HTTP odpověď v Nette: stavové kódy, hlavičky a cookies}} +{{description: Ovládejte HTTP odpověď přes srozumitelné API: stavový kód a hlavičky, odesílání cookies, přesměrování a řízení cache v prohlížeči.}} diff --git a/http/cs/sessions.texy b/http/cs/sessions.texy index a4fc0ba0ac..813aeb262d 100644 --- a/http/cs/sessions.texy +++ b/http/cs/sessions.texy @@ -209,3 +209,6 @@ Nette Framework proto správně nakonfiguruje PHP direktivy, aby session ID pře .[note] Pro konfiguraci PHP se používá funkce ini_set, kterou bohužel některé hostingy zakazují. Pokud to platí i pro vašeho poskytovatele hostingu, pokuste se s ním domluvit, aby vám funkci povolil nebo alespoň server nakonfiguroval. + +{{maintitle: Sessions v PHP s Nette: sekce, expirace a bezpečnost}} +{{description: Uchovávejte stav mezi požadavky, třeba nákupní košík. Session v Nette předchází konfliktům názvů pomocí sekcí, umí nastavit expiraci a dbá na bezpečnost.}} diff --git a/http/cs/ssrf.texy b/http/cs/ssrf.texy index d1e583429f..ea8f696f65 100644 --- a/http/cs/ssrf.texy +++ b/http/cs/ssrf.texy @@ -181,3 +181,6 @@ $ip->toIPv4(); // IPAddress('127.0.0.1') ``` Metody `isIPv4()` a `isIPv6()` hlásí textový tvar: mapovaná adresa je IPv6, nikoli IPv4. + +{{maintitle: Ochrana proti SSRF v PHP s Nette: UrlValidator a IPAddress}} +{{description: Když aplikace stahuje URL od uživatele, může se útočník dostat do vaší interní sítě. Třídy UrlValidator a IPAddress chrání PHP aplikaci před útoky SSRF.}} diff --git a/http/cs/upgrading.texy b/http/cs/upgrading.texy index 91c048cefb..4f8bacc1af 100644 --- a/http/cs/upgrading.texy +++ b/http/cs/upgrading.texy @@ -59,3 +59,6 @@ Upgrade na verzi 3.0 - objekt `Nette\Http\UrlScript` (který vrací třeba `Nette\Http\Request::getUrl()`) je nyní immutable - v zápisu `new Nette\Http\Url('abcd')` představuje `abcd` cestu, nikoliv doménu; od verze 3.0 tedy `(new Nette\Http\Url('abcd'))->setScheme('http')` korektně vygeneruje `http:abcd` místo dřívějšího `http://abcd` + +{{maintitle: Upgrade Nette HTTP: změny v jednotlivých verzích}} +{{description: Co se změnilo v Nette HTTP 3.4.1, 3.4, 3.2, 3.1 a 3.0 a jak upravit kód, včetně toho, kterým hlavičkám z proxy se důvěřuje.}} diff --git a/http/cs/urls.texy b/http/cs/urls.texy index a959ba5afd..b1310c697f 100644 --- a/http/cs/urls.texy +++ b/http/cs/urls.texy @@ -272,3 +272,6 @@ Pro vrácení částí URL jsou k dispozici metody: | `getPathInfo(): string` | `'/pathinfo/'` Objekty `UrlScript` obvykle přímo nevytváříme, ale vrací je metoda [Nette\Http\Request::getUrl()|request] s již správně nastavenými komponentami pro aktuální HTTP požadavek. + +{{maintitle: Práce s URL v PHP s Nette: parsování a sestavení adres}} +{{description: Parsujte, sestavujte a upravujte URL v PHP pomocí tříd Url, UrlImmutable a UrlScript: parametry v query, porovnávání adres a cesta ke skriptu.}} diff --git a/http/en/@home.texy b/http/en/@home.texy index edc56f4d9b..4b00a6ccba 100644 --- a/http/en/@home.texy +++ b/http/en/@home.texy @@ -22,3 +22,6 @@ composer require nette/http ``` The package requires PHP version 8.3 to 8.6. + +{{maintitle: Nette HTTP: Request, Response, Sessions and URLs in PHP}} +{{description: A clear object API over the HTTP request and response in PHP that also simplifies working with sessions and URLs and takes care of security.}} diff --git a/http/en/configuration.texy b/http/en/configuration.texy index 74f1bdf8ca..56b4f70ab9 100644 --- a/http/en/configuration.texy +++ b/http/en/configuration.texy @@ -208,3 +208,6 @@ These services are added to the DI container: | `http.response` | [api:Nette\Http\Response] | [HTTP response| response] | `session.session`| [api:Nette\Http\Session] | [session management| sessions] | `http.requestFactory`| [api:Nette\Http\RequestFactory] | factory that creates the HTTP request + +{{maintitle: Nette HTTP Configuration: Headers, CSP, Cookies, Session}} +{{description: Configure Nette HTTP in NEON: response headers, Content Security Policy, cookies, proxies, forced HTTPS, the base URL and session settings.}} diff --git a/http/en/request.texy b/http/en/request.texy index 4d8c70ce4e..14306cf44f 100644 --- a/http/en/request.texy +++ b/http/en/request.texy @@ -468,3 +468,6 @@ Returns a pair `[width, height]` with the dimensions of the uploaded image. If t toImage(): Nette\Utils\Image .[method] -------------------------------------- Loads the image as an [Image |utils:images] object. If the upload was not successful or it is not a valid image, it throws a `Nette\Utils\ImageException`. + +{{maintitle: Nette HTTP Request: Parameters, Headers and File Uploads}} +{{description: Read POST and GET data, headers, cookies and uploaded files through a clear API. Nette also strips control characters and invalid UTF-8 from the input.}} diff --git a/http/en/response.texy b/http/en/response.texy index 6d5c3afb5a..4c2fe60f2a 100644 --- a/http/en/response.texy +++ b/http/en/response.texy @@ -182,3 +182,6 @@ public function send(Nette\Http\IRequest $request, Nette\Http\IResponse $respons ``` Both parameters are optional. If you do not know the modification time of the content, use only the ETag, and vice versa. + +{{maintitle: Nette HTTP Response: Status Codes, Headers and Cookies}} +{{description: Control the HTTP response through a clear API: set the status code and headers, send cookies, redirect and control browser caching.}} diff --git a/http/en/sessions.texy b/http/en/sessions.texy index 95f228ae69..182dc43a57 100644 --- a/http/en/sessions.texy +++ b/http/en/sessions.texy @@ -209,3 +209,6 @@ Nette Framework therefore correctly configures PHP directives to transfer the se .[note] The `ini_set` function is used for configuring PHP, but unfortunately, some hosting providers prohibit its use. If this is the case with your host, try to arrange with them to allow this function for you or at least configure the server properly. + +{{maintitle: PHP Sessions in Nette: Sections, Expiration and Security}} +{{description: Keep state between requests, such as a shopping cart. Nette sessions prevent naming conflicts with sections, let you set expiration and take care of security.}} diff --git a/http/en/ssrf.texy b/http/en/ssrf.texy index f4321a5183..29bf0ef71a 100644 --- a/http/en/ssrf.texy +++ b/http/en/ssrf.texy @@ -181,3 +181,6 @@ $ip->toIPv4(); // IPAddress('127.0.0.1') ``` The `isIPv4()` and `isIPv6()` methods report the textual form: a mapped address is IPv6, not IPv4. + +{{maintitle: PHP SSRF Protection with Nette: UrlValidator and IPAddress}} +{{description: Downloading a URL supplied by a user lets an attacker reach your internal network. UrlValidator and IPAddress guard your PHP application against SSRF attacks.}} diff --git a/http/en/upgrading.texy b/http/en/upgrading.texy index bdf21793aa..e32c1b0d08 100644 --- a/http/en/upgrading.texy +++ b/http/en/upgrading.texy @@ -59,3 +59,6 @@ Upgrading to Version 3.0 - the `Nette\Http\UrlScript` object (returned e.g. by `Nette\Http\Request::getUrl()`) is now immutable - in `new Nette\Http\Url('abcd')`, `abcd` represents the path, not the domain; since 3.0, `(new Nette\Http\Url('abcd'))->setScheme('http')` correctly generates `http:abcd` instead of the previous `http://abcd` + +{{maintitle: Upgrading Nette HTTP: What Changed in Each Version}} +{{description: What changed in Nette HTTP 3.4.1, 3.4, 3.2, 3.1 and 3.0 and how to update your code, including which proxy headers are trusted.}} diff --git a/http/en/urls.texy b/http/en/urls.texy index 71baac19f6..90f56760cf 100644 --- a/http/en/urls.texy +++ b/http/en/urls.texy @@ -272,3 +272,6 @@ The following methods are available to retrieve these parts of the URL: | `getPathInfo(): string` | `'/pathinfo/'` We usually do not create `UrlScript` objects directly; instead, the [Nette\Http\Request::getUrl() |request] method returns it with the components already correctly set for the current HTTP request. + +{{maintitle: PHP URL Parsing and Building with Nette: Url and UrlScript}} +{{description: Parse, build and modify URLs in PHP with the Url, UrlImmutable and UrlScript classes: query parameters, comparing URLs and getting the script path.}} diff --git a/latte/cs/@home.texy b/latte/cs/@home.texy index ce78127c9c..6f62b4343b 100644 --- a/latte/cs/@home.texy +++ b/latte/cs/@home.texy @@ -1,3 +1,3 @@ -{{maintitle: Latte – nejbezpečnější & opravdu intuitivní šablony pro PHP}} -{{description: Latte je nejbezpečnější šablonovací systém pro PHP. Zabraňuje spoustě bezpečnostních zranitelností. Oceníte jeho intuitivní syntaxi a potěší vás spousta užitečných vychytávek.}} {{leftbar: no}} +{{maintitle: Latte – nejbezpečnější & opravdu intuitivní šablony pro PHP}} +{{description: Latte je nejbezpečnější šablonovací systém pro PHP. Zabraňuje spoustě zranitelností a oceníte jeho intuitivní syntaxi i řadu užitečných vychytávek.}} diff --git a/latte/cs/compiler-passes.texy b/latte/cs/compiler-passes.texy index 0c1550a494..61f4205d18 100644 --- a/latte/cs/compiler-passes.texy +++ b/latte/cs/compiler-passes.texy @@ -576,3 +576,6 @@ Při psaní kompilačních průchodů mějte na paměti tyto zásady pro vytvá - **Idempotence (pokud možno):** Ideálně by spuštění vašeho průchodu vícekrát na stejném AST mělo produkovat stejný výsledek jako jeho jednorázové spuštění. Není to vždy proveditelné, ale pokud se to podaří, zjednoduší to ladění i uvažování o vzájemných interakcích průchodů. Například zajistěte, aby váš modifikační průchod kontroloval, zda modifikace již byla aplikována, než ji aplikuje znovu. Dodržováním těchto postupů můžete kompilační průchody využít k rozšíření možností Latte mocným a spolehlivým způsobem, což vede k bezpečnějšímu, lépe optimalizovanému nebo funkčně bohatšímu zpracování šablon. + +{{maintitle: Kompilační průchody v Latte: analýza a úprava šablon}} +{{description: Analyzujte a upravujte šablony Latte mezi parsováním a generováním PHP kódu: procházení AST pomocí NodeTraverser pro optimalizace či bezpečnostní kontroly.}} diff --git a/latte/cs/cookbook/@home.texy b/latte/cs/cookbook/@home.texy index 357874fb99..b550a1ae33 100644 --- a/latte/cs/cookbook/@home.texy +++ b/latte/cs/cookbook/@home.texy @@ -14,3 +14,6 @@ Příklady kódů a receptů pro provádění běžných úkolů pomocí Latte. - [Migrace z Twigu |migration-from-twig] - [Použití Latte se Slim 4 |slim-framework] - [Použití Latte s CakePHP |https://github.com/josbeir/cakephp-latte-view] + +{{maintitle: Návody a recepty pro šablony Latte v PHP}} +{{description: Praktické návody na běžné úkoly v Latte: seskupování dat, předávání proměnných mezi šablonami, migrace z Twigu či PHP a použití se Slim Frameworkem.}} diff --git a/latte/cs/cookbook/grouping.texy b/latte/cs/cookbook/grouping.texy index 526b3c2dc9..f072a0333e 100644 --- a/latte/cs/cookbook/grouping.texy +++ b/latte/cs/cookbook/grouping.texy @@ -251,3 +251,6 @@ Dejme tomu, že v tabulce bude ještě sloupec `subcategoryId`, a kromě toho, {/foreach} ``` + +{{maintitle: Seskupování dat v Latte: group, batch a iterateWhile}} +{{description: Seskupte položky, rozdělte je do dávek nebo je procházejte podle podmínky. Kdy v šablonách Latte sáhnout po filtru group, filtru batch nebo tagu iterateWhile.}} diff --git a/latte/cs/cookbook/how-to-write-sql-queries-in-latte.texy b/latte/cs/cookbook/how-to-write-sql-queries-in-latte.texy index 35d275b61e..fdb192a9a1 100644 --- a/latte/cs/cookbook/how-to-write-sql-queries-in-latte.texy +++ b/latte/cs/cookbook/how-to-write-sql-queries-in-latte.texy @@ -38,3 +38,6 @@ $result = $db->query($sql); ``` *Uvedený příklad vyžaduje Latte v3.0.5 nebo vyšší.* + +{{maintitle: Jak psát SQL dotazy v šablonách Latte}} +{{description: SQL dotaz s mnoha podmínkami a proměnnými se rychle stává nepřehledným. Když ho napíšete jako šablonu Latte, zůstane přehledný i ten opravdu složitý.}} diff --git a/latte/cs/cookbook/migration-from-latte-30.texy b/latte/cs/cookbook/migration-from-latte-30.texy index c9710c1007..11f9ff07db 100644 --- a/latte/cs/cookbook/migration-from-latte-30.texy +++ b/latte/cs/cookbook/migration-from-latte-30.texy @@ -108,3 +108,6 @@ Během migrace si můžete začít užívat nové funkce: - **`n:elseif`:** Nyní můžete používat `n:elseif` společně s `n:if` a `n:else`. - **Zjednodušená syntaxe:** Pište `
` bez uvozovek. - **Toggle filtr:** Použijte `|toggle` k ručnímu ovládání boolean atributů. + +{{maintitle: Migrace z Latte 3.0 na 3.1: co se mění}} +{{description: Latte 3.1 přináší bezpečnější a pohodlnější šablony. Na co si dát při přechodu pozor: chytré atributy, strict types, globální konstanty a odstraněné funkce.}} diff --git a/latte/cs/cookbook/migration-from-latte2.texy b/latte/cs/cookbook/migration-from-latte2.texy index 80a28d6287..1d9bea2fb5 100644 --- a/latte/cs/cookbook/migration-from-latte2.texy +++ b/latte/cs/cookbook/migration-from-latte2.texy @@ -302,3 +302,5 @@ class FooNode extends Latte\Compiler\Nodes\StatementNode ``` {{priority: -1}} +{{maintitle: Migrace z Latte 2 na Latte 3: změny syntaxe a API}} +{{description: Latte 3 má přepsaný kompilátor a přesně definovanou gramatiku. Podívejte se, co se změnilo v syntaxi a API a jak upravit šablony, doplňky a konfiguraci.}} diff --git a/latte/cs/cookbook/migration-from-php.texy b/latte/cs/cookbook/migration-from-php.texy index 002cb5527a..b310b4852e 100644 --- a/latte/cs/cookbook/migration-from-php.texy +++ b/latte/cs/cookbook/migration-from-php.texy @@ -68,3 +68,6 @@ Vygeneruje tuto šablonu:
``` + +{{maintitle: Převod PHP šablon do Latte: online nástroj pro migraci}} +{{description: Převádíte starý projekt z čistého PHP do Latte? Převodník využívá skutečný PHP parser, takže zvládne i složitý kód. Vyzkoušejte ho online nebo lokálně.}} diff --git a/latte/cs/cookbook/migration-from-twig.texy b/latte/cs/cookbook/migration-from-twig.texy index 4bc33d2c53..028a2b1f2f 100644 --- a/latte/cs/cookbook/migration-from-twig.texy +++ b/latte/cs/cookbook/migration-from-twig.texy @@ -77,3 +77,6 @@ Po konverzi do Latte získáme tuto šablonu: ``` + +{{maintitle: Migrace z Twigu do Latte: online nástroj pro převod}} +{{description: Převádíte projekt z Twigu do Latte? Převodník využívá skutečný parser Twigu, takže zvládne i složité šablony. Vyzkoušejte ho online nebo na svém počítači.}} diff --git a/latte/cs/cookbook/passing-variables.texy b/latte/cs/cookbook/passing-variables.texy index 846938e0ac..90ddda4bfb 100644 --- a/latte/cs/cookbook/passing-variables.texy +++ b/latte/cs/cookbook/passing-variables.texy @@ -156,3 +156,6 @@ Tag `{sandbox}` izoluje šablonu pro bezpečné zpracování. Proměnné jsou p ```latte {sandbox 'secure.latte', data: $secureData} ``` + +{{maintitle: Předávání proměnných mezi šablonami Latte}} +{{description: Které proměnné se v Latte dostanou do vložené šablony, bloku, layoutu nebo embedu? Přehled toho, jak se proměnné předávají mezi šablonami, tag po tagu.}} diff --git a/latte/cs/cookbook/slim-framework.texy b/latte/cs/cookbook/slim-framework.texy index 78600056f3..5f50756428 100644 --- a/latte/cs/cookbook/slim-framework.texy +++ b/latte/cs/cookbook/slim-framework.texy @@ -155,3 +155,5 @@ Three ``` {{priority: -1}} +{{maintitle: Šablony Latte ve Slim Frameworku 4}} +{{description: Jak přidat šablonovací systém Latte do aplikace ve Slimu 4: konfigurace v DI kontejneru a vykreslování šablon z vašich akcí.}} diff --git a/latte/cs/custom-filters.texy b/latte/cs/custom-filters.texy index 47ba53dc7d..2ae9ced1e2 100644 --- a/latte/cs/custom-filters.texy +++ b/latte/cs/custom-filters.texy @@ -205,3 +205,6 @@ Filtry aplikované na [bloky |tags#block] s jiným než textovým obsahem (typic ``` Kontextové filtry dávají silnou kontrolu nad tím, jak se data zpracovávají podle svého kontextu. Umožňují pokročilé použití a zajišťují správné escapování, zejména při generování HTML obsahu. + +{{maintitle: Vlastní filtry v Latte: jak je vytvořit a zaregistrovat}} +{{description: Napište si vlastní filtry pro formátování a úpravu dat přímo v šablonách Latte: jak je vytvořit a zaregistrovat, předávat jim argumenty a psát kontextové filtry.}} diff --git a/latte/cs/custom-functions.texy b/latte/cs/custom-functions.texy index 3851de9a87..6a00cf16a3 100644 --- a/latte/cs/custom-functions.texy +++ b/latte/cs/custom-functions.texy @@ -142,3 +142,6 @@ Latte automaticky najde a zaregistruje metody označené tímto atributem, když **Kontextové funkce?** Na rozdíl od filtrů funkce neobdrží objekt `FilterInfo`. Kontext šablony ale získat lze: pokud je první parametr funkce typově označen jako `Latte\Runtime\Template`, Latte jí automaticky předá objekt aktuální šablony. Přesně takto jsou implementovány vestavěné funkce `hasBlock()` a `hasTemplate()`. + +{{maintitle: Vlastní funkce v Latte: PHP pomocníci v šablonách}} +{{description: Přidejte do šablon Latte vlastní pomocné funkce a volejte PHP logiku přímo ve výrazech pro výpočty, přístup ke službám nebo generování dynamického obsahu.}} diff --git a/latte/cs/custom-tags.texy b/latte/cs/custom-tags.texy index b602384e8e..71912eab88 100644 --- a/latte/cs/custom-tags.texy +++ b/latte/cs/custom-tags.texy @@ -1147,3 +1147,6 @@ Dodržováním těchto pokynů můžete vytvářet mocné, robustní a udržovat .[note] Studium tříd uzlů, které jsou součástí Latte, je nejlepší způsob, jak se naučit všechny podrobnosti o procesu parsování. + +{{maintitle: Vlastní tagy v Latte: kompletní návod na jejich tvorbu}} +{{description: Vytvořte si vlastní tagy v Latte, od jednoduchých po párové s vnořeným obsahem: jak se šablony kompilují, jak parsovat argumenty a jak generovat PHP kód.}} diff --git a/latte/cs/develop.texy b/latte/cs/develop.texy index 8c07ff9c33..0a4900d7ee 100644 --- a/latte/cs/develop.texy +++ b/latte/cs/develop.texy @@ -454,3 +454,6 @@ $latte->addProvider('coreParentFinder', $finder); ``` Pokud šablona nemá mít layout, oznámí to značkou `{layout none}`. + +{{maintitle: Latte v PHP: instalace, vykreslení šablon a nastavení}} +{{description: Nainstalujte Latte přes Composer, vykreslete šablonu z PHP a nastavte ho: cache, striktní režim, národní prostředí, překlady, linter a ladění s Tracy.}} diff --git a/latte/cs/extending-latte.texy b/latte/cs/extending-latte.texy index 867d8813e8..c0f3aa5a94 100644 --- a/latte/cs/extending-latte.texy +++ b/latte/cs/extending-latte.texy @@ -223,3 +223,6 @@ getCacheKey(Latte\Engine $engine): mixed .[method] -------------------------------------------------- Volá se před vykreslením šablony. Návratová hodnota se stává součástí klíče, jehož hash je obsažen v názvu souboru kompilované šablony. Pro různé návratové hodnoty tedy Latte vygeneruje různé cache soubory. + +{{maintitle: Rozšiřování Latte: vlastní tagy, filtry a rozšíření}} +{{description: Nestačí vám vestavěné tagy a filtry? Přehled všech způsobů, jak Latte rozšířit, od registrace jednoduchého filtru až po kompletní Latte Extension.}} diff --git a/latte/cs/filters.texy b/latte/cs/filters.texy index 23bf6afd3d..9ab1536e01 100644 --- a/latte/cs/filters.texy +++ b/latte/cs/filters.texy @@ -1014,3 +1014,6 @@ Převádí se na ASCII. Převede mezery na pomlčky. Odstraní znaky, které nej .[caution] Vyžaduje knihovnu [nette/utils|utils:]. + +{{maintitle: Filtry v Latte: úprava výstupu v PHP šablonách}} +{{description: Všechny vestavěné filtry Latte s příklady: formátování data a čísel, úprava a zkracování řetězců, řazení a seskupování polí a mnoho dalšího.}} diff --git a/latte/cs/functions.texy b/latte/cs/functions.texy index de315c5afb..bb506828a3 100644 --- a/latte/cs/functions.texy +++ b/latte/cs/functions.texy @@ -164,3 +164,6 @@ Pokud je start nezáporný, posloupnost začne posunutá o tento počet od zač Pokud je zadaný parametr length a je kladný, posloupnost bude obsahovat nejvýše tolik prvků. Pokud je vstup kratší než length, budou přítomny pouze dostupné prvky. Pokud je length záporný, posloupnost skončí o tolik prvků před koncem vstupu. Pokud tento parametr nezadáte, posloupnost bude obsahovat všechny prvky od pozice start až do konce vstupu. Ve výchozím nastavení funkce změní pořadí a resetuje celočíselné klíče pole. Toto chování lze změnit nastavením preserveKeys na true. Řetězcové klíče jsou vždy zachovány, bez ohledu na tento parametr. + +{{maintitle: Funkce v Latte: clamp, first, group, slice a další}} +{{description: Kromě běžných PHP funkcí můžete v šablonách Latte používat i tyto: clamp, divisibleBy, even, odd, first, last, group, slice, hasBlock a hasTemplate.}} diff --git a/latte/cs/guide.texy b/latte/cs/guide.texy index 218e2fffa6..334d9104dd 100644 --- a/latte/cs/guide.texy +++ b/latte/cs/guide.texy @@ -42,5 +42,5 @@ Latte dostáváte v plné výbavě, se vším důležitým v základu. - -{{description: Latte je nejbezpečnější šablonovací systém pro PHP. Zabraňuje spoustě bezpečnostních zranitelností. Oceníte jeho intuitivní syntaxi a potěší vás spousta užitečných vychytávek.}} +{{maintitle: Začínáme s Latte: šablonovací systém pro PHP}} +{{description: Začněte s Latte během pár minut: naučíte se syntaxi, tagy a filtry, nasadíte ho do své PHP aplikace a objevíte dědičnost šablon, sandbox a další možnosti.}} diff --git a/latte/cs/html-attributes.texy b/latte/cs/html-attributes.texy index 28cf45add6..a347ac0a6f 100644 --- a/latte/cs/html-attributes.texy +++ b/latte/cs/html-attributes.texy @@ -177,3 +177,6 @@ Protože se změnilo chování `null` (dříve vypisovalo `""`, nyní atribut vy Pro hladký přechod poskytuje Latte migrační režim, který upozorňuje na rozdíly. Přečtěte si podrobného průvodce [Migrace z Latte 3.0 na 3.1 |cookbook/migration-from-latte-30]. [* html-attributes.webp *] + +{{maintitle: Chytré HTML atributy v Latte: třídy, styly a boolean hodnoty}} +{{description: Latte 3.1 usnadňuje a zabezpečuje vypisování HTML atributů: boolean atributy, hodnoty null, pole pro class a style, data a aria atributy a typová kontrola.}} diff --git a/latte/cs/loaders.texy b/latte/cs/loaders.texy index 299a95f2c5..d805325e27 100644 --- a/latte/cs/loaders.texy +++ b/latte/cs/loaders.texy @@ -196,3 +196,6 @@ $latte->render('homepage'); // Načte šablonu s názvem 'homepage' z DB ``` Vlastní loadery vám dávají úplnou kontrolu nad tím, odkud vaše Latte šablony pocházejí, což umožňuje integraci s různými systémy úložišť a pracovními postupy. + +{{maintitle: Loadery v Latte: šablony ze souborů, řetězců nebo databáze}} +{{description: Načítejte šablony Latte odkudkoliv: ze souborů pomocí FileLoaderu, z řetězců pomocí StringLoaderu nebo vlastním loaderem, ukázaným na příkladu s databází.}} diff --git a/latte/cs/recipes.texy b/latte/cs/recipes.texy index edd16bd410..a23a56145a 100644 --- a/latte/cs/recipes.texy +++ b/latte/cs/recipes.texy @@ -160,3 +160,6 @@ Inkludovaná šablona `included.latte`: {* zapíšeme data do property foo *} {var $vars->foo = 123} ``` + +{{maintitle: Tipy a triky pro Latte: pluginy do IDE, JavaScript a XML}} +{{description: Pluginy pro Latte do PhpStormu a dalších editorů, Latte uvnitř JavaScriptu a CSS, generování XML, náhrada klauzule use a předávání dat mezi šablonami.}} diff --git a/latte/cs/safety-first.texy b/latte/cs/safety-first.texy index c38373822d..b71f6ba358 100644 --- a/latte/cs/safety-first.texy +++ b/latte/cs/safety-first.texy @@ -408,3 +408,6 @@ Latte není zcela kompletní ochranou před XSS pro celou aplikaci. Byli bychom .[tip] Chcete si ověřit své znalosti escapování v jednotlivých kontextech? Vyzkoušejte [kvíz o zranitelnosti XSS |https://blog.nette.org/cs/kviz-ubranite-se-pred-zranitelnosti-xss]. + +{{maintitle: Ochrana před XSS v PHP: kontextové escapování v Latte}} +{{description: Proč je XSS tak nebezpečné a jak ho Latte zastaví: pozná, kde se hodnota vypisuje, a podle toho ji escapuje. Naivní šablonovací systémy to nedokážou.}} diff --git a/latte/cs/sandbox.texy b/latte/cs/sandbox.texy index 6e4a2893bc..d197fbf5cf 100644 --- a/latte/cs/sandbox.texy +++ b/latte/cs/sandbox.texy @@ -118,3 +118,6 @@ Smyslem metody `__toString()` je vyrobit textovou reprezentaci objektu, takže j Tyhle nejpřímější případy by Latte zachytit dokázalo, ale ne spolehlivě a ne všechny. Převod objektu na řetězec totiž není volání metody, ale vestavěná operace jazyka, ke které dochází na mnoha místech výrazu. Někde (třeba při porovnání objektu s řetězcem nebo uvnitř volané funkce či filtru) by ji nešlo spolehlivě zachytit, aniž by se přitom blokovalo i legitimní použití. Proto je s dosažitelností `__toString()` potřeba počítat. **Nevystavujte sandboxu objekty, jejichž `__toString()` má vedlejší efekty nebo zpřístupňuje citlivé údaje.** A to nejen ty, které šabloně předáte přímo, ale i ty, které autor získá jako návratovou hodnotu povolené funkce, metody nebo property. + +{{maintitle: Sandbox v Latte: bezpečné spouštění cizích šablon}} +{{description: Určete, jaké tagy, filtry, PHP funkce a metody smí šablona používat. Klient nebo externí kodér pak může šablony upravovat, aniž by ohrozil vaši aplikaci.}} diff --git a/latte/cs/syntax.texy b/latte/cs/syntax.texy index 69f9ff78e8..5443dcb0db 100644 --- a/latte/cs/syntax.texy +++ b/latte/cs/syntax.texy @@ -343,3 +343,6 @@ Omezení PHP v Latte V Latte lze zapisovat jen PHP výrazy. Tedy nelze používat statementy ukončené středníkem. Nelze deklarovat třídy nebo používat [řídicí struktury |https://www.php.net/manual/en/language.control-structures.php], např. `if`, `foreach`, `switch`, `return`, `try`, `throw` a další, místo kterých Latte nabízí své [značky|tags]. Také nelze používat [atributy |https://www.php.net/manual/en/language.attributes.php], [backticks |https://www.php.net/manual/en/language.operators.execution.php] či některé [magické konstanty |https://www.php.net/manual/en/language.constants.magic.php]. Nelze používat ani `unset`, `echo`, `include`, `require`, `exit`, `eval`, protože nejde o funkce, ale speciální jazykové konstrukce PHP, a nejsou to tedy výrazy. Komentáře jsou podporované jen víceřádkové `/* ... */`. Tato omezení lze nicméně obejít tím, že si aktivujete rozšíření [RawPhpExtension |develop#RawPhpExtension], díky kterému lze pak používat ve značce `{php ...}` jakýkoliv PHP kód na zodpovědnost autora šablony. + +{{maintitle: Syntaxe Latte: tagy, n:atributy, filtry a komentáře}} +{{description: Syntaxe Latte vychází z PHP a rychle si ji osvojíte: tagy, n:atributy přímo v HTML, filtry, dynamické HTML značky, komentáře a řízení bílých znaků.}} diff --git a/latte/cs/tags.texy b/latte/cs/tags.texy index 760c472a33..d12b258caf 100644 --- a/latte/cs/tags.texy +++ b/latte/cs/tags.texy @@ -1092,3 +1092,6 @@ Značku lze také zapsat jako [n:attribut |syntax#n:atributy] pro překlad vnit ```latte

Objednávka

``` + +{{maintitle: Tagy v Latte: foreach, if, include, block a další}} +{{description: Všechny tagy (makra) šablonovacího systému Latte s příklady: vypisování, podmínky, cykly foreach, vkládání šablon, bloky, výjimky, proměnné a překlady.}} diff --git a/latte/cs/template-inheritance.texy b/latte/cs/template-inheritance.texy index 621591e9a8..ffcddbfd37 100644 --- a/latte/cs/template-inheritance.texy +++ b/latte/cs/template-inheritance.texy @@ -758,3 +758,6 @@ V Latte existují různé typy dědičnosti a opětovného použití kódu. Poj {block last}Last Service Page{/block} {/embed} ``` + +{{maintitle: Dědičnost šablon v PHP s Latte: layout, block a embed}} +{{description: Přestaňte v šablonách opakovat HTML. Dědičnost layoutů, bloky, horizontální znovupoužití a embed zařídí, že každá šablona Latte obsahuje jen svůj vlastní obsah.}} diff --git a/latte/cs/type-system.texy b/latte/cs/type-system.texy index 68fc8e2c27..f2a2ee0c39 100644 --- a/latte/cs/type-system.texy +++ b/latte/cs/type-system.texy @@ -71,3 +71,6 @@ Třídu si také můžete nechat vygenerovat pomocí značky `{templatePrint}`. Značka `{varPrint}` vám ušetří čas při psaní. Pokud ji umístíte do šablony, místo běžného vykreslení se zobrazí návrh značek `{varType}` pro lokální proměnné. Kód pak stačí jedním kliknutím označit a zkopírovat do šablony. Samotné `{varPrint}` vypisuje pouze lokální proměnné, které nejsou parametry šablony. Pokud chcete vypsat všechny proměnné, použijte `{varPrint all}`. + +{{maintitle: Typový systém v Latte: typy proměnných a napovídání v IDE}} +{{description: Deklarujte typy proměnných v šablonách Latte, aby je IDE umělo napovídat a statická analýza odhalila chyby. Samotné Latte je zatím nekontroluje.}} diff --git a/latte/cs/why-use.texy b/latte/cs/why-use.texy index 8cf076d48f..1c1aeebf60 100644 --- a/latte/cs/why-use.texy +++ b/latte/cs/why-use.texy @@ -78,3 +78,6 @@ Ovlivňuje Latte výkon webových aplikací? Ačkoliv jsou šablony Latte zpracovávány rychle, v produkci na tomto aspektu vlastně nezáleží. Důvodem je, že parsování souborů proběhne pouze jednou při prvním zobrazení. Následně jsou zkompilovány do PHP kódu, uloženy na disk a spouštěny při každém dalším požadavku, aniž by bylo nutné provádět opětovnou kompilaci. Toto je způsob fungování v produkčním prostředí. Během vývoje se Latte šablony překompilují pokaždé, když dojde ke změně jejich obsahu, aby vývojář viděl vždy aktuální podobu. + +{{maintitle: Proč používat šablony v PHP: čisté PHP, Twig, nebo Latte}} +{{description: PHP je samo šablonovací jazyk, tak proč používat šablonovací systém? A co nabízí Latte oproti Twigu nebo Blade? Odpovědi na časté otázky o šablonách.}} diff --git a/latte/en/@home.texy b/latte/en/@home.texy index 61a7f57373..61ba76da84 100644 --- a/latte/en/@home.texy +++ b/latte/en/@home.texy @@ -1,3 +1,3 @@ -{{maintitle: Latte – The Safest & Truly Intuitive Templates for PHP}} -{{description: Latte is the most secure templating system for PHP. It prevents many security vulnerabilities. You will appreciate its intuitive syntax and enjoy many useful features.}} {{leftbar: no}} +{{maintitle: Latte – The Safest & Truly Intuitive Templates for PHP}} +{{description: Latte is the most secure templating system for PHP. It prevents many security vulnerabilities, and you will appreciate its intuitive syntax and useful features.}} diff --git a/latte/en/compiler-passes.texy b/latte/en/compiler-passes.texy index 2475d83fd6..583a07c4e1 100644 --- a/latte/en/compiler-passes.texy +++ b/latte/en/compiler-passes.texy @@ -576,3 +576,6 @@ When writing compiler passes, keep these guidelines in mind to create robust, ma - **Idempotency (If Possible):** Ideally, running your pass multiple times on the same AST should produce the same result as running it once. This isn't always feasible, but it simplifies debugging and reasoning about pass interactions if achieved. For example, ensure your modification pass checks if the modification has already been applied before applying it again. By adhering to these practices, you can effectively leverage compiler passes to extend Latte's capabilities in powerful and reliable ways, contributing to safer, more optimized, or feature-rich template processing. + +{{maintitle: Latte Compiler Passes: Analyze and Modify Templates}} +{{description: Analyze and modify Latte templates between parsing and PHP code generation: traverse the AST with NodeTraverser for optimizations or security checks.}} diff --git a/latte/en/cookbook/@home.texy b/latte/en/cookbook/@home.texy index 497f8f5615..b09c79c601 100644 --- a/latte/en/cookbook/@home.texy +++ b/latte/en/cookbook/@home.texy @@ -14,3 +14,6 @@ Example codes and recipes for accomplishing common tasks with Latte. - [Migration from Twig |migration-from-twig] - [Using Latte with Slim 4 |slim-framework] - [Using Latte with CakePHP |https://github.com/josbeir/cakephp-latte-view] + +{{maintitle: Latte Cookbook: Recipes for PHP Templates}} +{{description: Practical recipes for common tasks in Latte: grouping data, passing variables between templates, migrating from Twig or PHP and using Latte with Slim.}} diff --git a/latte/en/cookbook/grouping.texy b/latte/en/cookbook/grouping.texy index 994d03af49..18b2b5680e 100644 --- a/latte/en/cookbook/grouping.texy +++ b/latte/en/cookbook/grouping.texy @@ -251,3 +251,6 @@ Let's assume the table has another column `subcategoryId`, and besides each cate {/foreach} ``` + +{{maintitle: Grouping Data in Latte: group, batch and iterateWhile}} +{{description: Group items, split them into batches or iterate by a condition in Latte templates. When to use the group filter, the batch filter or the iterateWhile tag.}} diff --git a/latte/en/cookbook/how-to-write-sql-queries-in-latte.texy b/latte/en/cookbook/how-to-write-sql-queries-in-latte.texy index 911817b477..5a8b9ce219 100644 --- a/latte/en/cookbook/how-to-write-sql-queries-in-latte.texy +++ b/latte/en/cookbook/how-to-write-sql-queries-in-latte.texy @@ -38,3 +38,6 @@ $result = $db->query($sql); ``` *This example requires Latte v3.0.5 or higher.* + +{{maintitle: How to Write SQL Queries in Latte Templates}} +{{description: An SQL query with many conditions and variables quickly gets hard to read. Writing it as a Latte template keeps even really complex queries clear.}} diff --git a/latte/en/cookbook/migration-from-latte-30.texy b/latte/en/cookbook/migration-from-latte-30.texy index e5a9d6ccd0..0206122dd9 100644 --- a/latte/en/cookbook/migration-from-latte-30.texy +++ b/latte/en/cookbook/migration-from-latte-30.texy @@ -108,3 +108,6 @@ While migrating, you can start enjoying the new features: - **`n:elseif`:** You can now use `n:elseif` alongside `n:if` and `n:else`. - **Simplified syntax:** Write `
` without quotes. - **Toggle filter:** Use `|toggle` for manual control over boolean attributes. + +{{maintitle: Migrating from Latte 3.0 to 3.1: What Changes}} +{{description: Latte 3.1 makes templates safer and easier to write. What to watch for when upgrading: smart attributes, strict types, global constants and removed features.}} diff --git a/latte/en/cookbook/migration-from-latte2.texy b/latte/en/cookbook/migration-from-latte2.texy index 13e96d763f..778aeaedf7 100644 --- a/latte/en/cookbook/migration-from-latte2.texy +++ b/latte/en/cookbook/migration-from-latte2.texy @@ -302,3 +302,5 @@ class FooNode extends Latte\Compiler\Nodes\StatementNode ``` {{priority: -1}} +{{maintitle: Migrating from Latte 2 to Latte 3: Syntax and API Changes}} +{{description: Latte 3 has a rewritten compiler and a precisely defined grammar. See what changed in the syntax and API and how to update templates, add-ons and configuration.}} diff --git a/latte/en/cookbook/migration-from-php.texy b/latte/en/cookbook/migration-from-php.texy index 9dc5a5ff6a..4bfb75efe4 100644 --- a/latte/en/cookbook/migration-from-php.texy +++ b/latte/en/cookbook/migration-from-php.texy @@ -68,3 +68,6 @@ It generates this template:
``` + +{{maintitle: Convert PHP Templates to Latte: Online Migration Tool}} +{{description: Moving an old project from plain PHP to Latte? The converter uses a real PHP parser, so it handles even complex code. Try it online or run it locally.}} diff --git a/latte/en/cookbook/migration-from-twig.texy b/latte/en/cookbook/migration-from-twig.texy index 1af57367c1..3933dfccfb 100644 --- a/latte/en/cookbook/migration-from-twig.texy +++ b/latte/en/cookbook/migration-from-twig.texy @@ -77,3 +77,6 @@ After converting to Latte, we get this template: ``` + +{{maintitle: Migrate from Twig to Latte: Online Conversion Tool}} +{{description: Moving a project from Twig to Latte? The converter uses the real Twig parser, so it copes with complex templates. Try it online or run it on your own machine.}} diff --git a/latte/en/cookbook/passing-variables.texy b/latte/en/cookbook/passing-variables.texy index dc81ffccf1..d6722af606 100644 --- a/latte/en/cookbook/passing-variables.texy +++ b/latte/en/cookbook/passing-variables.texy @@ -156,3 +156,6 @@ The `{sandbox}` tag isolates the template for safe processing. Variables are pas ```latte {sandbox 'secure.latte', data: $secureData} ``` + +{{maintitle: Passing Variables Between Latte Templates}} +{{description: Which variables reach an included template, block, layout or embed in Latte? An overview of how variables pass between templates, tag by tag.}} diff --git a/latte/en/cookbook/slim-framework.texy b/latte/en/cookbook/slim-framework.texy index 2d202aea27..85ea106f50 100644 --- a/latte/en/cookbook/slim-framework.texy +++ b/latte/en/cookbook/slim-framework.texy @@ -155,3 +155,5 @@ Three ``` {{priority: -1}} +{{maintitle: Using Latte Templates with the Slim 4 Framework}} +{{description: How to add the Latte template engine to a Slim 4 application: configuring it in the DI container and rendering templates from your actions.}} diff --git a/latte/en/custom-filters.texy b/latte/en/custom-filters.texy index 3b8cb04f98..3533ffb036 100644 --- a/latte/en/custom-filters.texy +++ b/latte/en/custom-filters.texy @@ -205,3 +205,6 @@ Filters applied to [blocks |tags#block] with a content type other than text (typ ``` Contextual filters provide powerful control over how data is processed based on its context, enabling advanced features and ensuring correct escaping behavior, especially when generating HTML content. + +{{maintitle: Custom Latte Filters: Create and Register Your Own}} +{{description: Write your own filters to format and modify data right in Latte templates: creating and registering them, passing arguments and writing contextual filters.}} diff --git a/latte/en/custom-functions.texy b/latte/en/custom-functions.texy index 92acc47e5b..efa74e9c28 100644 --- a/latte/en/custom-functions.texy +++ b/latte/en/custom-functions.texy @@ -142,3 +142,6 @@ Latte automatically discovers and registers methods marked with this attribute w **Contextual Functions?** Unlike filters, functions don't receive a `FilterInfo` object. However, a function can gain access to the template context: if its first parameter is type-hinted as `Latte\Runtime\Template`, Latte automatically passes the current template object to it. This is exactly how the built-in `hasBlock()` and `hasTemplate()` functions are implemented. + +{{maintitle: Custom Latte Functions: Add PHP Helpers to Templates}} +{{description: Add your own helper functions to Latte templates and call PHP logic directly in expressions for calculations, access to services or dynamic content.}} diff --git a/latte/en/custom-tags.texy b/latte/en/custom-tags.texy index dba90cf2c8..90eac8bea1 100644 --- a/latte/en/custom-tags.texy +++ b/latte/en/custom-tags.texy @@ -1147,3 +1147,6 @@ By following these guidelines, you can create powerful, robust, and maintainable .[note] Studying the node classes that are part of Latte is the best way to learn all the nitty-gritty details of the parsing process. + +{{maintitle: Custom Latte Tags: Complete Guide to Writing Your Own}} +{{description: Create your own Latte tags, from simple ones to paired tags with nested content: how templates compile, how to parse arguments and how to generate PHP code.}} diff --git a/latte/en/develop.texy b/latte/en/develop.texy index d8c433a995..a3fa11a856 100644 --- a/latte/en/develop.texy +++ b/latte/en/develop.texy @@ -454,3 +454,6 @@ $latte->addProvider('coreParentFinder', $finder); ``` If the template should not have a layout, it will indicate this with the `{layout none}` tag. + +{{maintitle: Using Latte in PHP: Install, Render and Configure}} +{{description: Install Latte with Composer, render a template from PHP and configure it: caching, strict mode, locale, translations, the linter and debugging with Tracy.}} diff --git a/latte/en/extending-latte.texy b/latte/en/extending-latte.texy index 27bb6cd8f0..4de403110b 100644 --- a/latte/en/extending-latte.texy +++ b/latte/en/extending-latte.texy @@ -223,3 +223,6 @@ getCacheKey(Latte\Engine $engine): mixed .[method] -------------------------------------------------- It is called before the template is rendered. The return value becomes part of the key whose hash is contained in the name of the compiled template file. Thus, for different return values, Latte will generate different cache files. + +{{maintitle: Extending Latte: Custom Tags, Filters and Extensions}} +{{description: Need more than the built-in tags and filters? See all the ways to extend Latte, from registering a simple filter to writing a complete Latte Extension.}} diff --git a/latte/en/filters.texy b/latte/en/filters.texy index dd53ec6448..be363f0a3d 100644 --- a/latte/en/filters.texy +++ b/latte/en/filters.texy @@ -1014,3 +1014,6 @@ Converts to ASCII. Converts spaces to hyphens. Removes characters that are not a .[caution] Requires the [nette/utils|utils:] library. + +{{maintitle: Latte Filters: Format Output in PHP Templates}} +{{description: All built-in Latte filters with examples: format dates and numbers, modify and truncate strings, sort and group arrays, and much more.}} diff --git a/latte/en/functions.texy b/latte/en/functions.texy index e3cb56df77..80761e2a0c 100644 --- a/latte/en/functions.texy +++ b/latte/en/functions.texy @@ -164,3 +164,6 @@ If `start` is non-negative, the sequence will start at that offset from the begi If `length` is given and is positive, then the sequence will have up to that many elements. If the input is shorter than the `length`, then only the available elements will be present. If `length` is given and is negative, the sequence will stop that many elements from the end of the input. If it is omitted, the sequence will have everything from `start` up until the end of the input. By default, the function reorders and resets the integer array keys. This behavior can be changed by setting `preserveKeys` to true. String keys are always preserved, regardless of this parameter. + +{{maintitle: Latte Functions: clamp, first, group, slice and More}} +{{description: Besides ordinary PHP functions, Latte templates offer a few of their own: clamp, divisibleBy, even, odd, first, last, group, slice, hasBlock and hasTemplate.}} diff --git a/latte/en/guide.texy b/latte/en/guide.texy index 3353dbb1dc..a3f44e77c7 100644 --- a/latte/en/guide.texy +++ b/latte/en/guide.texy @@ -42,5 +42,5 @@ Latte comes fully equipped, with everything important included in the base. - -{{description: Latte is the safest templating system for PHP. It prevents numerous security vulnerabilities. You'll appreciate its intuitive syntax and enjoy many useful features.}} +{{maintitle: Getting Started with Latte: PHP Template Engine}} +{{description: Start with Latte in a few minutes: learn the syntax, tags and filters, install it in your PHP application and discover layouts, the sandbox and more.}} diff --git a/latte/en/html-attributes.texy b/latte/en/html-attributes.texy index ff127298ef..985193e897 100644 --- a/latte/en/html-attributes.texy +++ b/latte/en/html-attributes.texy @@ -177,3 +177,6 @@ Since the behavior of `null` (it used to print `""`, now it drops the attribute) For a smooth transition, Latte provides a migration mode that highlights differences. Read the detailed guide [Migration from Latte 3.0 to 3.1|cookbook/migration-from-latte-30]. [* html-attributes.webp *] + +{{maintitle: Smart HTML Attributes in Latte: Classes, Styles, Booleans}} +{{description: Latte 3.1 makes printing HTML attributes easier and safer: boolean attributes, null values, class and style arrays, data and aria attributes and type checking.}} diff --git a/latte/en/loaders.texy b/latte/en/loaders.texy index a990296d8c..5c89324e36 100644 --- a/latte/en/loaders.texy +++ b/latte/en/loaders.texy @@ -196,3 +196,6 @@ $latte->render('homepage'); // Loads the template named 'homepage' from the DB ``` Custom loaders give you complete control over where your Latte templates come from, allowing integration with various storage systems and workflows. + +{{maintitle: Latte Loaders: Templates from Files, Strings or a Database}} +{{description: Load Latte templates from anywhere: files with FileLoader, strings with StringLoader, or a custom loader, shown on a simple database example.}} diff --git a/latte/en/recipes.texy b/latte/en/recipes.texy index e8ffd8be12..dc5150a15f 100644 --- a/latte/en/recipes.texy +++ b/latte/en/recipes.texy @@ -160,3 +160,6 @@ Included template `included.latte`: {* write data to the property foo *} {var $vars->foo = 123} ``` + +{{maintitle: Latte Tips and Tricks: IDE Plugins, JavaScript and XML}} +{{description: Latte plugins for PhpStorm and other editors, using Latte inside JavaScript and CSS, generating XML, replacing the use clause and passing data between templates.}} diff --git a/latte/en/safety-first.texy b/latte/en/safety-first.texy index b1d5c38742..62c6fb7291 100644 --- a/latte/en/safety-first.texy +++ b/latte/en/safety-first.texy @@ -408,3 +408,6 @@ Latte is not a complete XSS protection for the entire application. We would be u .[tip] Do you want to test your knowledge of escaping in individual contexts? Try the [XSS vulnerability quiz |https://blog.nette.org/en/quiz-can-you-defend-against-xss-vulnerability]. + +{{maintitle: PHP XSS Protection: Context-Aware Escaping in Latte}} +{{description: Why XSS is so dangerous and how Latte stops it: it knows where each value is printed and escapes it accordingly, which naive template systems cannot do.}} diff --git a/latte/en/sandbox.texy b/latte/en/sandbox.texy index 2c4f5e7d3b..bbcd581ce1 100644 --- a/latte/en/sandbox.texy +++ b/latte/en/sandbox.texy @@ -118,3 +118,6 @@ The purpose of `__toString()` is to produce a text representation of the object, Latte could catch these most direct cases, but not reliably in all of them. Converting an object to a string is not a method call but a built-in language operation that occurs in many places within an expression. In some of them (for example, comparing an object with a string, or inside a called function or filter) it could not be intercepted reliably without also blocking legitimate use. That is why you need to count on `__toString()` being reachable. **Do not expose objects whose `__toString()` has side effects or reveals sensitive data to the sandbox.** This applies not only to objects you pass to the template directly, but also to those the author obtains as the return value of an allowed function, method, or property. + +{{maintitle: Latte Sandbox: Run Untrusted PHP Templates Safely}} +{{description: Control which tags, filters, PHP functions and methods a template may use, so a client or an external coder can edit templates without putting your app at risk.}} diff --git a/latte/en/syntax.texy b/latte/en/syntax.texy index 9334edd13c..8494f3557a 100644 --- a/latte/en/syntax.texy +++ b/latte/en/syntax.texy @@ -343,3 +343,6 @@ PHP Limitations in Latte Only PHP expressions can be written in Latte. That is, statements ending with a semicolon cannot be used. You cannot declare classes or use [control structures |https://www.php.net/manual/en/language.control-structures.php], such as `if`, `foreach`, `switch`, `return`, `try`, `throw`, and others, for which Latte offers its [tags|tags]. You also cannot use [attributes |https://www.php.net/manual/en/language.attributes.php], [backticks |https://www.php.net/manual/en/language.operators.execution.php], or some [magic constants |https://www.php.net/manual/en/language.constants.magic.php]. You cannot use `unset`, `echo`, `include`, `require`, `exit`, `eval` either, because they are not functions but special PHP language constructs, and thus not expressions. Only multi-line comments `/* ... */` are supported. However, these limitations can be bypassed by activating the [RawPhpExtension |develop#RawPhpExtension] extension, which allows you to use any PHP code within the `{php ...}` tag at the template author's responsibility. + +{{maintitle: Latte Syntax: Tags, n:attributes, Filters and Comments}} +{{description: Latte syntax is close to PHP and easy to learn: tags, n:attributes written right in the HTML, filters, dynamic HTML tags, comments and whitespace control.}} diff --git a/latte/en/tags.texy b/latte/en/tags.texy index 160e79dd19..87d2402ce0 100644 --- a/latte/en/tags.texy +++ b/latte/en/tags.texy @@ -1092,3 +1092,6 @@ The tag can also be written as an [n:attribute |syntax#n:attributes], to transla ```latte

Order

``` + +{{maintitle: Latte Tags: foreach, if, include, block and More}} +{{description: Every tag available in Latte templates, with examples: printing, conditions, foreach loops, including templates, blocks, exceptions, variables and translation.}} diff --git a/latte/en/template-inheritance.texy b/latte/en/template-inheritance.texy index 7f7af3c27b..a54b1ed6bb 100644 --- a/latte/en/template-inheritance.texy +++ b/latte/en/template-inheritance.texy @@ -758,3 +758,6 @@ There are various types of inheritance and code reuse in Latte. Let's summarize {block last}Last Service Page{/block} {/embed} ``` + +{{maintitle: PHP Template Inheritance in Latte: Layout, Block and Embed}} +{{description: Stop repeating HTML in your templates. Layout inheritance, blocks, horizontal reuse and embed let each Latte template hold only its own unique content.}} diff --git a/latte/en/type-system.texy b/latte/en/type-system.texy index eee9ea0b51..dc1fd73774 100644 --- a/latte/en/type-system.texy +++ b/latte/en/type-system.texy @@ -71,3 +71,6 @@ You can also have the class generated using the `{templatePrint}` tag. If you pl The `{varPrint}` tag saves you writing time. If you place it in a template, instead of the normal rendering, a suggestion for `{varType}` tags for local variables will be displayed. Then simply select the code with one click and copy it into your template. `{varPrint}` itself only lists local variables that are not template parameters. If you want to list all variables, use `{varPrint all}`. + +{{maintitle: Latte Type System: Variable Types and IDE Autocomplete}} +{{description: Declare variable types in Latte templates so that your IDE can autocomplete them and static analysis can find errors. Latte itself does not check them yet.}} diff --git a/latte/en/why-use.texy b/latte/en/why-use.texy index 5f8e33befd..28fcbbb55e 100644 --- a/latte/en/why-use.texy +++ b/latte/en/why-use.texy @@ -78,3 +78,6 @@ Does Latte affect the performance of web applications? Although Latte templates are processed quickly, this aspect doesn't really matter in production. The reason is that template files are parsed only once upon their first display. They are then compiled into native PHP code, stored on disk, and executed on every subsequent request without requiring recompilation. This is how it works in a production environment. During development, Latte templates are recompiled every time their content changes, so the developer always sees the current version. + +{{maintitle: Why Use a PHP Template Engine: Plain PHP, Twig or Latte}} +{{description: PHP is itself a templating language, so why use a template system? And what does Latte offer over Twig or Blade? Answers to common questions about templates.}} diff --git a/mail/cs/@home.texy b/mail/cs/@home.texy index 0f54ae1e3f..80082566a2 100644 --- a/mail/cs/@home.texy +++ b/mail/cs/@home.texy @@ -523,3 +523,6 @@ Tyto služby se přidávají do DI kontejneru: Pokud aktualizujete balíček na novější verzi, podívejte se na stránku [upgrade|upgrading]. + +{{maintitle: Odesílání e-mailů v PHP s Nette Mail: SMTP, DKIM a šablony}} +{{description: Posílejte z PHP newslettery nebo potvrzení objednávek: e-maily s přílohami, šablony Latte, odesílání přes SMTP a podpis DKIM.}} diff --git a/mail/cs/upgrading.texy b/mail/cs/upgrading.texy index 83e102ba3f..4f5d9b109a 100644 --- a/mail/cs/upgrading.texy +++ b/mail/cs/upgrading.texy @@ -8,3 +8,6 @@ Upgrade na verzi 2.3 - pokud v šabloně používáte proměnnou `$mail`, musíte ji do šablony předat ručně - pokud máte v šabloně linkované obrázky s relativními cestami, předejte základní cestu k souborům jako druhý parametr metody `setHtmlBody()` - šablony není potřeba přetypovávat na `(string)` + +{{maintitle: Upgrade Nette Mail: co se změnilo ve verzi 2.3}} +{{description: Co se změnilo v Nette Mail 2.3: předávání proměnné $mail do šablon a základní cesta k odkazovaným obrázkům v setHtmlBody().}} diff --git a/mail/en/@home.texy b/mail/en/@home.texy index e53f387e97..38148acfa0 100644 --- a/mail/en/@home.texy +++ b/mail/en/@home.texy @@ -523,3 +523,6 @@ These services are added to the DI container: If you are upgrading to a newer version, see the [upgrading] page. + +{{maintitle: Sending Email in PHP with Nette Mail: SMTP, DKIM, Templates}} +{{description: Send newsletters or order confirmations from PHP: create emails with attachments, combine them with Latte templates, send over SMTP and sign with DKIM.}} diff --git a/mail/en/upgrading.texy b/mail/en/upgrading.texy index c78ffaa289..d93450bc46 100644 --- a/mail/en/upgrading.texy +++ b/mail/en/upgrading.texy @@ -8,3 +8,6 @@ Upgrading to Version 2.3 - if you use the `$mail` variable in a template, you must pass it to the template manually - if you have linked images with relative paths in a template, pass the base file path as the second parameter of `setHtmlBody()` - there is no need to cast templates to `(string)` + +{{maintitle: Upgrading Nette Mail: What Changed in Version 2.3}} +{{description: What changed in Nette Mail 2.3: passing the $mail variable to templates and the base path for linked images in setHtmlBody().}} diff --git a/migrations/cs/@home.texy b/migrations/cs/@home.texy index 94c2adb9a9..2ff4d382d6 100644 --- a/migrations/cs/@home.texy +++ b/migrations/cs/@home.texy @@ -36,3 +36,6 @@ Upgrade jednotlivých balíčků - [Security |security:upgrading] - [Tracy |tracy:upgrading] - [Utils |utils:upgrading] + +{{maintitle: Upgrade Nette: průvodce upgradem všech balíčků}} +{{description: Nette je rozdělené do samostatných balíčků s vlastní historií verzí. Pokyny pro upgrade balíčků, které používáte, na jednom místě.}} diff --git a/migrations/en/@home.texy b/migrations/en/@home.texy index 4e054329c3..5ea77d4bfc 100644 --- a/migrations/en/@home.texy +++ b/migrations/en/@home.texy @@ -36,3 +36,6 @@ Package Upgrade Guides - [Security |security:upgrading] - [Tracy |tracy:upgrading] - [Utils |utils:upgrading] + +{{maintitle: Upgrading Nette: Upgrade Guide for All Packages}} +{{description: Nette is split into independent packages, each with its own version history. Upgrade notes for the packages you use, all linked from one place.}} diff --git a/neon/cs/@home.texy b/neon/cs/@home.texy index b3997b21a2..286f07efef 100644 --- a/neon/cs/@home.texy +++ b/neon/cs/@home.texy @@ -88,3 +88,6 @@ Metoda `decodeFile()` při chybě vyhodí `Nette\Neon\Exception`. Pokud aktualizujete balíček na novější verzi, podívejte se na stránku [upgrade|upgrading]. + +{{maintitle: Nette NEON: čtení a zápis souborů NEON v PHP}} +{{description: NEON je lidsky srozumitelný jazyk pro serializaci dat, který Nette používá v konfiguračních souborech. Statická třída Neon ho v PHP kóduje a dekóduje.}} diff --git a/neon/cs/format.texy b/neon/cs/format.texy index 553c50c96e..dee3046bd5 100644 --- a/neon/cs/format.texy +++ b/neon/cs/format.texy @@ -456,5 +456,5 @@ users: Hurá, teď znáte syntaxi NEONu! - -{{description: NEON je snadno čitelný formát pro serializaci dat. Je podobný YAMLu. Hlavní rozdíl je v tom, že NEON podporuje „entity“ a k odsazování můžeme použít jak mezery, tak tabulátory.}} +{{maintitle: Formát NEON: lidsky čitelná alternativa k YAML a JSON}} +{{description: NEON je snadno čitelný formát pro serializaci dat, podobný YAMLu. Hlavní rozdíl je v tom, že podporuje entity a k odsazování můžete použít i tabulátory.}} diff --git a/neon/cs/upgrading.texy b/neon/cs/upgrading.texy index f036d10afc..4fc1fe80d2 100644 --- a/neon/cs/upgrading.texy +++ b/neon/cs/upgrading.texy @@ -14,3 +14,6 @@ Upgrade na verzi 3.2 - Decoder pracuje v režimu UTF-8, při neplatném vstupu vyhodí výjimku - escape sekvence `\xAA` je zastaralá ve prospěch `\uAAAA` + +{{maintitle: Upgrade Nette NEON: změny v jednotlivých verzích}} +{{description: Co se změnilo v Nette NEON 3.4 a 3.2 a jak upravit kód při přechodu na novější verzi.}} diff --git a/neon/en/@home.texy b/neon/en/@home.texy index bf821ca235..be3ec3fecd 100644 --- a/neon/en/@home.texy +++ b/neon/en/@home.texy @@ -88,3 +88,6 @@ The `decodeFile()` method throws `Nette\Neon\Exception` on error. If you are upgrading to a newer version, see the [upgrading] page. + +{{maintitle: Nette NEON: Parse and Generate NEON Files in PHP}} +{{description: NEON is a human-friendly data serialization language used in Nette configuration files. The static Neon class encodes and decodes it in PHP.}} diff --git a/neon/en/format.texy b/neon/en/format.texy index 313b25c426..775854ee86 100644 --- a/neon/en/format.texy +++ b/neon/en/format.texy @@ -456,5 +456,5 @@ users: Hooray, now you know the NEON syntax! - -{{description: NEON is a human-friendly data serialization language. It is similar to YAML. The main difference is that NEON supports "entities" and allows tab characters for indentation.}} +{{maintitle: NEON Format: Human-Friendly Alternative to YAML and JSON}} +{{description: NEON is a human-friendly data serialization language similar to YAML. The main difference is that NEON supports entities and allows tabs for indentation.}} diff --git a/neon/en/upgrading.texy b/neon/en/upgrading.texy index 5acf2586b4..6492ea7b48 100644 --- a/neon/en/upgrading.texy +++ b/neon/en/upgrading.texy @@ -14,3 +14,6 @@ Upgrading to Version 3.2 - the Decoder works in UTF-8 mode and throws an exception on invalid input - the `\xAA` escape sequence is deprecated in favor of `\uAAAA` + +{{maintitle: Upgrading Nette NEON: What Changed in Each Version}} +{{description: What changed in Nette NEON 3.4 and 3.2, and how to update your code when moving to a newer version.}} diff --git a/nette/cs/@home.texy b/nette/cs/@home.texy index ac21ed0528..bcea128f79 100644 --- a/nette/cs/@home.texy +++ b/nette/cs/@home.texy @@ -106,6 +106,6 @@ Utilities {{toc:no}} -{{description: Oficiální dokumentace Nette: popisuje, jak Nette funguje a osvědčené postupy pro vývoj webových aplikací.}} -{{maintitle: Dokumentace Nette}} {{leftbar: no}} +{{maintitle: Dokumentace Nette}} +{{description: Oficiální dokumentace Nette: popisuje, jak Nette funguje a osvědčené postupy pro vývoj webových aplikací.}} diff --git a/nette/cs/configuring.texy b/nette/cs/configuring.texy index a67006f215..1f23c2844a 100644 --- a/nette/cs/configuring.texy +++ b/nette/cs/configuring.texy @@ -32,4 +32,5 @@ Součásti Nette nastavujeme pomocí konfiguračních souborů, které se obvykl .[note] Chcete-li zapsat řetězec obsahující znak `%`, musíte jej escapovat zdvojením na `%%`. - +{{maintitle: Konfigurace Nette: přehled všech voleb v NEON}} +{{description: Přehled všech konfiguračních voleb v Nette Frameworku s odkazy na podrobnosti: aplikace, databáze, formuláře, HTTP, Latte, mail, session a další.}} diff --git a/nette/cs/glossary.texy b/nette/cs/glossary.texy index d60cc9f782..55b52b392d 100644 --- a/nette/cs/glossary.texy +++ b/nette/cs/glossary.texy @@ -165,3 +165,5 @@ View, tedy pohled, je vrstva aplikace, která má na starost zobrazení výsledk {{priority: -2}} +{{maintitle: Slovníček pojmů Nette: termíny z vývoje webu vysvětlené}} +{{description: Co znamená AJAX, DI kontejner, presenter, snippet nebo XSS? Srozumitelné vysvětlení pojmů z vývoje webu, které používá dokumentace Nette.}} diff --git a/nette/cs/installation.texy b/nette/cs/installation.texy index 96daa2febe..f2fef85fc8 100644 --- a/nette/cs/installation.texy +++ b/nette/cs/installation.texy @@ -63,4 +63,5 @@ Pro efektivní práci s Nette doporučujeme následující nástroje: - Verzovací systém Git - [Composer|best-practices:composer] - +{{maintitle: Instalace Nette: nový projekt, nebo stávající aplikace}} +{{description: Nainstalujte Nette do stávajícího PHP projektu, nebo vytvořte nový z Web Projectu, krok za krokem s Composerem.}} diff --git a/nette/cs/introduction-to-object-oriented-programming.texy b/nette/cs/introduction-to-object-oriented-programming.texy index 42e8ed5ed4..9b16de395e 100644 --- a/nette/cs/introduction-to-object-oriented-programming.texy +++ b/nette/cs/introduction-to-object-oriented-programming.texy @@ -839,3 +839,6 @@ Když máte za sebou základní principy objektově orientovaného programován 1) **Oddělení zájmů (Separation of Concerns)**: Každá třída by měla mít jasně definovanou odpovědnost a měla by řešit pouze jeden hlavní úkol. Pokud třída dělá příliš mnoho věcí, může být vhodné ji rozdělit na menší, specializované třídy. 2) **Zapouzdření (Encapsulation)**: Data a metody by měly být co nejvíce skryté a přístupné pouze prostřednictvím definovaného rozhraní. To vám umožní měnit interní implementaci třídy bez ovlivnění zbytku kódu. 3) **Předávání závislostí (Dependency Injection)**: Místo toho, abyste vytvářeli závislosti přímo ve třídě, měli byste je "injektovat" zvenčí. Pro hlubší porozumění tomuto principu doporučujeme [kapitoly o Dependency Injection|dependency-injection:introduction]. + +{{maintitle: Úvod do OOP v PHP: objektově orientované programování}} +{{description: Průvodce objektově orientovaným programováním v PHP pro začátečníky: třídy, objekty, dědičnost, rozhraní, traity, jmenné prostory a výjimky na příkladech.}} diff --git a/nette/cs/troubleshooting.texy b/nette/cs/troubleshooting.texy index e2031b31e4..2af440d1ae 100644 --- a/nette/cs/troubleshooting.texy +++ b/nette/cs/troubleshooting.texy @@ -223,4 +223,5 @@ abstract class BasePresenter extends Nette\Application\UI\Presenter } ``` - +{{maintitle: Řešení problémů v Nette: chyba 500, 404 a další potíže}} +{{description: Nette nefunguje? Bílá stránka, chyba 500 a 404, neprojevené změny v šablonách, oprávnění adresářů nebo .htaccess: časté příčiny a jak je opravit.}} diff --git a/nette/cs/vulnerability-protection.texy b/nette/cs/vulnerability-protection.texy index ffa9bb2597..e5c203deee 100644 --- a/nette/cs/vulnerability-protection.texy +++ b/nette/cs/vulnerability-protection.texy @@ -87,3 +87,5 @@ Příznak SameSite může mít tři hodnoty: `Lax`, `Strict` a `None` (ten vyža Nette ve výchozím nastavení odesílá všechny cookie s příznakem `Lax`. +{{maintitle: Bezpečnost v PHP s Nette: XSS, CSRF a krádež session}} +{{description: Jak Nette chrání vaši webovou aplikaci před zranitelnostmi: Cross-Site Scripting, CSRF, útoky přes URL, neplatné UTF-8, únos session a SameSite cookies.}} diff --git a/nette/en/@home.texy b/nette/en/@home.texy index cd9b3f7dc9..447b679901 100644 --- a/nette/en/@home.texy +++ b/nette/en/@home.texy @@ -106,6 +106,6 @@ Utilities {{toc:no}} -{{description: Official Nette Documentation: describes how Nette works and the best practices for developing web applications.}} -{{maintitle: Nette Documentation}} {{leftbar: no}} +{{maintitle: Nette Documentation}} +{{description: Official Nette Documentation: describes how Nette works and the best practices for developing web applications.}} diff --git a/nette/en/configuring.texy b/nette/en/configuring.texy index f5891b4f26..9880f982e6 100644 --- a/nette/en/configuring.texy +++ b/nette/en/configuring.texy @@ -32,4 +32,5 @@ Nette components are configured using configuration files, which are usually wri .[note] To write a string containing the character `%`, you must escape it by doubling it to `%%`. - +{{maintitle: Nette Configuration: Overview of All NEON Options}} +{{description: An overview of all configuration options in the Nette Framework, with links to details on application, database, forms, HTTP, Latte, mail, session and more.}} diff --git a/nette/en/glossary.texy b/nette/en/glossary.texy index ba823ff047..a93ea9f32c 100644 --- a/nette/en/glossary.texy +++ b/nette/en/glossary.texy @@ -165,3 +165,5 @@ The view is the application layer responsible for displaying the result of a req {{priority: -2}} +{{maintitle: Nette Glossary: Web Development Terms Explained}} +{{description: What do AJAX, DI container, presenter, snippet or XSS mean? Clear explanations of the web development terms used in the Nette documentation.}} diff --git a/nette/en/installation.texy b/nette/en/installation.texy index fa9744568b..65436aa291 100644 --- a/nette/en/installation.texy +++ b/nette/en/installation.texy @@ -63,4 +63,5 @@ For efficient work with Nette, we recommend the following tools: - Version control system Git - [Composer|best-practices:composer] - +{{maintitle: Installing Nette: New Project or Existing PHP Application}} +{{description: Install Nette into an existing PHP project or create a new one from the Web Project, step by step with Composer.}} diff --git a/nette/en/introduction-to-object-oriented-programming.texy b/nette/en/introduction-to-object-oriented-programming.texy index 99cb18e762..cb84f02cf9 100644 --- a/nette/en/introduction-to-object-oriented-programming.texy +++ b/nette/en/introduction-to-object-oriented-programming.texy @@ -839,3 +839,6 @@ Once you have the basic principles of object-oriented programming under your bel 1) **Separation of Concerns**: Each class should have a clearly defined responsibility and should address only one primary task. If a class does too many things, it might be appropriate to split it into smaller, specialized classes. 2) **Encapsulation**: Data and methods should be as hidden as possible and accessible only through a defined interface. This allows you to change the internal implementation of a class without affecting the rest of the code. 3) **Dependency Injection**: Instead of creating dependencies directly within a class, you should "inject" them from the outside. For a deeper understanding of this principle, we recommend the [chapters on Dependency Injection|dependency-injection:introduction]. + +{{maintitle: Introduction to OOP in PHP: Object-Oriented Programming}} +{{description: A beginner's guide to object-oriented programming in PHP: classes, objects, inheritance, interfaces, traits, namespaces and exceptions, explained with examples.}} diff --git a/nette/en/troubleshooting.texy b/nette/en/troubleshooting.texy index 80031d8b4b..cf0c192ea8 100644 --- a/nette/en/troubleshooting.texy +++ b/nette/en/troubleshooting.texy @@ -223,4 +223,5 @@ abstract class BasePresenter extends Nette\Application\UI\Presenter } ``` - +{{maintitle: Nette Troubleshooting: Error 500, 404 and Common Problems}} +{{description: Nette is not working? White page, error 500 or 404, templates not refreshing, directory permissions or .htaccess: common causes and how to fix them.}} diff --git a/nette/en/vulnerability-protection.texy b/nette/en/vulnerability-protection.texy index cdd48e0658..3c37b0fb21 100644 --- a/nette/en/vulnerability-protection.texy +++ b/nette/en/vulnerability-protection.texy @@ -87,3 +87,5 @@ The SameSite flag can have three values: `Lax`, `Strict`, and `None` (the latter Nette defaults to sending all cookies with the `Lax` flag. +{{maintitle: PHP Security in Nette: XSS, CSRF and Session Hijacking}} +{{description: How Nette protects your web application from vulnerabilities: Cross-Site Scripting, CSRF, URL attacks, invalid UTF-8, session hijacking and SameSite cookies.}} diff --git a/php-generator/cs/@home.texy b/php-generator/cs/@home.texy index 7b8da68071..968665ccd1 100644 --- a/php-generator/cs/@home.texy +++ b/php-generator/cs/@home.texy @@ -998,3 +998,6 @@ PhpGenerator 4.2 je kompatibilní s PHP 8.1 až 8.5. Pokud aktualizujete balíček na novější verzi, podívejte se na stránku [upgrade|upgrading]. + +{{maintitle: Nette PhpGenerator: generování PHP tříd a kódu}} +{{description: Generujte PHP kód tříd, funkcí i celých souborů se všemi novinkami PHP, jako jsou property hooks, enumy a atributy. Umí také upravovat existující třídy.}} diff --git a/php-generator/cs/upgrading.texy b/php-generator/cs/upgrading.texy index 5221d70235..6d747914b7 100644 --- a/php-generator/cs/upgrading.texy +++ b/php-generator/cs/upgrading.texy @@ -6,3 +6,6 @@ Upgrade na verzi 2.4 ==================== - metody `setDocuments()`, `getDocuments()` a `addDocument()` nahradily metody `setComment()`, `getComment()` a `addComment()` + +{{maintitle: Upgrade Nette PhpGenerator: co se změnilo ve verzi 2.4}} +{{description: Co se změnilo v Nette PhpGenerator 2.4: metody pro práci s dokumenty nahradily setComment(), getComment() a addComment().}} diff --git a/php-generator/en/@home.texy b/php-generator/en/@home.texy index 64f7e91452..1aa67bb5da 100644 --- a/php-generator/en/@home.texy +++ b/php-generator/en/@home.texy @@ -998,3 +998,6 @@ PhpGenerator 4.2 is compatible with PHP 8.1 to 8.5. If you are upgrading to a newer version, see the [upgrading] page. + +{{maintitle: Nette PhpGenerator: Generate PHP Classes and Code}} +{{description: Generate PHP code for classes, functions or whole files with the latest PHP features such as property hooks, enums and attributes, or modify existing classes.}} diff --git a/php-generator/en/upgrading.texy b/php-generator/en/upgrading.texy index 06a66ff57c..cf5fd3748a 100644 --- a/php-generator/en/upgrading.texy +++ b/php-generator/en/upgrading.texy @@ -6,3 +6,6 @@ Upgrading to Version 2.4 ======================== - the methods `setDocuments()`, `getDocuments()`, and `addDocument()` were replaced by `setComment()`, `getComment()`, and `addComment()` + +{{maintitle: Upgrading Nette PhpGenerator: What Changed in Version 2.4}} +{{description: What changed in Nette PhpGenerator 2.4: methods for working with documents were replaced by setComment(), getComment() and addComment().}} diff --git a/quickstart/cs/@home.texy b/quickstart/cs/@home.texy index 891f283cc5..e93dfc9fa0 100644 --- a/quickstart/cs/@home.texy +++ b/quickstart/cs/@home.texy @@ -116,3 +116,5 @@ composer thanks Zkuste si to! {{priority: -1}} +{{maintitle: Nette Framework tutoriál: první aplikace v PHP}} +{{description: Poznejte Nette Framework při tvorbě jednoduchého blogu s komentáři, krok za krokem. Nainstalujete Web Project, spustíte aplikaci a seznámíte se s Tracy.}} diff --git a/quickstart/cs/authentication.texy b/quickstart/cs/authentication.texy index 8b85282ef4..5a91b2bfb1 100644 --- a/quickstart/cs/authentication.texy +++ b/quickstart/cs/authentication.texy @@ -177,3 +177,5 @@ Máme odkaz pro přihlášení a také odhlášení uživatele. K ověření jsm Zde si můžete přečíst více o [přihlašování uživatelů |security:authentication] a [Ověřování oprávnění |security:authorization]. {{priority: -1}} +{{maintitle: Nette tutoriál: přihlášení uživatele a zabezpečení presenterů}} +{{description: Část tutoriálu Nette: přidáte přihlašovací formulář, zabezpečíte presentery, aby příspěvky psali jen přihlášení uživatelé, a doplníte odkaz na přihlášení.}} diff --git a/quickstart/cs/comments.texy b/quickstart/cs/comments.texy index 9d453723dc..3a7558b307 100644 --- a/quickstart/cs/comments.texy +++ b/quickstart/cs/comments.texy @@ -169,3 +169,5 @@ Všimněte si speciálního atributu `n:tag-if`. Již víte, jak `n:atributy` fu ``` {{priority: -1}} +{{maintitle: Nette tutoriál: komentáře u blogu a formulář}} +{{description: Část tutoriálu Nette: vytvoříte tabulku komentářů a formulář, uložíte odeslaná data do databáze a vykreslíte komentáře pod každým příspěvkem.}} diff --git a/quickstart/cs/creating-posts.texy b/quickstart/cs/creating-posts.texy index 27db1bdbdc..bc2cf6f126 100644 --- a/quickstart/cs/creating-posts.texy +++ b/quickstart/cs/creating-posts.texy @@ -185,3 +185,5 @@ Shrnutí Blog je nyní funkční, návštěvníci jej aktivně komentují a my již nepotřebujeme na publikaci Adminer. Aplikace je plně nezávislá a kdokoliv může přidat nový příspěvek. Tak moment, to asi není úplně v pořádku, že kdokoliv - a tím myslím opravdu kdokoliv s přístupem na internet - může přidávat nové příspěvky. Je zapotřebí nějaké zabezpečení, aby mohl nový příspěvek přidat pouze přihlášený uživatel. Na to se podíváme v příští kapitole. {{priority: -1}} +{{maintitle: Nette tutoriál: vytváření a editace příspěvků}} +{{description: Část tutoriálu Nette: nový presenter s formulářem pro ukládání příspěvků, stránka pro jejich vytváření, odkazy na ni a úprava existujících příspěvků.}} diff --git a/quickstart/cs/home-page.texy b/quickstart/cs/home-page.texy index 36b7c5dfc3..d6f3d06d82 100644 --- a/quickstart/cs/home-page.texy +++ b/quickstart/cs/home-page.texy @@ -199,3 +199,5 @@ Shrnutí Nyní máme velmi jednoduchou MySQL databázi s pár příspěvky. Aplikace se připojuje k této databázi a vypisuje jednoduchý seznam těchto příspěvků do šablony. {{priority: -1}} +{{maintitle: Nette tutoriál: úvodní stránka blogu, databáze a šablona}} +{{description: Část tutoriálu Nette: vytvoříte databázi v Admineru, připojíte se k ní, předáte spojení do presenteru a vypíšete poslední příspěvky blogu v šabloně Latte.}} diff --git a/quickstart/cs/model.texy b/quickstart/cs/model.texy index de9ad2d18f..a47d3d3616 100644 --- a/quickstart/cs/model.texy +++ b/quickstart/cs/model.texy @@ -82,3 +82,5 @@ Třída `PostFacade` si v konstruktoru řekne o předání `Nette\Database\Explo Zde si můžete přečíst více o [dependency injection |dependency-injection:introduction] a [konfiguraci |nette:configuring]. {{priority: -1}} +{{maintitle: Nette tutoriál: přesun práce s databází do modelu}} +{{description: Část tutoriálu Nette: přesunete dotazy do databáze z presenterů do modelové třídy PostFacade a předáte ji konstruktorem. Kód bude přehlednější.}} diff --git a/quickstart/cs/single-post.texy b/quickstart/cs/single-post.texy index 2e1d142334..32aac55f41 100644 --- a/quickstart/cs/single-post.texy +++ b/quickstart/cs/single-post.texy @@ -122,3 +122,5 @@ Shrnutí Máme databázi s příspěvky a webovou aplikaci, která má dva pohledy - první zobrazuje přehled všech příspěvků a druhý zobrazuje jeden konkrétní příspěvek. {{priority: -1}} +{{maintitle: Nette tutoriál: stránka s příspěvkem a kontrola ID}} +{{description: Část tutoriálu Nette: přidáte stránku s jedním příspěvkem blogu, odkaz na ni a chybu 404, když požadovaný příspěvek neexistuje.}} diff --git a/quickstart/en/@home.texy b/quickstart/en/@home.texy index 2953e23f82..4dfde257e4 100644 --- a/quickstart/en/@home.texy +++ b/quickstart/en/@home.texy @@ -116,3 +116,5 @@ composer thanks Try it! {{priority: -1}} +{{maintitle: Nette Framework Tutorial: Create Your First Application}} +{{description: Get to know the Nette Framework by building a simple blog with comments, step by step. Install the Web Project, start the app and meet the Tracy debugger.}} diff --git a/quickstart/en/authentication.texy b/quickstart/en/authentication.texy index 127d56c2d7..722defdf0f 100644 --- a/quickstart/en/authentication.texy +++ b/quickstart/en/authentication.texy @@ -177,3 +177,5 @@ We have links for signing in and signing out the user. We used the built-in auth You can read more about [user login |security:authentication] and [authorization |security:authorization] here. {{priority: -1}} +{{maintitle: Nette Tutorial: User Login and Securing Presenters}} +{{description: Part of the Nette tutorial: add a sign-in form, protect presenters so that only logged-in users can create and edit posts, and add a sign-in link.}} diff --git a/quickstart/en/comments.texy b/quickstart/en/comments.texy index 140f7dd8ba..ce2e17cdba 100644 --- a/quickstart/en/comments.texy +++ b/quickstart/en/comments.texy @@ -169,3 +169,5 @@ Notice the special `n:tag-if` attribute. You already know how `n:attributes` wor ``` {{priority: -1}} +{{maintitle: Nette Tutorial: Add Comments to a Blog with a Form}} +{{description: Part of the Nette tutorial: create a comments table, build a comment form, save submitted data to the database and render comments under each post.}} diff --git a/quickstart/en/creating-posts.texy b/quickstart/en/creating-posts.texy index 17f10793e1..fd4023c516 100644 --- a/quickstart/en/creating-posts.texy +++ b/quickstart/en/creating-posts.texy @@ -185,3 +185,5 @@ Summary The blog is working, people are commenting rapidly and we no longer rely on Adminer for adding new posts. It is fully independent and even normal people can post there. But wait, that's probably not ok, that anyone, I mean really anyone on the Internet, can post on our blog. Some form of authentication is required so that only logged-in users are able to post. We'll add that in the next chapter. {{priority: -1}} +{{maintitle: Nette Tutorial: Creating and Editing Blog Posts}} +{{description: Part of the Nette tutorial: add a new presenter with a form for saving posts, a page for creating them, links to it and editing of existing posts.}} diff --git a/quickstart/en/home-page.texy b/quickstart/en/home-page.texy index 4cb3063434..38d406b05e 100644 --- a/quickstart/en/home-page.texy +++ b/quickstart/en/home-page.texy @@ -199,3 +199,5 @@ Summary We now have a very simple MySQL database with a few posts. The application connects to this database and displays a simple list of these posts in a template. {{priority: -1}} +{{maintitle: Nette Tutorial: Blog Home Page with Database and Template}} +{{description: Part of the Nette tutorial: create a database with Adminer, connect to it, inject the connection into a presenter and list recent posts in a Latte template.}} diff --git a/quickstart/en/model.texy b/quickstart/en/model.texy index af925bfde2..afa355bb9c 100644 --- a/quickstart/en/model.texy +++ b/quickstart/en/model.texy @@ -82,3 +82,5 @@ The `PostFacade` class asks for `Nette\Database\Explorer` in its constructor, an Here you can read more about [dependency injection |dependency-injection:introduction] and [configuration |nette:configuring]. {{priority: -1}} +{{maintitle: Nette Tutorial: Move Database Code into a Model Class}} +{{description: Part of the Nette tutorial: move database queries out of presenters into a PostFacade model class and pass it in through the constructor for cleaner code.}} diff --git a/quickstart/en/single-post.texy b/quickstart/en/single-post.texy index 6e9fe40ba3..4d182e8030 100644 --- a/quickstart/en/single-post.texy +++ b/quickstart/en/single-post.texy @@ -122,3 +122,5 @@ Summary We have a database with posts and a web application with two views - the first displays an overview of all posts, and the second displays one specific post. {{priority: -1}} +{{maintitle: Nette Tutorial: Single Post Page and Handling a Missing ID}} +{{description: Part of the Nette tutorial: add a page that displays one blog post, create a link to it and show a 404 error when the requested post does not exist.}} diff --git a/robot-loader/cs/@home.texy b/robot-loader/cs/@home.texy index fda80b7648..444355b47e 100644 --- a/robot-loader/cs/@home.texy +++ b/robot-loader/cs/@home.texy @@ -152,3 +152,5 @@ Pokud aktualizujete balíček na novější verzi, podívejte se na stránku [up {{sitename: Nette Dokumentace}} +{{maintitle: Automatické načítání tříd v PHP: Nette RobotLoader}} +{{description: Zbavte se všech require. RobotLoader automaticky načítá třídy v celé aplikaci včetně knihoven třetích stran a nevyžaduje přísné jmenné konvence.}} diff --git a/robot-loader/cs/upgrading.texy b/robot-loader/cs/upgrading.texy index b9696b941b..50c245cc04 100644 --- a/robot-loader/cs/upgrading.texy +++ b/robot-loader/cs/upgrading.texy @@ -6,3 +6,6 @@ Upgrade na verzi 2.3 ==================== - RobotLoader je nyní case-sensitive a upozorní vás, pokud v názvu třídy použijete špatnou velikost písmen + +{{maintitle: Upgrade Nette RobotLoader: co se změnilo ve verzi 2.3}} +{{description: Co se změnilo v Nette RobotLoader 2.3: rozlišuje velikost písmen a upozorní vás, když v názvu třídy použijete špatnou.}} diff --git a/robot-loader/en/@home.texy b/robot-loader/en/@home.texy index b5c0922c13..07d262d205 100644 --- a/robot-loader/en/@home.texy +++ b/robot-loader/en/@home.texy @@ -152,3 +152,5 @@ If you are upgrading to a newer version, see the [upgrading] page. {{sitename: Nette Documentation}} +{{maintitle: PHP Autoloader Without Naming Rules: Nette RobotLoader}} +{{description: Get rid of all require statements. RobotLoader loads classes across your whole application, including third-party libraries, with no strict naming rules.}} diff --git a/robot-loader/en/upgrading.texy b/robot-loader/en/upgrading.texy index f1604afc92..d52cf89d74 100644 --- a/robot-loader/en/upgrading.texy +++ b/robot-loader/en/upgrading.texy @@ -6,3 +6,6 @@ Upgrading to Version 2.3 ======================== - RobotLoader is now case-sensitive and warns you if you use the wrong case in a class name + +{{maintitle: Upgrading Nette RobotLoader: What Changed in Version 2.3}} +{{description: What changed in Nette RobotLoader 2.3: it is now case-sensitive and warns you if you use the wrong case in a class name.}} diff --git a/safe-stream/cs/@home.texy b/safe-stream/cs/@home.texy index eca8dcc64a..310f95616e 100644 --- a/safe-stream/cs/@home.texy +++ b/safe-stream/cs/@home.texy @@ -73,3 +73,5 @@ Pokud aktualizujete balíček na novější verzi, podívejte se na stránku [up {{sitename: Nette Dokumentace}} +{{maintitle: Atomický zápis do souborů v PHP s Nette SafeStream}} +{{description: SafeStream izoluje každé čtení a zápis do souboru: žádné vlákno nezačne číst nedopsaný soubor a více vláken si nepřepíše stejný soubor.}} diff --git a/safe-stream/cs/upgrading.texy b/safe-stream/cs/upgrading.texy index 1599af323f..9e55eddf14 100644 --- a/safe-stream/cs/upgrading.texy +++ b/safe-stream/cs/upgrading.texy @@ -6,3 +6,6 @@ Upgrade na verzi 2.3 ==================== - protokol `safe://...` doporučujeme změnit na jmenný `nette.safe://...` + +{{maintitle: Upgrade Nette SafeStream: co se změnilo ve verzi 2.3}} +{{description: Co se změnilo v Nette SafeStream 2.3: místo protokolu safe:// se doporučuje protokol se jmenným prostorem nette.safe://.}} diff --git a/safe-stream/en/@home.texy b/safe-stream/en/@home.texy index 7525b6ff0f..85249b4780 100644 --- a/safe-stream/en/@home.texy +++ b/safe-stream/en/@home.texy @@ -73,3 +73,5 @@ If you are upgrading to a newer version, see the [upgrading] page. {{sitename: Nette Documentation}} +{{maintitle: PHP Atomic File Writes with Nette SafeStream}} +{{description: SafeStream makes every file read and write isolated: no thread reads a half-written file and several threads never overwrite the same file.}} diff --git a/safe-stream/en/upgrading.texy b/safe-stream/en/upgrading.texy index 23d8d2f8d4..c88f38af95 100644 --- a/safe-stream/en/upgrading.texy +++ b/safe-stream/en/upgrading.texy @@ -6,3 +6,6 @@ Upgrading to Version 2.3 ======================== - it is recommended to change the `safe://...` protocol to the namespaced `nette.safe://...` + +{{maintitle: Upgrading Nette SafeStream: What Changed in Version 2.3}} +{{description: What changed in Nette SafeStream 2.3: the recommended protocol changed from safe:// to the namespaced nette.safe://.}} diff --git a/schema/cs/@home.texy b/schema/cs/@home.texy index ec4c99bbd6..24bca67cf6 100644 --- a/schema/cs/@home.texy +++ b/schema/cs/@home.texy @@ -803,3 +803,6 @@ $processor->process($schema, ['maxUpload' => '5 TB']); ``` Protože prvek implementuje celé rozhraní, funguje automaticky i uvnitř `processMultiple()` - `Processor` volá jeho metodu `merge()` stejně jako u kteréhokoli jiného prvku. Jen `JsonSchema::export()` nemůže vědět, co takový prvek přijímá, a proto vyhodí `Nette\NotSupportedException`. + +{{maintitle: Nette Schema: validace a normalizace datových struktur v PHP}} +{{description: Praktická PHP knihovna pro validaci a normalizaci dat oproti schématu s chytrým a srozumitelným API. Hodí se třeba pro konfiguraci nebo vstupy z API.}} diff --git a/schema/en/@home.texy b/schema/en/@home.texy index d594376e41..0cc596b943 100644 --- a/schema/en/@home.texy +++ b/schema/en/@home.texy @@ -803,3 +803,6 @@ $processor->process($schema, ['maxUpload' => '5 TB']); ``` Because the element implements the whole interface, it also works automatically inside `processMultiple()` - the `Processor` calls its `merge()` method just like for any other element. Only `JsonSchema::export()` cannot know what such an element accepts, so it throws `Nette\NotSupportedException`. + +{{maintitle: Nette Schema: Validate and Normalize Data Structures in PHP}} +{{description: A practical PHP library for validating and normalizing data against a schema with a smart, easy-to-understand API. Great for configuration and API inputs.}} diff --git a/security/cs/@home.texy b/security/cs/@home.texy index 2a508baa32..56896a5363 100644 --- a/security/cs/@home.texy +++ b/security/cs/@home.texy @@ -19,3 +19,6 @@ Knihovnu stáhnete a nainstalujete pomocí nástroje [Composer|best-practices:co ```shell composer require nette/security ``` + +{{maintitle: Nette Security: přihlašování, oprávnění a hesla v PHP}} +{{description: Bezpečné uživatelské účty v PHP: přihlašování a odhlašování, ověřování oprávnění pomocí voterů nebo ACL a bezpečné ukládání hesel.}} diff --git a/security/cs/acl.texy b/security/cs/acl.texy index cd8882d15a..a6c0791b20 100644 --- a/security/cs/acl.texy +++ b/security/cs/acl.texy @@ -245,3 +245,6 @@ protected function startup() } } ``` + +{{maintitle: ACL v PHP s Nette: role, zdroje a pravidla}} +{{description: Řiďte přístup podle rolí uživatelů a částí webu. Třída Permission drží role, zdroje a pravidla přehledně na jednom místě, včetně dědičnosti mezi rolemi.}} diff --git a/security/cs/authentication.texy b/security/cs/authentication.texy index fbbce0b065..460b8c4a9d 100644 --- a/security/cs/authentication.texy +++ b/security/cs/authentication.texy @@ -326,3 +326,6 @@ $form->onSuccess[] = function (Form $form, \stdClass $data) { // ... }; ``` + +{{maintitle: Přihlašování uživatelů v PHP s Nette: autentizace a identita}} +{{description: Přihlašování a odhlašování uživatelů v Nette: vlastní autentikátor, práce s identitou, expirace přihlášení a více nezávislých přihlášení vedle sebe.}} diff --git a/security/cs/configuration.texy b/security/cs/configuration.texy index 47298b63e6..35f12916fc 100644 --- a/security/cs/configuration.texy +++ b/security/cs/configuration.texy @@ -109,3 +109,6 @@ Tyto služby se přidávají do DI kontejneru: | `security.passwords` | [api:Nette\Security\Passwords] | [hashování hesel|passwords] | `security.user` | [api:Nette\Security\User] | aktuální uživatel | `security.userStorage` | [api:Nette\Security\UserStorage] | [#úložiště] + +{{maintitle: Konfigurace Nette Security: uživatelé, role a úložiště}} +{{description: Konfigurace Nette Security v NEON: uživatelé, role a zdroje, volba úložiště přihlášeného uživatele a služby DI, které balíček registruje.}} diff --git a/security/cs/passwords.texy b/security/cs/passwords.texy index 665db864f0..d3f6d9b143 100644 --- a/security/cs/passwords.texy +++ b/security/cs/passwords.texy @@ -99,3 +99,6 @@ if ($passwords->needsRehash($hash)) { // uložit $hash do databáze } ``` + +{{maintitle: Hashování hesel v PHP s Nette: bcrypt a Argon2}} +{{description: Nikdy neukládejte hesla v čitelné podobě. Třída Passwords je bezpečně zahashuje, ověří při přihlášení a pozná, kdy je přehashovat po změně nastavení.}} diff --git a/security/cs/upgrading.texy b/security/cs/upgrading.texy index 48b92e0bc3..a30167c2e8 100644 --- a/security/cs/upgrading.texy +++ b/security/cs/upgrading.texy @@ -18,3 +18,6 @@ Upgrade na verzi 3.0 ==================== - třída `Nette\Security\Passwords` se nyní používá jako objekt, tj. metody již nejsou statické + +{{maintitle: Upgrade Nette Security: změny v jednotlivých verzích}} +{{description: Co se změnilo v Nette Security 4.0, 3.1 a 3.0 a jak upravit kód, včetně přechodu od authorizatorů k voterům ve verzi 4.0.}} diff --git a/security/en/@home.texy b/security/en/@home.texy index 64c2b1cd77..e139981bed 100644 --- a/security/en/@home.texy +++ b/security/en/@home.texy @@ -19,3 +19,6 @@ Download and install the package using [Composer|best-practices:composer]: ```shell composer require nette/security ``` + +{{maintitle: Nette Security: Login, Permissions and Password Hashing}} +{{description: User accounts done safely in PHP: log users in and out, check their permissions with voters or an ACL, and store their passwords as secure hashes.}} diff --git a/security/en/acl.texy b/security/en/acl.texy index 40fde774a5..f2a0f17629 100644 --- a/security/en/acl.texy +++ b/security/en/acl.texy @@ -245,3 +245,6 @@ protected function startup() } } ``` + +{{maintitle: PHP ACL with Nette: Roles, Resources and Rules}} +{{description: Control access by user role and section of your site. The Permission class keeps roles, resources and rules in one place, including inheritance between roles.}} diff --git a/security/en/authentication.texy b/security/en/authentication.texy index 6377dbd4ba..4fd5fcd245 100644 --- a/security/en/authentication.texy +++ b/security/en/authentication.texy @@ -326,3 +326,6 @@ $form->onSuccess[] = function (Form $form, \stdClass $data) { // ... }; ``` + +{{maintitle: User Login in PHP with Nette: Authentication and Identity}} +{{description: Log users in and out with Nette: write a custom authenticator, work with identity, set login expiration and run several independent logins side by side.}} diff --git a/security/en/configuration.texy b/security/en/configuration.texy index e110c08000..7af048cfea 100644 --- a/security/en/configuration.texy +++ b/security/en/configuration.texy @@ -109,3 +109,6 @@ These services are added to the DI container: | `security.passwords` | [api:Nette\Security\Passwords] | [password hashing |passwords] | `security.user` | [api:Nette\Security\User] | current user | `security.userStorage` | [api:Nette\Security\UserStorage] | [storage |#User Storage] + +{{maintitle: Nette Security Configuration: Users, Roles and Storage}} +{{description: Configure Nette Security in NEON: define users, roles and resources, choose where the logged-in user is stored and see the DI services it registers.}} diff --git a/security/en/passwords.texy b/security/en/passwords.texy index 4774263dd4..16ea669e3a 100644 --- a/security/en/passwords.texy +++ b/security/en/passwords.texy @@ -99,3 +99,6 @@ if ($passwords->needsRehash($hash)) { // store $hash into database } ``` + +{{maintitle: PHP Password Hashing with Nette: bcrypt and Argon2}} +{{description: Never store passwords in readable form. Hash them securely with the Passwords class, verify them at login and rehash them when your algorithm settings change.}} diff --git a/security/en/upgrading.texy b/security/en/upgrading.texy index bd49a01566..f1c831040f 100644 --- a/security/en/upgrading.texy +++ b/security/en/upgrading.texy @@ -18,3 +18,6 @@ Upgrading to Version 3.0 ======================== - the `Nette\Security\Passwords` class is now used as an object, i.e. the methods are no longer static + +{{maintitle: Upgrading Nette Security: What Changed in Each Version}} +{{description: What changed in Nette Security 4.0, 3.1 and 3.0 and how to update your code, including the move from authorizators to voters in version 4.0.}} diff --git a/tester/cs/@home.texy b/tester/cs/@home.texy index 80e11efe81..b8adbef9b2 100644 --- a/tester/cs/@home.texy +++ b/tester/cs/@home.texy @@ -1,3 +1,3 @@ -{{maintitle: Nette Tester – pohodové testování v PHP}} -{{description: Nette Tester je jednoduchý a přitom velmi šikovný nástroj na testování PHP kódu.}} {{leftbar: no}} +{{maintitle: Nette Tester – pohodové testování v PHP}} +{{description: Pište testy v PHP jako obyčejné skripty, které spustíte a odladíte samostatně. Nette Tester je pouští paralelně a přidává aserce a reporty pokrytí kódu.}} diff --git a/tester/cs/assertions.texy b/tester/cs/assertions.texy index dbb12c8071..efdc99fe58 100644 --- a/tester/cs/assertions.texy +++ b/tester/cs/assertions.texy @@ -298,3 +298,6 @@ app/ ``` Název adresáře můžeme změnit přes `Tester\Dumper::$dumpDir`. + +{{maintitle: Aserce v Nette Tester: Assert::same, exception a další}} +{{description: Všechny metody třídy Tester Assert: porovnávání hodnot, kontrola typů a polí, očekávané výjimky a chyby a porovnání textu se vzorem.}} diff --git a/tester/cs/guide.texy b/tester/cs/guide.texy index d1ea141693..730930e5f3 100644 --- a/tester/cs/guide.texy +++ b/tester/cs/guide.texy @@ -174,3 +174,6 @@ Podporované verze PHP Platí pro poslední patch verze. Tester do verze 1.7 podporoval také [HHVM |https://hhvm.com] 3.3.0 nebo vyšší (přes `tester -p hhvm`). Podpora byla od verze Testeru 2.0 ukončena. + +{{maintitle: Začínáme s Nette Tester: unit testy v PHP}} +{{description: Nainstalujte Nette Tester přes Composer, napište první test v PHP a spusťte ho. Čím je Tester unikátní, watch režim a reporty pokrytí kódu.}} diff --git a/tester/cs/helpers.texy b/tester/cs/helpers.texy index d0cacd9793..6c7648aa9e 100644 --- a/tester/cs/helpers.texy +++ b/tester/cs/helpers.texy @@ -263,3 +263,6 @@ Tester spouští testy paralelně v zadaném počtu vláken. Pokud nás zajímá ```php echo "Běžím ve vlákně číslo " . getenv(Tester\Environment::VariableThread); ``` + +{{maintitle: Pomocné třídy v Nette Tester: HttpAssert, DomQuery, FileMock}} +{{description: Pomocné třídy pro testy v PHP: HttpAssert pro testování HTTP odpovědí, DomQuery pro dotazy do HTML, FileMock pro falešné soubory a příprava prostředí.}} diff --git a/tester/cs/running-tests.texy b/tester/cs/running-tests.texy index 26acfa37a4..f51c4de928 100644 --- a/tester/cs/running-tests.texy +++ b/tester/cs/running-tests.texy @@ -283,3 +283,6 @@ Při použití `-c` Tester **ignoruje systémovou konfiguraci** (spouští PHP s .[note] Do verze 2.6 Tester bez uvedení `-c` spouštěl PHP s parametrem `-n`, tedy bez php.ini; volba `-C` toto potlačila. Od verze 2.6 se systémové php.ini načítá automaticky. Chování při použití `-c` zůstává stejné. + +{{maintitle: Spouštění testů v Nette Tester: příkazová řádka a parametry}} +{{description: Spouštěč testů Nette Tester pouští každý test jako samostatný proces, paralelně ve více vláknech. Všechny parametry, watch režim a vlastní php.ini.}} diff --git a/tester/cs/test-annotations.texy b/tester/cs/test-annotations.texy index 3efe3f7c9e..93da781511 100644 --- a/tester/cs/test-annotations.texy +++ b/tester/cs/test-annotations.texy @@ -173,3 +173,6 @@ Funkce anotací je shodná s asercemi `Assert::match()` a `Assert::matchFile()`. @phpIni .[filter] ----------------- Pro test nastavuje konfigurační INI hodnoty. Zapisujeme například jako `@phpIni precision=20` a funguje stejně, jako kdybychom zadali hodnotu z příkazové řádky přes parametr `-d precision=20`. + +{{maintitle: Anotace testů v Nette Tester: skip, data provider a další}} +{{description: Anotace na začátku souboru říkají spouštěči Nette Tester, jak s testem naložit: přeskočit ho, vyžadovat verzi PHP, použít data provider nebo nastavit timeout.}} diff --git a/tester/cs/testcase.texy b/tester/cs/testcase.texy index d037fbe14e..91dfb46ba6 100644 --- a/tester/cs/testcase.texy +++ b/tester/cs/testcase.texy @@ -221,3 +221,6 @@ return [ Stejně jako u [data provideru pro soubory |test-annotations#dataProvider] lze za název souboru připojit filtrovací dotaz a spustit metodu jen pro vyhovující sekce. U atributu dotaz předáme jako druhý argument, například `#[DataProvider('loop-args.ini', 'one')]`. Metoda může mít i více data providerů, zapsaných jako více atributů nebo anotací. Spustí se pak postupně se sadami dat ze všech. + +{{maintitle: TestCase v Nette Tester: testy v PHP uspořádané do tříd}} +{{description: Zabalte aserce do testovací třídy a dejte jim strukturu: testovací metody, setUp a tearDown, očekávané výjimky a data providery v anotacích metod.}} diff --git a/tester/cs/writing-tests.texy b/tester/cs/writing-tests.texy index d9631e238e..3394a276c7 100644 --- a/tester/cs/writing-tests.texy +++ b/tester/cs/writing-tests.texy @@ -287,3 +287,6 @@ Test, který nezavolá ani jednu aserční metodu, je podezřelý a vyhodnotí s Pokud opravdu má být test bez volání asercí považován za platný, zavolejte třeba `Assert::true(true)`. Také může být zrádné používat `exit()` a `die()` k ukončení testu s chybovou zprávou. Například `exit('Error in connection')` ukončí test s návratovým kódem 0, což signalizuje úspěch. Použijte `Assert::fail('Error in connection')`. + +{{maintitle: Psaní testů v PHP s Nette Tester: samostatné skripty}} +{{description: V Nette Tester je každý test PHP skript, který spustíte samostatně a krokujete v IDE. Jak psát přehledné testy, přeskakovat je a uspořádat adresáře.}} diff --git a/tester/en/@home.texy b/tester/en/@home.texy index 7df7751909..17accab6af 100644 --- a/tester/en/@home.texy +++ b/tester/en/@home.texy @@ -1,3 +1,3 @@ -{{maintitle: Nette Tester – Enjoyable Unit Testing in PHP}} -{{description: Nette Tester is a simple yet very handy tool for testing PHP code.}} {{leftbar: no}} +{{maintitle: Nette Tester – Enjoyable Unit Testing in PHP}} +{{description: Write PHP tests as plain scripts you can run and debug on their own. Nette Tester runs them in parallel and adds clear assertions and code coverage reports.}} diff --git a/tester/en/assertions.texy b/tester/en/assertions.texy index 6d161ec08f..2801048718 100644 --- a/tester/en/assertions.texy +++ b/tester/en/assertions.texy @@ -298,3 +298,6 @@ app/ ``` We can change the directory name via `Tester\Dumper::$dumpDir`. + +{{maintitle: Nette Tester Assertions: Assert::same, exception and More}} +{{description: All methods of the Tester Assert class: compare values, check types and arrays, expect exceptions and errors, and match text against patterns.}} diff --git a/tester/en/guide.texy b/tester/en/guide.texy index 457b81f543..f9894d30b7 100644 --- a/tester/en/guide.texy +++ b/tester/en/guide.texy @@ -174,3 +174,6 @@ Supported PHP versions Applies to the latest patch version. Tester up to version 1.7 also supported [HHVM |https://hhvm.com] 3.3.0 or higher (via `tester -p hhvm`). Support was discontinued from Tester version 2.0. + +{{maintitle: Getting Started with Nette Tester: PHP Unit Testing}} +{{description: Install Nette Tester with Composer, write your first PHP test and run it. See what makes Tester unique, plus watch mode and code coverage reports.}} diff --git a/tester/en/helpers.texy b/tester/en/helpers.texy index 1129a1819f..5ae6849953 100644 --- a/tester/en/helpers.texy +++ b/tester/en/helpers.texy @@ -263,3 +263,6 @@ Tester runs tests in parallel in the specified number of threads. If we are inte ```php echo "Running in thread number " . getenv(Tester\Environment::VariableThread); ``` + +{{maintitle: Nette Tester Helpers: HttpAssert, DomQuery and FileMock}} +{{description: Helper classes for your PHP tests: test HTTP responses with HttpAssert, query HTML with DomQuery, mock files with FileMock and set up the test environment.}} diff --git a/tester/en/running-tests.texy b/tester/en/running-tests.texy index 10c735af13..8a599fb9cd 100644 --- a/tester/en/running-tests.texy +++ b/tester/en/running-tests.texy @@ -283,3 +283,6 @@ When using `-c`, Tester **ignores the system configuration** (runs PHP with the .[note] Prior to version 2.6, without `-c`, Tester ran PHP with the `-n` flag, i.e., without php.ini; the `-C` option suppressed this. From version 2.6, the system php.ini is loaded by default. The behavior when using `-c` remains unchanged. + +{{maintitle: Running PHP Tests with Nette Tester: Command-Line Runner}} +{{description: The Nette Tester command-line runner runs each test as a separate process, in parallel across multiple threads. All options, watch mode and your own php.ini.}} diff --git a/tester/en/test-annotations.texy b/tester/en/test-annotations.texy index abb00b124f..9eed286f83 100644 --- a/tester/en/test-annotations.texy +++ b/tester/en/test-annotations.texy @@ -173,3 +173,6 @@ The function of these annotations is identical to the `Assert::match()` and `Ass @phpIni .[filter] ----------------- Sets INI configuration values for the test. For example, write it as `@phpIni precision=20`. It works the same way as if you specified the value from the command line using the `-d precision=20` parameter. + +{{maintitle: Nette Tester Annotations: Skip, Data Providers and More}} +{{description: Annotations at the start of a test file tell the Nette Tester runner how to handle it: skip it, require a PHP version, use a data provider or set a timeout.}} diff --git a/tester/en/testcase.texy b/tester/en/testcase.texy index 295ef94aa7..ff47caefb2 100644 --- a/tester/en/testcase.texy +++ b/tester/en/testcase.texy @@ -221,3 +221,6 @@ return [ As with the [data provider for test files |test-annotations#dataProvider], you can append a filtering query after the file name to run the method only for the matching sections. With the attribute, pass the query as the second argument, for example `#[DataProvider('loop-args.ini', 'one')]`. A method can also have several data providers, written as several attributes or annotations. It then runs with the data sets of all of them, one after another. + +{{maintitle: Nette Tester TestCase: Organize PHP Tests in Classes}} +{{description: Wrap assertions in a test class to give them structure: test methods, setUp and tearDown, expected exceptions and data providers in method annotations.}} diff --git a/tester/en/writing-tests.texy b/tester/en/writing-tests.texy index 5c49570949..3a9dceb19e 100644 --- a/tester/en/writing-tests.texy +++ b/tester/en/writing-tests.texy @@ -287,3 +287,6 @@ A test that does not call any assertion method is considered suspicious and will If a test without assertions is intentionally valid, call `Assert::true(true)` to mark it as such. Using `exit()` or `die()` to terminate a test with an error message can be misleading. For example, `exit('Error in connection')` terminates the test with an exit code of 0, which signals success. Use `Assert::fail('Error in connection')` instead. + +{{maintitle: Writing PHP Tests with Nette Tester: Standalone Scripts}} +{{description: In Nette Tester, each test is a PHP script you can run on its own and step through in your IDE. Keep tests readable, skip them and organize their directories.}} diff --git a/tokenizer/cs/@home.texy b/tokenizer/cs/@home.texy index c3bbb47e51..ac39b0e979 100644 --- a/tokenizer/cs/@home.texy +++ b/tokenizer/cs/@home.texy @@ -210,3 +210,5 @@ Poslední metoda `reset()` vrací kurzor na začátek, takže můžete opakovat {{leftbar: utils:@left-menu}} {{sitename: Nette Dokumentace}} +{{maintitle: Nette Tokenizer: rozdělení řetězců na tokeny pomocí regexů}} +{{description: Jednoduchý nástroj, který pomocí regulárních výrazů rozdělí řetězec na tokeny. Upozornění: tato knihovna se již nevyvíjí.}} diff --git a/tokenizer/en/@home.texy b/tokenizer/en/@home.texy index 7fd6992327..d5d1f7e239 100644 --- a/tokenizer/en/@home.texy +++ b/tokenizer/en/@home.texy @@ -210,3 +210,5 @@ And the last method `reset()` resets the cursor, so you can iterate the token st {{leftbar: utils:@left-menu}} {{sitename: Nette Documentation}} +{{maintitle: Nette Tokenizer: Split Strings into Tokens with Regex}} +{{description: A simple tool that splits a string into tokens using regular expressions. Note that this library is no longer being developed.}} diff --git a/tools/cs/@home.texy b/tools/cs/@home.texy index 7cb06b3c43..bb3d5526d6 100644 --- a/tools/cs/@home.texy +++ b/tools/cs/@home.texy @@ -34,3 +34,6 @@ Frontend Migrace na Latte ---------------- - Převod šablon [z PHP |latte:cookbook/migration-from-php] a [z Twigu |latte:cookbook/migration-from-twig] pomocí nástroje latte-tools. + +{{maintitle: Nástroje pro vývoj s Nette: Code Checker, PHPStan a IDE}} +{{description: Pomocné nástroje, které usnadní vývoj s Nette: Code Checker, coding standard, pravidla pro PHPStan, X-Ray a pluginy pro editory a IDE.}} diff --git a/tools/cs/code-checker.texy b/tools/cs/code-checker.texy index 1dcea2441a..cdc9d7ea4c 100644 --- a/tools/cs/code-checker.texy +++ b/tools/cs/code-checker.texy @@ -83,3 +83,6 @@ Styl PHP kódu ============= Na styl PHP kódu Code Checker nesahá, to je práce pro [DressCode |coding-standard]. Ten kontroluje a opravuje PHP kód podle standardu, který si zvolíte (PER Coding Style, PSR-12, Nette, Symfony nebo Laravel), mění přitom jen to, co opravuje, a umí kód rovnou převést na novější verzi PHP i na nové verze knihoven. Převzal také PHP kontroly, které dělaly starší verze Code Checkeru: chybně zapsané phpDoc komentáře, chybějící `declare(strict_types=1)` a odsazení mezerami v souborech PHP. + +{{maintitle: Nette Code Checker: kontrola BOM, kódování a syntaxe}} +{{description: Zkontrolujte ve zdrojových souborech neviditelný BOM, kontrolní znaky, chybné kódování i syntaxi PHP, Latte, NEON a JSON a nechte je automaticky opravit.}} diff --git a/tools/cs/coding-standard.texy b/tools/cs/coding-standard.texy index 89db373529..3bff0a468f 100644 --- a/tools/cs/coding-standard.texy +++ b/tools/cs/coding-standard.texy @@ -166,3 +166,6 @@ Původní balíček `nette/coding-standard` kontroloval standard pomocí PHP CS První `dresscode fix` nejspíš sáhne na víc souborů, než čekáte, protože DressCode opravuje i některá místa, která verze 3 nechávala být. Udělejte z něj samostatný commit bez dalších změn. Všechno ostatní, od všech nastavení až po spouštění DressCode v editoru nebo po každé úpravě, kterou udělá AI agent, najdete v [manuálu DressCode |https://dresscode.run/cs/]. + +{{maintitle: Nette Coding Standard: kontrola a oprava PHP kódu s DressCode}} +{{description: Nechte DressCode hlídat, aby váš PHP kód dodržoval Nette coding standard: zkontroluje každý soubor a jedním příkazem opraví, co najde, lokálně i v CI.}} diff --git a/tools/cs/ide.texy b/tools/cs/ide.texy index 5c499c5644..1f31fa423a 100644 --- a/tools/cs/ide.texy +++ b/tools/cs/ide.texy @@ -42,3 +42,6 @@ Propojení s Tracy ================= Propojte si také Tracy s editorem. Při zobrazení chybové stránky pak půjde kliknout na jména souborů a ty se otevřou v editoru s kurzorem na příslušné řádce. Přečtěte si, [jak systém nakonfigurovat |tracy:open-files-in-ide]. + +{{maintitle: Pluginy pro Nette do PhpStormu a VS Code: editory a IDE}} +{{description: Dobrý editor obarví syntaxi, našeptává kód a hlídá překlepy. Doporučené editory a pluginy pro Nette, Latte a NEON v PhpStormu a VS Code.}} diff --git a/tools/cs/phpstan-rules.texy b/tools/cs/phpstan-rules.texy index 3f449eaa46..497a8d055c 100644 --- a/tools/cs/phpstan-rules.texy +++ b/tools/cs/phpstan-rules.texy @@ -294,3 +294,6 @@ Strings::replace($s, '#(\d+)#', function (array $m) { **`Helpers::falseToNull()`** zúží návratový typ tak, že odstraní `false` a přidá `null`. Z `string|false` se tedy stane `string|null`. **`Html` magické metody**: `$el->setClass(…)`, `$el->addData(…)`, `$el->getHref()` a podobné se rozpoznají i bez `@method` anotací. `setXxx()` a `addXxx()` vrací `static` (fluent API), `getXxx()` vrací `mixed`. + +{{maintitle: Nette PHPStan Rules: přesné typy a méně falešných chyb}} +{{description: Naučte PHPStan rozumět Nette kódu, aby statická analýza odvozovala přesné typy a hlásila méně falešných chyb u formulářů, komponent, DI, schema a dalších.}} diff --git a/tools/cs/xray.texy b/tools/cs/xray.texy index fa606f7999..a8e5e1cd28 100644 --- a/tools/cs/xray.texy +++ b/tools/cs/xray.texy @@ -88,3 +88,6 @@ Pomozte vývoji Nette Po analýze můžete report dobrovolně odeslat a pomoct tak směřovat vývoj frameworku – reálná data o používání jsou spolehlivější než ankety. Odesílají se jen agregovaná čísla: kolikrát se které API zavolá a jaké vzory používáte. Žádný kód, žádné cesty k souborům, žádné hodnoty proměnných. Data se odešlou jen tehdy, když to výslovně potvrdíte, a JSON report se vždy nejdřív uloží lokálně, takže si ho můžete v klidu prohlédnout. \-- + +{{maintitle: Nette X-Ray: jak váš projekt využívá Nette}} +{{description: X-Ray vám ukáže, jak přesně váš projekt využívá ekosystém Nette: které metody, Latte filtry a konfigurační klíče doopravdy používáte.}} diff --git a/tools/en/@home.texy b/tools/en/@home.texy index 0348e5cfed..20c248467a 100644 --- a/tools/en/@home.texy +++ b/tools/en/@home.texy @@ -34,3 +34,6 @@ Frontend Migrating to Latte ------------------ - Convert templates [from PHP |latte:cookbook/migration-from-php] and [from Twig |latte:cookbook/migration-from-twig] using the latte-tools tool. + +{{maintitle: Nette Developer Tools: Code Checker, PHPStan, IDE Support}} +{{description: Helper tools that make development with Nette easier: Code Checker, the coding standard, PHPStan rules, X-Ray and editor and IDE plugins.}} diff --git a/tools/en/code-checker.texy b/tools/en/code-checker.texy index 1805f61b62..406d0866b3 100644 --- a/tools/en/code-checker.texy +++ b/tools/en/code-checker.texy @@ -83,3 +83,6 @@ PHP Code Style ============== Code Checker leaves the style of PHP code alone; that is the job of [DressCode |coding-standard]. It checks and fixes PHP code in the coding standard you pick (PER Coding Style, PSR-12, Nette, Symfony or Laravel), changes only what it fixes, and can also upgrade the code to a newer PHP version and to new versions of libraries. It has also taken over the PHP checks that earlier versions of Code Checker did: malformed phpDoc comments, a missing `declare(strict_types=1)` and indentation with spaces in PHP files. + +{{maintitle: Nette Code Checker: Find BOM, Encoding and Syntax Errors}} +{{description: Check your source files for an invisible BOM, control characters, broken encoding or invalid PHP, Latte, NEON and JSON syntax, and fix them automatically.}} diff --git a/tools/en/coding-standard.texy b/tools/en/coding-standard.texy index 90c061a960..f76e52e431 100644 --- a/tools/en/coding-standard.texy +++ b/tools/en/coding-standard.texy @@ -166,3 +166,6 @@ The original `nette/coding-standard` package checked the standard with PHP CS Fi The first `dresscode fix` will probably touch more files than you expect, because DressCode also fixes some places that version 3 left alone. Make it a commit of its own, with no other changes. Everything else, from all the settings to running DressCode in your editor or after every edit an AI agent makes, is in the [DressCode manual |https://dresscode.run/en/]. + +{{maintitle: Nette Coding Standard: Check and Fix PHP Code with DressCode}} +{{description: Let DressCode keep your PHP code in the Nette coding standard: it checks every file and fixes what it finds with one command, locally and in CI.}} diff --git a/tools/en/ide.texy b/tools/en/ide.texy index 9ebffca913..2c395600ee 100644 --- a/tools/en/ide.texy +++ b/tools/en/ide.texy @@ -42,3 +42,6 @@ Tracy Integration ================= Also integrate Tracy with your editor. When an error page is displayed, clicking on file names will open them directly in your editor at the corresponding line. Learn [how to configure this feature |tracy:open-files-in-ide]. + +{{maintitle: Nette Plugins for PhpStorm and VS Code: Editors and IDEs}} +{{description: A good editor highlights syntax, autocompletes code and catches typos. Recommended editors and plugins for Nette, Latte and NEON in PhpStorm and VS Code.}} diff --git a/tools/en/phpstan-rules.texy b/tools/en/phpstan-rules.texy index b9d9a2a600..a40edf84fc 100644 --- a/tools/en/phpstan-rules.texy +++ b/tools/en/phpstan-rules.texy @@ -294,3 +294,6 @@ Strings::replace($s, '#(\d+)#', function (array $m) { **`Helpers::falseToNull()`** narrows the return type by removing `false` and adding `null`. Thus `string|false` becomes `string|null`. **`Html` magic methods**: `$el->setClass(…)`, `$el->addData(…)`, `$el->getHref()` and similar are resolved without `@method` annotations. `setXxx()` and `addXxx()` return `static` (fluent API), `getXxx()` returns `mixed`. + +{{maintitle: Nette PHPStan Rules: Precise Types, Fewer False Positives}} +{{description: Teach PHPStan to understand Nette code, so static analysis infers precise types and reports fewer false positives for forms, components, DI, schema and more.}} diff --git a/tools/en/xray.texy b/tools/en/xray.texy index fbe6262e77..c19e3973c4 100644 --- a/tools/en/xray.texy +++ b/tools/en/xray.texy @@ -88,3 +88,6 @@ Help Improve Nette After the analysis, you can optionally send the report to help guide the framework's development – real usage data is far more reliable than surveys. Only aggregated numbers are sent: how many times each API is called and which patterns you use. No code, no file paths, no variable values. Data is sent only if you explicitly confirm, and the JSON report is always saved locally first, so you can review it at your leisure. \-- + +{{maintitle: Nette X-Ray: See How Your Project Uses Nette}} +{{description: X-Ray shows exactly how your project uses the Nette ecosystem: which methods, Latte filters and configuration keys you actually use.}} diff --git a/tracy/cs/@home.texy b/tracy/cs/@home.texy index cced1421f2..98589481de 100644 --- a/tracy/cs/@home.texy +++ b/tracy/cs/@home.texy @@ -1,3 +1,3 @@ -{{maintitle: Tracy – ladicí nástroj, se kterým je radost chybovat}} -{{description: Tracy je nástroj určený k usnadnění ladění PHP kódu. Je užitečným pomocníkem pro všechny programátory PHP, kterým pomáhá s vizualizací a logováním chyb, s dumpováním proměnných a mnohem více. Upozornění: Tracy je návyková!}} {{leftbar: no}} +{{maintitle: Tracy – ladicí nástroj, se kterým je radost chybovat}} +{{description: Tracy usnadňuje ladění PHP kódu: přehledná vizualizace a logování chyb, dumpování proměnných a mnohem více. Upozornění: Tracy je návyková!}} diff --git a/tracy/cs/configuring.texy b/tracy/cs/configuring.texy index 825dc4ab0f..d3ef6fed91 100644 --- a/tracy/cs/configuring.texy +++ b/tracy/cs/configuring.texy @@ -193,3 +193,6 @@ Tyto služby se přidávají do DI kontejneru: | `tracy.logger` | [api:Tracy\ILogger] | logger | `tracy.blueScreen` | [api:Tracy\BlueScreen] | BlueScreen | `tracy.bar` | [api:Tracy\Bar] | Tracy Bar + +{{maintitle: Konfigurace Tracy: logování chyb, dump() a další}} +{{description: Nastavení PHP debuggeru Tracy: logování chyb a upozornění e-mailem, chování funkce dump() a konfigurace v Nette přes NEON.}} diff --git a/tracy/cs/dumper.texy b/tracy/cs/dumper.texy index 502ca49016..ac3be8725b 100644 --- a/tracy/cs/dumper.texy +++ b/tracy/cs/dumper.texy @@ -121,3 +121,6 @@ Dumper::$objectExporters[PhpToken::class] = function (PhpToken $token, Dumper\Va ``` Exportér dostane objekt a objekt `Tracy\Dumper\Value` popisující, jak se objekt zobrazí. Přiřazení do `$value->value` nahradí hlavičku (ve výchozím stavu název třídy) vaším vlastním textem, takže místo výpisu properties dostanete kompaktní, čitelný popisek. Nastavení se uplatní na každý dump dané třídy, i na objekty zanořené v polích či jiných objektech. Případně můžete exportéry předat jen pro jedno volání pomocí volby `Dumper::OBJECT_EXPORTERS` funkce `Tracy\Dumper::dump()`. + +{{maintitle: Dumpování proměnných v PHP s Tracy: lepší var_dump}} +{{description: Lepší var_dump: Tracy vypisuje proměnné v PHP barevně a s rozbalovacími strukturami. Volby Dumperu a vlastní vykreslení objektů.}} diff --git a/tracy/cs/extensions.texy b/tracy/cs/extensions.texy index 346ce13a79..6be1e423a3 100644 --- a/tracy/cs/extensions.texy +++ b/tracy/cs/extensions.texy @@ -197,3 +197,6 @@ Pokud je výjimka vyhozena v okamžiku, kdy je fiber nebo generátor pozastaven ```php Tracy\Debugger::getBlueScreen()->addFiber($fiber); ``` + +{{maintitle: Tvorba rozšíření pro Tracy: panely Baru a Bluescreen}} +{{description: Chcete mít při ladění po ruce další informace? Napište si vlastní panely pro Tracy Bar a vlastní sekce pro chybovou stránku Bluescreen v PHP.}} diff --git a/tracy/cs/guide.texy b/tracy/cs/guide.texy index 29a365f9f9..42b286978e 100644 --- a/tracy/cs/guide.texy +++ b/tracy/cs/guide.texy @@ -238,3 +238,6 @@ Toto je seznam neoficiálních portů pro další frameworky a CMS: - [Slim Framework](https://github.com/runcmf/runtracy) - Symfony framework: [kutny/tracy-bundle](https://github.com/kutny/tracy-bundle), [VasekPurchart/Tracy-Blue-Screen-Bundle](https://github.com/VasekPurchart/Tracy-Blue-Screen-Bundle) - [WordPress](https://github.com/ktstudio/WP-Tracy) + +{{maintitle: PHP debugger Tracy: začínáme s laděním chyb}} +{{description: Nainstalujte Tracy a rychle najděte a opravte chyby v PHP: přehledná chybová stránka, Tracy Bar, dumpování, logování chyb, měření času a spotřeby paměti.}} diff --git a/tracy/cs/open-files-in-ide.texy b/tracy/cs/open-files-in-ide.texy index 453d093012..4aec6c0ea9 100644 --- a/tracy/cs/open-files-in-ide.texy +++ b/tracy/cs/open-files-in-ide.texy @@ -149,3 +149,6 @@ Importujte jej dvojitým kliknutím a restartujte prohlížeč Chrome. Politika S případnými dotazy nebo připomínkami se prosím obraťte na [fórum |https://forum.nette.org]. + +{{maintitle: Otevírání souborů v editoru z Tracy: integrace s IDE}} +{{description: Klikněte na název souboru na chybové stránce Tracy a otevře se v editoru na správném řádku. Jak to nastavit ve Windows, Linuxu a macOS a řešení potíží.}} diff --git a/tracy/cs/recipes.texy b/tracy/cs/recipes.texy index f868a0f2f4..e11e848058 100644 --- a/tracy/cs/recipes.texy +++ b/tracy/cs/recipes.texy @@ -256,3 +256,6 @@ změňte to na: ```nginx try_files $uri $uri/ /index.php$is_args$args; ``` + +{{maintitle: Návody pro Tracy: CSP, ladění AJAXu, vlastní logger, nginx}} +{{description: Praktické návody pro debugger Tracy: Content Security Policy, rychlejší načítání, ladění AJAXových požadavků, vlastní scrubber a logger a nastavení nginx.}} diff --git a/tracy/cs/stopwatch.texy b/tracy/cs/stopwatch.texy index 2c75f01c27..19dda69c01 100644 --- a/tracy/cs/stopwatch.texy +++ b/tracy/cs/stopwatch.texy @@ -33,3 +33,6 @@ Debugger::timer(); // zapne stopky echo Debugger::timer(); // vypíše uplynulý čas v sekundách ``` + +{{maintitle: Měření času běhu PHP skriptu se stopkami Tracy}} +{{description: Změřte, jak dlouho běží váš PHP kód, pomocí stopek v Tracy: nanosekundová přesnost, více nezávislých měření a jednoduché volání Debugger::timer().}} diff --git a/tracy/cs/upgrading.texy b/tracy/cs/upgrading.texy index 2355596870..aabef9429e 100644 --- a/tracy/cs/upgrading.texy +++ b/tracy/cs/upgrading.texy @@ -8,3 +8,6 @@ Upgrade na verzi 2.9 - Tracy již nepoužívá nativní PHP session. Data si odkládá do vlastních dočasných souborů a klíč posílá v cookie `tracy-session`. Díky tomu Tracy session nestartuje a vy tak můžete ladit, jak s ní pracuje vaše vlastní aplikace. Co dalšího se na ikonické červené obrazovce změnilo, popisuje článek [Tracy 2.9 a proměna ikonické obrazovky |https://blog.nette.org/cs/tracy-2-9-a-promena-ikonicke-obrazovky]. + +{{maintitle: Upgrade Tracy: co se změnilo ve verzi 2.9}} +{{description: Co se změnilo v Tracy 2.9: přestala používat nativní PHP session a data si ukládá do vlastních dočasných souborů, což je dobré vědět při upgradu.}} diff --git a/tracy/en/@home.texy b/tracy/en/@home.texy index 781834be95..737ef62e55 100644 --- a/tracy/en/@home.texy +++ b/tracy/en/@home.texy @@ -1,3 +1,3 @@ -{{maintitle: Tracy – A Must-Have Debugging Tool for All PHP Developers}} -{{description: Tracy is a tool designed to facilitate debugging PHP code. It is a useful assistant for all PHP programmers, helping with clear visualization and logging of errors, dumping variables, and much more. Warning: Tracy is addictive!}} {{leftbar: no}} +{{maintitle: Tracy – A Must-Have Debugging Tool for All PHP Developers}} +{{description: Tracy makes debugging PHP code easier: clear visualization and logging of errors, dumping variables and much more. Warning: Tracy is addictive!}} diff --git a/tracy/en/configuring.texy b/tracy/en/configuring.texy index 3388a9eddf..213b521a3f 100644 --- a/tracy/en/configuring.texy +++ b/tracy/en/configuring.texy @@ -193,3 +193,6 @@ These services are added to the DI container: | `tracy.logger` | [api:Tracy\ILogger] | logger | `tracy.blueScreen` | [api:Tracy\BlueScreen] | BlueScreen | `tracy.bar` | [api:Tracy\Bar] | Tracy Bar + +{{maintitle: Tracy Configuration: Error Logging, dump() and More}} +{{description: Set up the Tracy PHP debugger: error logging and email notifications, the behavior of dump(), and configuration in Nette through NEON.}} diff --git a/tracy/en/dumper.texy b/tracy/en/dumper.texy index 3bf27798c0..c5f8d38e22 100644 --- a/tracy/en/dumper.texy +++ b/tracy/en/dumper.texy @@ -121,3 +121,6 @@ Dumper::$objectExporters[PhpToken::class] = function (PhpToken $token, Dumper\Va ``` The exporter receives the object and a `Tracy\Dumper\Value` object describing how it will be shown. Assigning to `$value->value` replaces the header (by default the class name) with your own text, so instead of a list of properties you get a compact, readable label. The setting applies to every dump of that class, even to objects nested inside arrays or other objects. Alternatively, you can pass exporters for a single call only via the `Dumper::OBJECT_EXPORTERS` option of `Tracy\Dumper::dump()`. + +{{maintitle: PHP Variable Dump with Tracy: A Better var_dump}} +{{description: A better var_dump: Tracy dumps PHP variables with colored output and collapsible structures. Dumper options and custom rendering of objects.}} diff --git a/tracy/en/extensions.texy b/tracy/en/extensions.texy index a61ac198ce..e1971c25e9 100644 --- a/tracy/en/extensions.texy +++ b/tracy/en/extensions.texy @@ -197,3 +197,6 @@ If an exception is thrown while a fiber or generator is suspended, its stack is ```php Tracy\Debugger::getBlueScreen()->addFiber($fiber); ``` + +{{maintitle: Creating Tracy Extensions: Bar Panels and Bluescreen}} +{{description: Want more information at hand while debugging? Write your own panels for the Tracy Bar and custom sections for the Bluescreen error page in PHP.}} diff --git a/tracy/en/guide.texy b/tracy/en/guide.texy index 38ef14c2fc..69d7e42dc5 100644 --- a/tracy/en/guide.texy +++ b/tracy/en/guide.texy @@ -238,3 +238,6 @@ This is a list of unofficial ports to other frameworks and CMS: - [Slim Framework](https://github.com/runcmf/runtracy) - Symfony framework: [kutny/tracy-bundle](https://github.com/kutny/tracy-bundle), [VasekPurchart/Tracy-Blue-Screen-Bundle](https://github.com/VasekPurchart/Tracy-Blue-Screen-Bundle) - [WordPress](https://github.com/ktstudio/WP-Tracy) + +{{maintitle: Tracy PHP Debugger: Getting Started with Error Debugging}} +{{description: Install Tracy and quickly find and fix PHP errors: a clear error page, Tracy Bar, variable dumps, error logging, execution time and memory measurement.}} diff --git a/tracy/en/open-files-in-ide.texy b/tracy/en/open-files-in-ide.texy index a2facd34e5..75563cbd21 100644 --- a/tracy/en/open-files-in-ide.texy +++ b/tracy/en/open-files-in-ide.texy @@ -149,3 +149,6 @@ Import it by double clicking and restart Chrome. The `AutoLaunchProtocolsFromOri For further questions or suggestions, please visit the [forum |https://forum.nette.org]. + +{{maintitle: Open Files in Your Editor from Tracy: IDE Integration}} +{{description: Click a file name on the Tracy error page and it opens in your editor on the right line. How to set this up on Windows, Linux and macOS, plus troubleshooting.}} diff --git a/tracy/en/recipes.texy b/tracy/en/recipes.texy index a2eee3c5a5..2702da7e8a 100644 --- a/tracy/en/recipes.texy +++ b/tracy/en/recipes.texy @@ -256,3 +256,6 @@ change it to: ```nginx try_files $uri $uri/ /index.php$is_args$args; ``` + +{{maintitle: Tracy Recipes: CSP, AJAX Debugging, Custom Logger, nginx}} +{{description: Practical recipes for the Tracy debugger: Content Security Policy, faster loading, debugging AJAX requests, a custom scrubber and logger, and nginx settings.}} diff --git a/tracy/en/stopwatch.texy b/tracy/en/stopwatch.texy index d6ddfbf442..3fc7f6de75 100644 --- a/tracy/en/stopwatch.texy +++ b/tracy/en/stopwatch.texy @@ -33,3 +33,6 @@ Debugger::timer(); // runs the timer echo Debugger::timer(); // elapsed time in seconds ``` + +{{maintitle: Measure PHP Execution Time with the Tracy Stopwatch}} +{{description: Measure how long your PHP code takes with the Tracy stopwatch: nanosecond precision, several independent timers and a simple call to Debugger::timer().}} diff --git a/tracy/en/upgrading.texy b/tracy/en/upgrading.texy index 41ac3f8f31..f941183188 100644 --- a/tracy/en/upgrading.texy +++ b/tracy/en/upgrading.texy @@ -8,3 +8,6 @@ Upgrading to Version 2.9 - Tracy no longer uses the native PHP session. It stores its data in its own temporary files and sends the key in the `tracy-session` cookie. Thanks to that Tracy no longer starts a session, so you can debug how your own application works with it. What else has changed on the iconic red screen is described in the article [Tracy 2.9 and evolution of the iconic screen |https://blog.nette.org/en/tracy-2-9-and-evolution-of-the-iconic-screen]. + +{{maintitle: Upgrading Tracy: What Changed in Version 2.9}} +{{description: What changed in Tracy 2.9: it no longer uses the native PHP session and stores its data in its own temporary files, which is worth knowing when upgrading.}} diff --git a/utils/cs/@home.texy b/utils/cs/@home.texy index 6cf2861ad4..d8d47349be 100644 --- a/utils/cs/@home.texy +++ b/utils/cs/@home.texy @@ -45,3 +45,6 @@ Platí pro poslední patch verze. Pokud aktualizujete balíček na novější verzi, podívejte se na stránku [upgrade|upgrading]. + +{{maintitle: Nette Utils: užitečné PHP třídy pro každodenní práci}} +{{description: Pole, řetězce, obrázky, JSON, soubory, datum a čas, validátory a další: šikovná sada PHP tříd pro každodenní použití, díky které nepíšete pořád dokola totéž.}} diff --git a/utils/cs/arrays.texy b/utils/cs/arrays.texy index 07c1a872dc..8a57f60382 100644 --- a/utils/cs/arrays.texy +++ b/utils/cs/arrays.texy @@ -559,3 +559,6 @@ Nový prvek lze přidat na začátek metodou `prepend()`: $list->prepend('d'); // ArrayList(0 => 'd', 1 => 'a', 2 => 'c') ``` + +{{maintitle: Práce s poli v PHP s Nette Utils: Arrays a ArrayList}} +{{description: Šikovné funkce pro práci s poli v PHP ze třídy Arrays a k tomu třídy ArrayHash a ArrayList pro práci s daty jako s objekty.}} diff --git a/utils/cs/callback.texy b/utils/cs/callback.texy index 94a1cf7bb2..f2ee95a303 100644 --- a/utils/cs/callback.texy +++ b/utils/cs/callback.texy @@ -91,3 +91,6 @@ $result = Callback::invokeSafe('file_get_contents', ['file.txt'], function (stri throw new Exception($message); }); ``` + +{{maintitle: Callbacky v PHP s Nette Utils: kontrola a převod}} +{{description: Práce s PHP callbacky: ověření platnosti, převod na řetězec nebo reflexi a rozbalení closure pomocí statické třídy Callback.}} diff --git a/utils/cs/datetime.texy b/utils/cs/datetime.texy index bbb580dc9e..649cd6e5f5 100644 --- a/utils/cs/datetime.texy +++ b/utils/cs/datetime.texy @@ -133,3 +133,6 @@ DateTime::relativeToSeconds('-1 hour'); // -3600 ``` Nakonec `DateTime` definuje konstanty `MINUTE`, `HOUR`, `DAY`, `WEEK`, `MONTH` a `YEAR` vyjadřující délku v sekundách; `MONTH` a `YEAR` jsou průměry, používejte je proto jen pro hrubé odhady. + +{{maintitle: Datum a čas v PHP: DateTime a DateTimeImmutable v Nette}} +{{description: Třídy pro datum a čas v Nette rozšiřují ty nativní z PHP a přidávají striktní validaci, snazší vytváření objektů a čistý výstup do řetězce a JSON.}} diff --git a/utils/cs/filesystem.texy b/utils/cs/filesystem.texy index 87e3ebab24..a9460226cf 100644 --- a/utils/cs/filesystem.texy +++ b/utils/cs/filesystem.texy @@ -234,3 +234,6 @@ class AnyClassUsingFileSystem // ... } ``` + +{{maintitle: Práce se soubory v PHP s Nette Utils: FileSystem s výjimkami}} +{{description: Kopírujte, přesouvejte, mažte, čtěte a zapisujte soubory a pracujte s cestami v PHP. Třída FileSystem na rozdíl od nativních funkcí při chybě vyhodí výjimku.}} diff --git a/utils/cs/finder.texy b/utils/cs/finder.texy index afde5c467b..8c38672b85 100644 --- a/utils/cs/finder.texy +++ b/utils/cs/finder.texy @@ -301,3 +301,6 @@ Výsledky si můžete nechat také vrátit jako pole objektů `Nette\Utils\FileI ```php $array = Finder::findFiles('*.php')->collect(); ``` + +{{maintitle: Hledání souborů v PHP s Nette Finder}} +{{description: Potřebujete najít soubory podle masky? Finder rychle prochází adresáře a umí filtrovat podle názvu, velikosti nebo data, rekurzivně i ve více složkách.}} diff --git a/utils/cs/floats.texy b/utils/cs/floats.texy index a421e4eb8e..3c8c967d1f 100644 --- a/utils/cs/floats.texy +++ b/utils/cs/floats.texy @@ -146,3 +146,6 @@ Floats::isInteger(-5.1); // false Floats::isInteger(INF); // false Floats::isInteger(NAN); // false ``` + +{{maintitle: Porovnávání desetinných čísel v PHP s Nette Utils}} +{{description: Proč se v PHP 0.1 + 0.2 nerovná 0.3? Třída Floats bezpečně porovnává desetinná čísla a nabízí pomocné funkce jako areEqual, isLessThan nebo isZero.}} diff --git a/utils/cs/helpers.texy b/utils/cs/helpers.texy index 6d4270c24d..e18f183aa9 100644 --- a/utils/cs/helpers.texy +++ b/utils/cs/helpers.texy @@ -95,3 +95,6 @@ Rozdělí celý název třídy v PHP na jmenný prostor a zkrácený název tř Helpers::splitClassName('Nette\Utils\Helpers'); // ['Nette\Utils', 'Helpers'] Helpers::splitClassName('Foo'); // ['', 'Foo'] ``` + +{{maintitle: Pomocné funkce v Nette Utils: clamp, compare, capture a další}} +{{description: Šikovní statičtí pomocníci pro PHP: zachycení výstupu do řetězce, omezení hodnoty na rozsah, porovnání hodnot, poslední chyba a návrh nejpodobnějšího řetězce.}} diff --git a/utils/cs/html-elements.texy b/utils/cs/html-elements.texy index 9c8a7f5c42..0f52077c90 100644 --- a/utils/cs/html-elements.texy +++ b/utils/cs/html-elements.texy @@ -352,3 +352,6 @@ HtmlStringable ============== Objekt `Nette\Utils\Html` implementuje rozhraní `Nette\HtmlStringable`, kterým například Latte nebo formuláře rozlišují objekty, které mají metodu `__toString()` vracející HTML kód. Takže nedojde k dvojímu escapování, pokud třeba objekt vypíšeme v šabloně pomocí `{$el}`. + +{{maintitle: Generování HTML v PHP: bezpečné elementy s Nette Utils}} +{{description: Generujte HTML kód v PHP pomocí třídy Html, která nedovolí vznik zranitelnosti XSS. Vytváření elementů, nastavení atributů a obsahu i převod HTML na text.}} diff --git a/utils/cs/images.texy b/utils/cs/images.texy index d0d3d4ee40..75c4d74731 100644 --- a/utils/cs/images.texy +++ b/utils/cs/images.texy @@ -709,3 +709,6 @@ Převede obraz truecolor na paletový. ([více |https://www.php.net/manual/en/fu ttfText(float $size, float $angle, int $x, int $y, ImageColor $color, string $fontFile, string $text, array $options=[]): array .[method] ----------------------------------------------------------------------------------------------------------------------------------------- Vypíše daný text do obrázku. ([více |https://www.php.net/manual/en/function.imagettftext]) + +{{maintitle: Změna velikosti a ořez obrázků v PHP s Nette Utils}} +{{description: Měňte velikost obrázků v PHP, ořezávejte je, doostřujte, spojujte, kreslete do nich a ukládejte jako JPEG, PNG, WebP nebo AVIF, to vše s třídou Image.}} diff --git a/utils/cs/iterables.texy b/utils/cs/iterables.texy index 0e4b930a9e..b800a8800a 100644 --- a/utils/cs/iterables.texy +++ b/utils/cs/iterables.texy @@ -189,3 +189,6 @@ $iterator = Iterables::toIterator($array); ``` Tato metoda je užitečná, když potřebujete zajistit, že máte k dispozici Iterator, bez ohledu na typ vstupních dat. Hodí se to při vytváření funkcí, které pracují s různými typy iterovatelných dat. + +{{maintitle: Práce s iterátory v PHP s Nette Utils: map, filter, first}} +{{description: Co umí funkce pro pole, to třída Iterables umí pro iterátory a generátory: filtrování, mapování, hledání prvního výskytu nebo memoizace výsledků.}} diff --git a/utils/cs/json.texy b/utils/cs/json.texy index ba3a37d5bb..4613d4a563 100644 --- a/utils/cs/json.texy +++ b/utils/cs/json.texy @@ -95,3 +95,6 @@ Jak odeslat JSON z presenteru? ============================== Lze k tomu použít metodu `$this->sendJson($data)`, kterou můžeme zavolat třeba v metodě `action*()`, viz [Odeslání odpovědi |application:presenters#Odeslání odpovědi]. + +{{maintitle: JSON v PHP s výjimkami: kódování a dekódování v Nette Utils}} +{{description: Kódujte a dekódujte JSON v PHP pomocí třídy Json, která při chybách vyhazuje výjimky. A k tomu jak odeslat JSON z presenteru v Nette.}} diff --git a/utils/cs/paginator.texy b/utils/cs/paginator.texy index 43b43c8c57..f3424dc713 100644 --- a/utils/cs/paginator.texy +++ b/utils/cs/paginator.texy @@ -63,3 +63,6 @@ $result = $database->query( ``` Příklad použití v aplikaci najdete v kuchařce [Stránkování výsledků databáze |best-practices:pagination]. + +{{maintitle: Stránkování v PHP s Nette Utils Paginator}} +{{description: Stránkovací matematika umí být zrádná. Paginator spočítá počet stránek, aktuální stránku, offset i limit pro vaše výpisy dat. Včetně příkladu s databází.}} diff --git a/utils/cs/process.texy b/utils/cs/process.texy index 3b93d63c2c..98729d2b92 100644 --- a/utils/cs/process.texy +++ b/utils/cs/process.texy @@ -396,3 +396,6 @@ Chyby se vždy hlásí vyhozením výjimky, nikdy návratovou hodnotou: | `Nette\NotSupportedException` | pokus o řetězení procesů na Windows `ProcessFailedException` a `ProcessTimeoutException` dědí z PHP `RuntimeException`. + +{{maintitle: Spouštění externích programů v PHP: Nette Process}} +{{description: Přívětivý obal nad proc_open(): spouštějte z PHP externí programy, posílejte jim vstup, sledujte výstup naživo, řetězte je a chyby dostávejte jako výjimky.}} diff --git a/utils/cs/random.texy b/utils/cs/random.texy index 0275704be2..a2f0645929 100644 --- a/utils/cs/random.texy +++ b/utils/cs/random.texy @@ -23,3 +23,6 @@ use Nette\Utils\Random; Random::generate(10); // '6zq3a1nl8n' Random::generate(5, 'A-Z'); // 'HLKUR' ``` + +{{maintitle: Generování náhodných řetězců v PHP s Nette Utils}} +{{description: Generujte kryptograficky bezpečné náhodné řetězce v PHP jediným voláním Random::generate() a zvolte si jejich délku i povolené znaky.}} diff --git a/utils/cs/reflection.texy b/utils/cs/reflection.texy index 92249fe044..10a1e29a12 100644 --- a/utils/cs/reflection.texy +++ b/utils/cs/reflection.texy @@ -173,3 +173,6 @@ echo Reflection::toString($param); // '$param in DemoClass::foo()' $prop = new ReflectionProperty('DemoClass', 'foo'); echo Reflection::toString($prop); // 'DemoClass::$foo' ``` + +{{maintitle: PHP reflexe v Nette Utils: pomocné funkce a klauzule use}} +{{description: Funkce, které doplňují nativní reflexi PHP a sjednocují ji napříč verzemi: rozvinutí názvů tříd, čtení klauzulí use a dohledání deklarace metody či property.}} diff --git a/utils/cs/smartobject.texy b/utils/cs/smartobject.texy index e5db1092d1..a1d25afcb2 100644 --- a/utils/cs/smartobject.texy +++ b/utils/cs/smartobject.texy @@ -242,3 +242,6 @@ Kvůli srozumitelnosti doporučujeme se magické metodě `$this->onChange()` vyh ```php Nette\Utils\Arrays::invoke($this->onChange, $this, $radius); ``` + +{{maintitle: Nette SmartObject: striktní objekty a properties v PHP}} +{{description: SmartObject po léta přidával objektům v PHP striktní kontrolu chyb a properties s kontrolovaným přístupem. Od PHP 8.4 jsou všechny jeho funkce součástí PHP.}} diff --git a/utils/cs/staticclass.texy b/utils/cs/staticclass.texy index cc4268dc16..5bd0c12d38 100644 --- a/utils/cs/staticclass.texy +++ b/utils/cs/staticclass.texy @@ -19,3 +19,6 @@ class Strings use Nette\StaticClass; } ``` + +{{maintitle: Statické třídy v PHP s traitou StaticClass z Nette}} +{{description: Třídy, u kterých se nepočítá s vytvářením instancí, označíte traitou StaticClass z Nette Utils. Krátká poznámka k jejímu použití.}} diff --git a/utils/cs/strings.texy b/utils/cs/strings.texy index 6a521df413..ede3666558 100644 --- a/utils/cs/strings.texy +++ b/utils/cs/strings.texy @@ -634,3 +634,6 @@ Strings::replace( ); // dumps ['ac', 'a', null, 'c'] ``` + +{{maintitle: Nette Utils Strings: práce s UTF-8 řetězci v PHP}} +{{description: Práce s UTF-8 řetězci v PHP: změna velikosti písmen, zkracování, ořezávání, převod kódování a regulární výrazy, které při chybě vyhazují výjimky.}} diff --git a/utils/cs/type.texy b/utils/cs/type.texy index c83f8a5daa..0a77146f0c 100644 --- a/utils/cs/type.texy +++ b/utils/cs/type.texy @@ -242,3 +242,6 @@ echo $type->with('int'); // 'string|int' // Přidání typu, který "přebije" vše ostatní echo $type->with('mixed'); // 'mixed' ``` + +{{maintitle: Analýza typů v PHP s Nette Utils: porovnání a zkoumání}} +{{description: Třída Type reprezentuje datový typ PHP z řetězce nebo reflexe. Analyzujte union a intersection typy, ověřujte kompatibilitu a kombinujte typy.}} diff --git a/utils/cs/upgrading.texy b/utils/cs/upgrading.texy index 7e60f32e3c..f10445fac6 100644 --- a/utils/cs/upgrading.texy +++ b/utils/cs/upgrading.texy @@ -77,3 +77,6 @@ Upgrade na verzi 2.3 - `Image::getFormatFromString()` je zastaralá - `Strings::chr()` a `normalize()` nyní fungují pouze s kódováním UTF-8 - `Strings::chr()` vyhodí `Nette\InvalidArgumentException`, pokud kód znaku není v platném rozsahu + +{{maintitle: Upgrade Nette Utils: změny v jednotlivých verzích}} +{{description: Co se změnilo v Nette Utils 4.0, 3.1, 3.0, 2.4 a 2.3 a jak upravit kód při přechodu na novější verzi.}} diff --git a/utils/cs/validators.texy b/utils/cs/validators.texy index 1c7b72df61..fdeb620118 100644 --- a/utils/cs/validators.texy +++ b/utils/cs/validators.texy @@ -327,3 +327,6 @@ Validators::isUri('https://nette.org'); // true Validators::isUri('mailto:gandalf@example.org'); // true Validators::isUri('nette.org'); // false ``` + +{{maintitle: Validace hodnot v PHP s Nette Utils: e-mail, URL a typy}} +{{description: Rychle ověřte, že je v proměnné platný e-mail, URL, číslo nebo očekávaný typ. Třída Validators nabízí i aserce, které při neúspěchu vyhodí výjimku.}} diff --git a/utils/en/@home.texy b/utils/en/@home.texy index 0098ef8cd6..ea1bf3e127 100644 --- a/utils/en/@home.texy +++ b/utils/en/@home.texy @@ -45,3 +45,6 @@ Applies to the latest patch versions. If you are upgrading to a newer version, see the [upgrading] page. + +{{maintitle: Nette Utils: Handy PHP Classes for Everyday Tasks}} +{{description: Arrays, strings, images, JSON, files, dates, validators and more: a handy set of PHP classes for everyday use that saves you from rewriting the same code.}} diff --git a/utils/en/arrays.texy b/utils/en/arrays.texy index 834552635a..0a44a5def3 100644 --- a/utils/en/arrays.texy +++ b/utils/en/arrays.texy @@ -559,3 +559,6 @@ You can add a new element to the beginning using the `prepend()` method: $list->prepend('d'); // ArrayList(0 => 'd', 1 => 'a', 2 => 'c') ``` + +{{maintitle: PHP Array Functions with Nette Utils: Arrays and ArrayList}} +{{description: Handy functions for working with arrays in PHP from the Arrays class, plus ArrayHash and ArrayList for working with data as objects.}} diff --git a/utils/en/callback.texy b/utils/en/callback.texy index 741d3e9582..bc4dc9f1d9 100644 --- a/utils/en/callback.texy +++ b/utils/en/callback.texy @@ -91,3 +91,6 @@ $result = Callback::invokeSafe('file_get_contents', ['file.txt'], function (stri throw new Exception($message); }); ``` + +{{maintitle: PHP Callbacks with Nette Utils: Check and Convert}} +{{description: Work with PHP callbacks: check that a callable is valid, convert it to a string or reflection, and unwrap closures with the static Callback class.}} diff --git a/utils/en/datetime.texy b/utils/en/datetime.texy index b3364d643b..884582633f 100644 --- a/utils/en/datetime.texy +++ b/utils/en/datetime.texy @@ -133,3 +133,6 @@ DateTime::relativeToSeconds('-1 hour'); // -3600 ``` Finally, `DateTime` defines the constants `MINUTE`, `HOUR`, `DAY`, `WEEK`, `MONTH` and `YEAR` expressing a length in seconds; `MONTH` and `YEAR` are averages, so use them only for rough estimates. + +{{maintitle: PHP DateTime and DateTimeImmutable in Nette Utils}} +{{description: Nette date classes extend the native PHP ones and add strict validation, easier object creation and clean output to strings and JSON.}} diff --git a/utils/en/filesystem.texy b/utils/en/filesystem.texy index d3b664c606..c9c53986a9 100644 --- a/utils/en/filesystem.texy +++ b/utils/en/filesystem.texy @@ -234,3 +234,6 @@ class AnyClassUsingFileSystem // ... } ``` + +{{maintitle: PHP File Functions with Exceptions: Nette Utils FileSystem}} +{{description: Copy, move, delete, read and write files and work with paths in PHP. Unlike the native functions, the FileSystem class throws exceptions on errors.}} diff --git a/utils/en/finder.texy b/utils/en/finder.texy index 2995a43663..924c58ffb2 100644 --- a/utils/en/finder.texy +++ b/utils/en/finder.texy @@ -301,3 +301,6 @@ You can also retrieve the results as an array of `Nette\Utils\FileInfo` objects ```php $array = Finder::findFiles('*.php')->collect(); ``` + +{{maintitle: Finding Files in PHP with Nette Finder}} +{{description: Need to find files matching a mask? Finder browses directories quickly and lets you filter by name, size or date, recursively and across several folders.}} diff --git a/utils/en/floats.texy b/utils/en/floats.texy index 1383532283..6409e699f9 100644 --- a/utils/en/floats.texy +++ b/utils/en/floats.texy @@ -146,3 +146,6 @@ Floats::isInteger(-5.1); // false Floats::isInteger(INF); // false Floats::isInteger(NAN); // false ``` + +{{maintitle: PHP Float Comparison with Nette Utils: Why == Fails}} +{{description: Why does 0.1 + 0.2 not equal 0.3 in PHP? The Floats class compares floating-point numbers safely, with helpers such as areEqual, isLessThan and isZero.}} diff --git a/utils/en/helpers.texy b/utils/en/helpers.texy index d71b6c0f4b..2553f5ef28 100644 --- a/utils/en/helpers.texy +++ b/utils/en/helpers.texy @@ -95,3 +95,6 @@ Splits a PHP class name into a namespace and a short class name. Returns an arra Helpers::splitClassName('Nette\Utils\Helpers'); // ['Nette\Utils', 'Helpers'] Helpers::splitClassName('Foo'); // ['', 'Foo'] ``` + +{{maintitle: Nette Utils Helpers: clamp, compare, capture and More}} +{{description: Handy static helpers for PHP: capture output to a string, clamp a value to a range, compare values, get the last error and suggest the closest string.}} diff --git a/utils/en/html-elements.texy b/utils/en/html-elements.texy index 1289149ec7..295525e849 100644 --- a/utils/en/html-elements.texy +++ b/utils/en/html-elements.texy @@ -352,3 +352,6 @@ HtmlStringable ============== The `Nette\Utils\Html` object implements the `Nette\HtmlStringable` interface. Latte and Forms use this interface, for example, to distinguish objects that have a `__toString()` method returning HTML code. This prevents double escaping if, for example, you print the object in a template using `{$el}`. + +{{maintitle: PHP HTML Generator: Safe HTML Elements with Nette Utils}} +{{description: Generate HTML code in PHP with the Html class, which prevents XSS vulnerabilities. Create elements, set attributes and content and convert HTML to text.}} diff --git a/utils/en/images.texy b/utils/en/images.texy index cefdc12ba2..61df425b99 100644 --- a/utils/en/images.texy +++ b/utils/en/images.texy @@ -709,3 +709,6 @@ Converts a truecolor image to a palette image. ([more |https://www.php.net/manua ttfText(float $size, float $angle, int $x, int $y, ImageColor $color, string $fontFile, string $text, array $options=[]): array .[method] ----------------------------------------------------------------------------------------------------------------------------------------- Writes the given text into the image. ([more |https://www.php.net/manual/en/function.imagettftext]) + +{{maintitle: PHP Image Resize and Crop with Nette Utils}} +{{description: Resize, crop, sharpen and merge images in PHP, draw on them and save them as JPEG, PNG, WebP or AVIF, all with the simple Image class.}} diff --git a/utils/en/iterables.texy b/utils/en/iterables.texy index d090059352..84ccc0524e 100644 --- a/utils/en/iterables.texy +++ b/utils/en/iterables.texy @@ -189,3 +189,6 @@ $iterator = Iterables::toIterator($array); ``` This method is useful when you need to ensure you have an Iterator available, regardless of the input data type. This can be helpful when creating functions that work with various types of iterable data. + +{{maintitle: PHP Iterable Functions in Nette Utils: map, filter, first}} +{{description: What array functions do for arrays, the Iterables class does for iterators and generators: filter, map, find the first match or memoize their results.}} diff --git a/utils/en/json.texy b/utils/en/json.texy index b2ad8d7e82..4a7ced4898 100644 --- a/utils/en/json.texy +++ b/utils/en/json.texy @@ -95,3 +95,6 @@ How to Send JSON from a Presenter? ================================== You can use the `$this->sendJson($data)` method, which can be called, for example, within an `action*()` method. See [Sending a Response |application:presenters#Sending a Response]. + +{{maintitle: PHP JSON Encode and Decode with Exceptions: Nette Utils}} +{{description: Encode and decode JSON in PHP with the Json class, which throws exceptions on errors. Plus how to send JSON from a Nette presenter.}} diff --git a/utils/en/paginator.texy b/utils/en/paginator.texy index e020f670a7..f97969aec3 100644 --- a/utils/en/paginator.texy +++ b/utils/en/paginator.texy @@ -63,3 +63,6 @@ $result = $database->query( ``` An example of usage in an application can be found in the cookbook [Paginating Database Results|best-practices:pagination]. + +{{maintitle: PHP Pagination with Nette Utils Paginator}} +{{description: Pagination math can be tricky. Paginator calculates the number of pages, the current page, offset and limit for your data listings. With a database example.}} diff --git a/utils/en/process.texy b/utils/en/process.texy index 733bec14fd..582921f12e 100644 --- a/utils/en/process.texy +++ b/utils/en/process.texy @@ -396,3 +396,6 @@ Errors are always reported by throwing an exception, never by a return value: | `Nette\NotSupportedException` | process piping was attempted on Windows `ProcessFailedException` and `ProcessTimeoutException` extend PHP's `RuntimeException`. + +{{maintitle: Run External Programs in PHP: Nette Process and proc_open}} +{{description: A friendly wrapper around proc_open(): run external programs from PHP, send input, watch output live, chain processes and get errors as exceptions.}} diff --git a/utils/en/random.texy b/utils/en/random.texy index cb17d6ba96..4d13cc69de 100644 --- a/utils/en/random.texy +++ b/utils/en/random.texy @@ -23,3 +23,6 @@ use Nette\Utils\Random; Random::generate(10); // '6zq3a1nl8n' Random::generate(5, 'A-Z'); // 'HLKUR' ``` + +{{maintitle: PHP Random String Generator with Nette Utils}} +{{description: Generate cryptographically secure random strings in PHP with a single call to Random::generate(), and choose their length and the allowed characters.}} diff --git a/utils/en/reflection.texy b/utils/en/reflection.texy index 5b4fd56828..778db597c5 100644 --- a/utils/en/reflection.texy +++ b/utils/en/reflection.texy @@ -173,3 +173,6 @@ echo Reflection::toString($param); // '$param in DemoClass::foo()' $prop = new ReflectionProperty('DemoClass', 'foo'); echo Reflection::toString($prop); // 'DemoClass::$foo' ``` + +{{maintitle: PHP Reflection Helpers in Nette Utils: use Statements}} +{{description: Helpers that fill gaps in native PHP reflection and unify it across versions: expand class names, read use statements, find where a method is declared.}} diff --git a/utils/en/smartobject.texy b/utils/en/smartobject.texy index 100009a788..76b3dfc72f 100644 --- a/utils/en/smartobject.texy +++ b/utils/en/smartobject.texy @@ -242,3 +242,6 @@ For clarity, we recommend avoiding the magic `$this->onChange()` method. A pract ```php Nette\Utils\Arrays::invoke($this->onChange, $this, $radius); ``` + +{{maintitle: Nette SmartObject: Strict Objects and Properties in PHP}} +{{description: For years, SmartObject gave PHP objects strict error checks and controlled properties. Since PHP 8.4 all of its features are a native part of PHP.}} diff --git a/utils/en/staticclass.texy b/utils/en/staticclass.texy index d68b70954c..febd0448c0 100644 --- a/utils/en/staticclass.texy +++ b/utils/en/staticclass.texy @@ -19,3 +19,6 @@ class Strings use Nette\StaticClass; } ``` + +{{maintitle: Static Classes in PHP with the Nette StaticClass Trait}} +{{description: Classes that are not meant to be instantiated can be marked with the StaticClass trait from Nette Utils. A short note on how to use it.}} diff --git a/utils/en/strings.texy b/utils/en/strings.texy index 5052a1967d..ec2fc21611 100644 --- a/utils/en/strings.texy +++ b/utils/en/strings.texy @@ -634,3 +634,6 @@ Strings::replace( ); // dumps ['ac', 'a', null, 'c'] ``` + +{{maintitle: PHP UTF-8 String Functions and Regex in Nette Utils}} +{{description: Work with UTF-8 strings in PHP: change letter case, truncate, trim, pad, convert encoding and use regular expressions that throw exceptions on errors.}} diff --git a/utils/en/type.texy b/utils/en/type.texy index 29901b4e88..7e3458a892 100644 --- a/utils/en/type.texy +++ b/utils/en/type.texy @@ -242,3 +242,6 @@ echo $type->with('int'); // 'string|int' // Adding a type that supersedes everything echo $type->with('mixed'); // 'mixed' ``` + +{{maintitle: PHP Type Analysis with Nette Utils: Compare and Inspect}} +{{description: The Type class represents a PHP data type from a string or reflection. Analyze union and intersection types, test compatibility and combine types.}} diff --git a/utils/en/upgrading.texy b/utils/en/upgrading.texy index 4cc2f41d80..bbd766ba1f 100644 --- a/utils/en/upgrading.texy +++ b/utils/en/upgrading.texy @@ -77,3 +77,6 @@ Upgrading to Version 2.3 - `Image::getFormatFromString()` is deprecated - `Strings::chr()` and `normalize()` now work only with UTF-8 encoding - `Strings::chr()` throws `Nette\InvalidArgumentException` if the code point is not in the valid range + +{{maintitle: Upgrading Nette Utils: What Changed in Each Version}} +{{description: What changed in Nette Utils 4.0, 3.1, 3.0, 2.4 and 2.3, and how to update your code when moving to a newer version.}} diff --git a/utils/en/validators.texy b/utils/en/validators.texy index 649f657241..3f2c9e3d6a 100644 --- a/utils/en/validators.texy +++ b/utils/en/validators.texy @@ -327,3 +327,6 @@ Validators::isUri('https://nette.org'); // true Validators::isUri('mailto:gandalf@example.org'); // true Validators::isUri('nette.org'); // false (missing scheme) ``` + +{{maintitle: PHP Value Validators in Nette Utils: Email, URL and Types}} +{{description: Quickly check that a variable holds a valid email, URL, number or expected type. The Validators class also offers assertions that throw an exception on failure.}} diff --git a/www/cs/10-reasons-why-nette.texy b/www/cs/10-reasons-why-nette.texy index 45d25b3211..425251089c 100644 --- a/www/cs/10-reasons-why-nette.texy +++ b/www/cs/10-reasons-why-nette.texy @@ -89,4 +89,5 @@ Máte otázky? Obraťte se na stránku s [častými dotazy|nette:troubleshooting **Seznamte se s frameworkem, který vás bude rozmazlovat, vést a inspirovat.** - +{{maintitle: 7 důvodů, proč si vybrat PHP framework Nette}} +{{description: PHP framework, který vám dovolí soustředit se na to, co děláte nejraději, vede vás k čistému kódu a sám dbá na bezpečnost. Sedm důvodů, proč zvolit Nette.}} diff --git a/www/cs/@home.texy b/www/cs/@home.texy index d9916661ec..db0633b65c 100644 --- a/www/cs/@home.texy +++ b/www/cs/@home.texy @@ -1,3 +1,3 @@ -{{maintitle:Nette – Pohodlný a bezpečný vývoj webových aplikací v PHP}} -{{description: Nette je rodina vyspělých a samostatně použitelných komponent pro PHP. Nechte se jimi nadchnout. Dohromady tvoří framework, vyhodnocený jako 3. nejpopulárnější na světě. Filosofie Nette klade mimořádný důraz na produktivitu, nejlepší postupy a bezpečnost.}} {{leftbar: no}} +{{maintitle: Nette – Pohodlný a bezpečný vývoj webových aplikací v PHP}} +{{description: Nette je rodina vyspělých, samostatně použitelných PHP komponent. Dohromady tvoří framework s důrazem na produktivitu, nejlepší postupy a bezpečnost.}} diff --git a/www/cs/donate.texy b/www/cs/donate.texy index 124d6be8f1..a5ff07f242 100644 --- a/www/cs/donate.texy +++ b/www/cs/donate.texy @@ -18,3 +18,6 @@ Partnerům vystavujeme faktury, aby si mohli podporu dát do nákladů, a to bu {{include: buttons}} + +{{maintitle: Podpořte vývoj Nette: staňte se partnerem}} +{{description: Podpořte PHP framework, na kterém stojí vaše aplikace. Staňte se partnerem Nette, pomozte financovat podporu nových verzí PHP a opravy chyb a získejte výhody.}} diff --git a/www/cs/history.texy b/www/cs/history.texy index 03dfa57121..c84d361f49 100644 --- a/www/cs/history.texy +++ b/www/cs/history.texy @@ -35,3 +35,5 @@ Nette se také umístilo na úžasném 3. místě v celosvětové anketě o nejl {{toc:no}} +{{maintitle: Historie Nette: jak PHP framework vznikal}} +{{description: Počátky Nette sahají do roku 2004, kdy David Grudl hledal vhodný framework pro psaní aplikací. Přečtěte si, jak se Nette od té doby vyvíjelo.}} diff --git a/www/cs/license.texy b/www/cs/license.texy index 3e314dec6c..82b03f7c39 100644 --- a/www/cs/license.texy +++ b/www/cs/license.texy @@ -42,3 +42,5 @@ Znění GPL licencí jsou velmi dlouhá, proto jsou zde uvedeny odkazy na ně: {{toc:yes}} {{priority: -2}} +{{maintitle: Licence Nette: New BSD, nebo GNU GPL 2 a 3}} +{{description: Nette Framework je svobodný software: vyberte si licenci New BSD, nebo GNU GPL verze 2 či 3. Co která umožňuje a jak smíte používat ochrannou známku Nette.}} diff --git a/www/cs/logo.texy b/www/cs/logo.texy index 2c896d643c..3910690517 100644 --- a/www/cs/logo.texy +++ b/www/cs/logo.texy @@ -58,3 +58,5 @@ Reprodukce loga Nette Framework bude vypadat nejlépe, pokud zachováte oficiál ---------- .[clear] {{priority: -2}} +{{maintitle: Loga a grafika Nette: oficiální podklady ke stažení}} +{{description: Potřebujete oficiální logo Nette Framework nebo ikonku na své stránky? Stáhněte si logo a grafiku a podívejte se, jak správně psát a používat název frameworku.}} diff --git a/www/cs/maintenance.texy b/www/cs/maintenance.texy index 980bd92d3a..7aa668c57e 100644 --- a/www/cs/maintenance.texy +++ b/www/cs/maintenance.texy @@ -23,4 +23,5 @@ Kompatibilita platí vždy pro nejnovější vydání z každé řady. {{toc: no}} -{{description: Vydání Nette, roadmap, tabulky údržby a kompatibilita s PHP}} +{{maintitle: Údržba Nette a kompatibilita s PHP: roadmap a podpora LTS}} +{{description: Vydání Nette, roadmap, tabulky údržby a kompatibilita s PHP. Každá větev je LTS vydání s podporou nejméně 2 roky.}} diff --git a/www/cs/packages.texy b/www/cs/packages.texy index 2188c28eb2..97fb426f76 100644 --- a/www/cs/packages.texy +++ b/www/cs/packages.texy @@ -25,3 +25,5 @@ Seznam balíčků Nette | **Utils**:[utils:] | Základní třídy a nástroje | [GitHub |https://github.com/nette/utils] [API |https://api.nette.org/utils/] {{toc: no}} +{{maintitle: Balíčky Nette: seznam všech PHP knihoven}} +{{description: Všechny balíčky Nette na jednom místě: application, DI, databáze, formuláře, Latte, Tracy a další, každý s krátkým popisem a odkazy na GitHub a API.}} diff --git a/www/cs/security-warning.texy b/www/cs/security-warning.texy index 5210e9d9c4..1c528394d6 100644 --- a/www/cs/security-warning.texy +++ b/www/cs/security-warning.texy @@ -9,3 +9,6 @@ Jak zjistíte, že je soubor chráněný? Můžete se pokusit jej otevřít v pr Ochránit kritické adresáře před přístupem z webu je vaše zodpovědnost. Tyto adresáře musí být umístěné MIMO veřejnou složku (tzv. document root). Pokud by váš hosting neumožňoval vytvářet složky o úroveň výš nad veřejným adresářem, poohlédněte se po jiném hostingu. Jinak vám hrozí značné bezpečnostní riziko. + +{{maintitle: Bezpečnostní varování Nette: ochrana config.neon a app}} +{{description: Je nesmírně důležité, aby soubor config.neon a adresáře app a log nebyly dostupné z prohlížeče. Jinak může kdokoliv vidět vaše hesla a další citlivá data.}} diff --git a/www/cs/terms-of-use.texy b/www/cs/terms-of-use.texy index dc0445c7c0..61ecf0c390 100644 --- a/www/cs/terms-of-use.texy +++ b/www/cs/terms-of-use.texy @@ -26,3 +26,5 @@ Nikdo z autorů, přispěvatelů, sponzorů, správců, ani kdokoli jiný spojen Provozovatel nenese vůči jiným subjektům odpovědnost za přímé, nepřímé, mimořádné nebo jiné následné škody, způsobené použitím informací získaných prostřednictvím provozovaného serveru, včetně (ale ne výhradně) ušlého zisku, vynaložených nákladů, přerušení činnosti a dalších škod. {{priority: -2}} +{{maintitle: Právní doložka Nette: osobní údaje a autorská práva}} +{{description: Jak web nette.org nakládá s osobními údaji podle zákonů České republiky a jak autorské právo chrání jeho obsah.}} diff --git a/www/en/10-reasons-why-nette.texy b/www/en/10-reasons-why-nette.texy index decccd7b2c..fe4283aca7 100644 --- a/www/en/10-reasons-why-nette.texy +++ b/www/en/10-reasons-why-nette.texy @@ -89,4 +89,5 @@ Do you have questions? Visit the [frequently asked questions |nette:troubleshoot **Get to know the framework that will pamper, guide, and inspire you.** - +{{maintitle: 7 Reasons to Use Nette: Why Choose This PHP Framework}} +{{description: A PHP framework that lets you focus on what you love, guides you to clean code and takes care of security itself. Seven reasons to choose Nette.}} diff --git a/www/en/@home.texy b/www/en/@home.texy index 2f5e54db85..2fb6567ff2 100644 --- a/www/en/@home.texy +++ b/www/en/@home.texy @@ -1,3 +1,3 @@ -{{maintitle:Nette – Comfortable and Safe Web Development in PHP}} -{{description: Nette is a family of mature and stand-alone components for PHP. Let them inspire you. Together, they create a framework rated as the 3rd most popular in the world. The Nette philosophy places extraordinary emphasis on productivity, best practices, and security.}} {{leftbar: no}} +{{maintitle: Nette – Comfortable and Safe Web Development in PHP}} +{{description: Nette is a family of mature, stand-alone PHP components. Together they form a framework with an emphasis on productivity, best practices and security.}} diff --git a/www/en/donate.texy b/www/en/donate.texy index 2e3b8cbaf1..341440fec9 100644 --- a/www/en/donate.texy +++ b/www/en/donate.texy @@ -18,3 +18,6 @@ We issue invoices to partners so they can include the support in their expenses, {{include: buttons}} + +{{maintitle: Sponsor Nette Development: Become a Partner}} +{{description: Support the PHP framework your applications rely on. Become a Nette partner, help fund new PHP version support and bug fixes and get exclusive benefits.}} diff --git a/www/en/history.texy b/www/en/history.texy index 82013fa6f2..44e9d87680 100644 --- a/www/en/history.texy +++ b/www/en/history.texy @@ -35,3 +35,5 @@ Nette also achieved an impressive 3rd place in the global poll for the best PHP {{toc:no}} +{{maintitle: History of Nette: How the PHP Framework Came to Be}} +{{description: The origins of Nette date back to 2004, when David Grudl began searching for a suitable framework for writing applications. How it evolved over the years.}} diff --git a/www/en/license.texy b/www/en/license.texy index 6d651d320d..3ce7a4d5d2 100644 --- a/www/en/license.texy +++ b/www/en/license.texy @@ -42,3 +42,5 @@ The texts of the GPL licenses are very long, so links are provided here instead: {{toc:yes}} {{priority: -2}} +{{maintitle: Nette License: New BSD or GNU GPL 2 and 3}} +{{description: Nette Framework is free software: choose the New BSD license or GNU GPL version 2 or 3. What each one allows and how the Nette Framework trademark may be used.}} diff --git a/www/en/logo.texy b/www/en/logo.texy index 2f807c304d..bed4861bc1 100644 --- a/www/en/logo.texy +++ b/www/en/logo.texy @@ -58,3 +58,5 @@ The Nette Framework logo reproduction will look best if you keep the official co ---------- .[clear] {{priority: -2}} +{{maintitle: Nette Logos and Graphics: Official Downloads}} +{{description: Need the official Nette Framework logo or an icon for your website? Download logos and graphics and see how to write and use the framework name.}} diff --git a/www/en/maintenance.texy b/www/en/maintenance.texy index 039ff07f90..6e6f64bae4 100644 --- a/www/en/maintenance.texy +++ b/www/en/maintenance.texy @@ -23,4 +23,5 @@ Compatibility always applies to the latest patch release within each minor versi {{toc: no}} -{{description: Nette releases, roadmap, maintenance schedule, and PHP compatibility tables}} +{{maintitle: Nette Maintenance and PHP Versions: Roadmap, LTS Support}} +{{description: Nette releases, roadmap, maintenance schedule and PHP compatibility tables. Each branch is an LTS release with support for at least 2 years.}} diff --git a/www/en/packages.texy b/www/en/packages.texy index 87c2a6e653..73a8e57d79 100644 --- a/www/en/packages.texy +++ b/www/en/packages.texy @@ -25,3 +25,5 @@ List of Packages | **Utils**:[utils:] | Essential classes and utilities | [GitHub |https://github.com/nette/utils] [API |https://api.nette.org/utils/] {{toc: no}} +{{maintitle: Nette Packages: List of All PHP Libraries}} +{{description: All Nette packages at a glance: application, DI, database, forms, Latte, Tracy and others, each with a short description and links to GitHub and the API.}} diff --git a/www/en/security-warning.texy b/www/en/security-warning.texy index d2bdd8f6da..eecaa58e7b 100644 --- a/www/en/security-warning.texy +++ b/www/en/security-warning.texy @@ -9,3 +9,6 @@ How do you know if a file is protected? You can try to open it in a browser. If It is your responsibility to protect critical directories from access from the web. These directories must be located OUTSIDE the public folder (called document root). If your hosting does not allow you to create folders one level above the public directory, find another hosting. Otherwise, you run a significant security risk. + +{{maintitle: Nette Security Warning: Protect config.neon and app}} +{{description: It is extremely important that config.neon and the app and log directories are not accessible from a web browser. Otherwise anyone can see your passwords.}} diff --git a/www/en/terms-of-use.texy b/www/en/terms-of-use.texy index 030b217fbc..d0c1413319 100644 --- a/www/en/terms-of-use.texy +++ b/www/en/terms-of-use.texy @@ -26,3 +26,5 @@ Any of the authors, contributors, sponsors, administrators, or anyone else assoc The operator shall not be liable to other entities for direct, indirect, extraordinary or other consequential damages caused by the use of information obtained through the server operated, including (but not limited to) lost profits, costs incurred, interruption of activity and other damages. {{priority: -2}} +{{maintitle: Nette Legal Clause: Personal Data and Copyright}} +{{description: How nette.org handles personal data under the laws of the Czech Republic, and the copyright that protects the content of this website.}} From 2ca15b541797c17451b6bb87bf49e6f897d2a56e Mon Sep 17 00:00:00 2001 From: David Grudl Date: Sat, 7 Nov 2026 14:19:02 +0100 Subject: [PATCH 2/7] examples write a comma between the destination and the arguments of {control}, {link}, n:href and {define} 1560d87b-943f-441c-9a0d-a31da9129126 --- application/cs/ajax.texy | 2 +- application/cs/components.texy | 10 +++++----- application/cs/creating-links.texy | 6 +++--- application/cs/how-it-works.texy | 2 +- application/cs/presenters.texy | 8 ++++---- application/de/ajax.texy | 2 +- application/de/components.texy | 10 +++++----- application/de/creating-links.texy | 6 +++--- application/de/how-it-works.texy | 2 +- application/de/presenters.texy | 8 ++++---- application/en/ajax.texy | 2 +- application/en/components.texy | 10 +++++----- application/en/creating-links.texy | 6 +++--- application/en/how-it-works.texy | 2 +- application/en/presenters.texy | 8 ++++---- application/es/ajax.texy | 2 +- application/es/components.texy | 10 +++++----- application/es/creating-links.texy | 6 +++--- application/es/how-it-works.texy | 2 +- application/es/presenters.texy | 8 ++++---- application/fr/ajax.texy | 2 +- application/fr/components.texy | 10 +++++----- application/fr/creating-links.texy | 8 ++++---- application/fr/how-it-works.texy | 2 +- application/fr/presenters.texy | 8 ++++---- application/it/ajax.texy | 2 +- application/it/components.texy | 10 +++++----- application/it/creating-links.texy | 6 +++--- application/it/how-it-works.texy | 2 +- application/it/presenters.texy | 8 ++++---- application/ja/ajax.texy | 2 +- application/ja/components.texy | 10 +++++----- application/ja/creating-links.texy | 6 +++--- application/ja/how-it-works.texy | 2 +- application/ja/presenters.texy | 8 ++++---- application/pl/ajax.texy | 2 +- application/pl/components.texy | 10 +++++----- application/pl/creating-links.texy | 6 +++--- application/pl/how-it-works.texy | 2 +- application/pl/presenters.texy | 8 ++++---- application/ru/ajax.texy | 2 +- application/ru/components.texy | 10 +++++----- application/ru/creating-links.texy | 6 +++--- application/ru/how-it-works.texy | 2 +- application/ru/presenters.texy | 8 ++++---- application/tr/ajax.texy | 2 +- application/tr/components.texy | 10 +++++----- application/tr/creating-links.texy | 6 +++--- application/tr/how-it-works.texy | 2 +- application/tr/presenters.texy | 8 ++++---- best-practices/cs/dynamic-snippets.texy | 8 ++++---- best-practices/cs/post-links.texy | 4 ++-- best-practices/de/dynamic-snippets.texy | 8 ++++---- best-practices/de/post-links.texy | 4 ++-- best-practices/en/dynamic-snippets.texy | 8 ++++---- best-practices/en/post-links.texy | 4 ++-- best-practices/es/dynamic-snippets.texy | 8 ++++---- best-practices/es/post-links.texy | 4 ++-- best-practices/fr/dynamic-snippets.texy | 8 ++++---- best-practices/fr/post-links.texy | 4 ++-- best-practices/it/dynamic-snippets.texy | 8 ++++---- best-practices/it/post-links.texy | 4 ++-- best-practices/ja/dynamic-snippets.texy | 8 ++++---- best-practices/ja/post-links.texy | 4 ++-- best-practices/pl/dynamic-snippets.texy | 8 ++++---- best-practices/pl/post-links.texy | 4 ++-- best-practices/ru/dynamic-snippets.texy | 8 ++++---- best-practices/ru/post-links.texy | 4 ++-- best-practices/tr/dynamic-snippets.texy | 8 ++++---- best-practices/tr/post-links.texy | 4 ++-- latte/cs/cookbook/passing-variables.texy | 2 +- latte/de/cookbook/passing-variables.texy | 2 +- latte/en/cookbook/passing-variables.texy | 2 +- latte/es/cookbook/passing-variables.texy | 2 +- latte/fr/cookbook/passing-variables.texy | 2 +- latte/it/cookbook/passing-variables.texy | 2 +- latte/ja/cookbook/passing-variables.texy | 2 +- latte/pl/cookbook/passing-variables.texy | 2 +- latte/ru/cookbook/passing-variables.texy | 2 +- latte/tr/cookbook/passing-variables.texy | 2 +- quickstart/cs/creating-posts.texy | 2 +- quickstart/cs/single-post.texy | 4 ++-- quickstart/de/creating-posts.texy | 2 +- quickstart/de/single-post.texy | 4 ++-- quickstart/en/creating-posts.texy | 2 +- quickstart/en/single-post.texy | 4 ++-- quickstart/es/creating-posts.texy | 2 +- quickstart/es/single-post.texy | 4 ++-- quickstart/fr/creating-posts.texy | 2 +- quickstart/fr/single-post.texy | 4 ++-- quickstart/it/creating-posts.texy | 2 +- quickstart/it/single-post.texy | 4 ++-- quickstart/ja/creating-posts.texy | 2 +- quickstart/ja/single-post.texy | 4 ++-- quickstart/pl/creating-posts.texy | 2 +- quickstart/pl/single-post.texy | 4 ++-- quickstart/ru/creating-posts.texy | 2 +- quickstart/ru/single-post.texy | 4 ++-- quickstart/tr/creating-posts.texy | 2 +- quickstart/tr/single-post.texy | 4 ++-- 100 files changed, 241 insertions(+), 241 deletions(-) diff --git a/application/cs/ajax.texy b/application/cs/ajax.texy index 8174051dc0..5f0c89bf28 100644 --- a/application/cs/ajax.texy +++ b/application/cs/ajax.texy @@ -209,7 +209,7 @@ OK {control productGrid} nebude fungovat: -{control productGrid $arg, $arg} +{control productGrid, $arg, $arg} {control productGrid:paginator} ``` diff --git a/application/cs/components.texy b/application/cs/components.texy index d249f2fcdb..fb4be07928 100644 --- a/application/cs/components.texy +++ b/application/cs/components.texy @@ -107,7 +107,7 @@ public function render(): void Značka `{control}` umožňuje do metody `render()` předat parametry: ```latte -{control poll $id, $message} +{control poll, $id, $message} ``` ```php .{file:PollControl.php} @@ -136,7 +136,7 @@ Pro lepší pochopení je dobré vědět, jak se tato značka přeloží do PHP. ```latte {control poll} -{control poll:paginator 123, 'hello'} +{control poll:paginator, 123, 'hello'} ``` se přeloží jako: @@ -200,7 +200,7 @@ public function handleClick(int $x, int $y): void Odkaz, který zavolá signál, vytvoříme obvyklým způsobem, tedy v šabloně atributem `n:href` nebo značkou `{link}`, v kódu metodou `link()`. Více v kapitole [Vytváření odkazů URL |creating-links#Odkazy na signál]. ```latte -click here +click here ``` Signál se vždy volá na aktuálním presenteru a akci, není možné jej vyvolat na jiném presenteru nebo jiné akci. @@ -281,13 +281,13 @@ U property doporučujeme uvádět i datový typ (např. `int`) a můžete uvést Při vytváření odkazu lze persistentnímu parametru změnit hodnotu: ```latte -next +next ``` Nebo jej lze *vyresetovat*, tj. odstranit z URL. Pak bude nabývat svou výchozí hodnotu: ```latte -reset +reset ``` diff --git a/application/cs/creating-links.texy b/application/cs/creating-links.texy index 6cc1a6fdef..126a11240a 100644 --- a/application/cs/creating-links.texy +++ b/application/cs/creating-links.texy @@ -29,13 +29,13 @@ Všimněte si, že místo HTML atributu `href` jsme použili [n:atribut |latte:s Kliknutí na odkaz je, zjednodušeně řečeno, něco jako zavolání metody `ProductPresenter::renderShow()`. A pokud má ve své signatuře parametry, můžeme ji volat s argumenty: ```latte -detail produktu +detail produktu ``` Je možné předávat i pojmenované parametry. Následující odkaz předává parametr `lang` s hodnotou `cs`: ```latte -detail produktu +detail produktu ``` Pokud metoda `ProductPresenter::renderShow()` nemá `$lang` ve své signatuře, může si hodnotu parametru zjistit pomocí `$lang = $this->getParameter('lang')` nebo z [property |presenters#Parametry požadavku]. @@ -162,7 +162,7 @@ Zároveň se přenáší i všechny parametry uvedené v signatuře metody `acti Samozřejmě je možné parametry uvést přímo: ```latte -refresh +refresh ``` Funkce `isLinkCurrent()` zjišťuje, zda je cíl odkazu shodný s aktuální stránkou. Toho lze využít například v šabloně k odlišení odkazů apod. diff --git a/application/cs/how-it-works.texy b/application/cs/how-it-works.texy index 58d62dcb4c..4a52c576b3 100644 --- a/application/cs/how-it-works.texy +++ b/application/cs/how-it-works.texy @@ -150,7 +150,7 @@ Když už přišla řeč na šablony, v Nette se používá šablonovací systé V šabloně se [vytvářejí odkazy |creating-links] na další presentery a akce takto: ```latte -detail produktu +detail produktu ``` Prostě místo reálného URL napíšete známý pár `Presenter:action` a uvedete případné parametry. Trik je v tom `n:href`, které říká, že tento atribut zpracuje Nette. A vygeneruje: diff --git a/application/cs/presenters.texy b/application/cs/presenters.texy index 186bf5777f..2af57b46df 100644 --- a/application/cs/presenters.texy +++ b/application/cs/presenters.texy @@ -164,7 +164,7 @@ $url = $this->link('Product:show', [$id, 'lang' => 'cs']); V šabloně se vytvářejí odkazy na další presentery a akce tímto způsobem: ```latte -detail produktu +detail produktu ``` Prostě místo reálného URL napíšete známý pár `Presenter:action` a uvedete případné parametry. Trik je v tom `n:href`, které říká, že tento atribut zpracuje Latte a vygeneruje reálné URL. V Nette tak vůbec nemusíte uvažovat nad URL, jen nad presentery a akcemi. @@ -282,7 +282,7 @@ U property doporučujeme uvádět i datový typ (např. `string`) a Nette podle Při vytváření odkazu lze parametrům hodnotu přímo nastavit: ```latte -click +click ``` @@ -330,13 +330,13 @@ class ProductPresenter extends Nette\Application\UI\Presenter Při vytváření odkazu lze persistentnímu parametru změnit hodnotu: ```latte -detail v češtině +detail v češtině ``` Nebo jej lze *vyresetovat*, tj. odstranit z URL. Pak bude nabývat svou výchozí hodnotu: ```latte -klikni +klikni ``` diff --git a/application/de/ajax.texy b/application/de/ajax.texy index 5fa29383e4..00e066bda7 100644 --- a/application/de/ajax.texy +++ b/application/de/ajax.texy @@ -209,7 +209,7 @@ OK {control productGrid} funktioniert nicht: -{control productGrid $arg, $arg} +{control productGrid, $arg, $arg} {control productGrid:paginator} ``` diff --git a/application/de/components.texy b/application/de/components.texy index b9b3713eee..d6a7e7f72b 100644 --- a/application/de/components.texy +++ b/application/de/components.texy @@ -107,7 +107,7 @@ public function render(): void Der Tag `{control}` erlaubt es, der Methode `render()` Parameter zu übergeben: ```latte -{control poll $id, $message} +{control poll, $id, $message} ``` ```php .{file:PollControl.php} @@ -136,7 +136,7 @@ Zum besseren Verständnis ist es gut zu wissen, wie sich dieser Tag in PHP-Code ```latte {control poll} -{control poll:paginator 123, 'hello'} +{control poll:paginator, 123, 'hello'} ``` übersetzt sich zu: @@ -200,7 +200,7 @@ public function handleClick(int $x, int $y): void Einen Link, der ein Signal aufruft, erstellt man auf die übliche Weise, also im Template mit dem Attribut `n:href` oder dem Tag `{link}`, im Code mit der Methode `link()`. Mehr im Kapitel [Erstellen von URL-Links |creating-links#Links auf Signale]. ```latte -hier klicken +hier klicken ``` Ein Signal wird immer auf dem aktuellen Presenter und der aktuellen Aktion aufgerufen; es lässt sich nicht auf einem anderen Presenter oder einer anderen Aktion auslösen. @@ -281,13 +281,13 @@ Wir empfehlen, für die Property den Datentyp anzugeben (z. B. `int`), und Sie k Beim Erstellen eines Links lässt sich der Wert eines persistenten Parameters ändern: ```latte -weiter +weiter ``` Oder er lässt sich *zurücksetzen*, also aus der URL entfernen. Er nimmt dann seinen Standardwert an: ```latte -zurücksetzen +zurücksetzen ``` diff --git a/application/de/creating-links.texy b/application/de/creating-links.texy index 66821107bd..efb5faf9c9 100644 --- a/application/de/creating-links.texy +++ b/application/de/creating-links.texy @@ -29,13 +29,13 @@ Beachten Sie, dass wir statt des HTML-Attributs `href` das [n:Attribut |latte:sy Auf einen Link zu klicken ist, vereinfacht gesagt, so etwas wie der Aufruf der Methode `ProductPresenter::renderShow()`. Und wenn diese in ihrer Signatur Parameter hat, können wir sie mit Argumenten aufrufen: ```latte -Produktdetail +Produktdetail ``` Es lassen sich auch benannte Parameter übergeben. Der folgende Link übergibt den Parameter `lang` mit dem Wert `en`: ```latte -Produktdetail +Produktdetail ``` Hat die Methode `ProductPresenter::renderShow()` in ihrer Signatur kein `$lang`, kann sie den Wert des Parameters mit `$lang = $this->getParameter('lang')` oder aus einer [Property |presenters#Parameter des Requests] holen. @@ -162,7 +162,7 @@ Dabei werden zugleich alle Parameter übernommen, die in der Signatur der Method Natürlich lassen sich Parameter auch direkt angeben: ```latte -aktualisieren +aktualisieren ``` Die Funktion `isLinkCurrent()` prüft, ob das Ziel des Links mit der aktuellen Seite identisch ist. Das lässt sich zum Beispiel im Template nutzen, um Links optisch zu unterscheiden usw. diff --git a/application/de/how-it-works.texy b/application/de/how-it-works.texy index 0766651e3b..12eca8f7b7 100644 --- a/application/de/how-it-works.texy +++ b/application/de/how-it-works.texy @@ -150,7 +150,7 @@ Da wir gerade bei Templates sind: Nette verwendet das Templating-System [Latte | Im Template [erstellen Sie Links |creating-links] auf andere Presenter & Aktionen so: ```latte -Produktdetail +Produktdetail ``` Schreiben Sie einfach das vertraute Paar `Presenter:Aktion` statt der tatsächlichen URL und ergänzen Sie eventuelle Parameter. Der Trick steckt in `n:href`, das Nette sagt, dieses Attribut zu verarbeiten. Es erzeugt dann: diff --git a/application/de/presenters.texy b/application/de/presenters.texy index 27a758fbbe..230239d102 100644 --- a/application/de/presenters.texy +++ b/application/de/presenters.texy @@ -164,7 +164,7 @@ $url = $this->link('Product:show', [$id, 'lang' => 'en']); Im Template werden Links auf andere Presenter & Aktionen so erstellt: ```latte -Produktdetail +Produktdetail ``` Schreiben Sie einfach das vertraute Paar `Presenter:action` statt der tatsächlichen URL und ergänzen Sie eventuelle Parameter. Der Trick steckt in `n:href`, das Latte sagt, dieses Attribut zu verarbeiten und die echte URL zu erzeugen. In Nette müssen Sie überhaupt nicht über URLs nachdenken, sondern nur über Presenter und Aktionen. @@ -282,7 +282,7 @@ Für die Property empfehlen wir, den Datentyp anzugeben (z. B. `string`), Nette Beim Erstellen eines Links lässt sich der Wert des Parameters direkt setzen: ```latte -klicken +klicken ``` @@ -330,13 +330,13 @@ class ProductPresenter extends Nette\Application\UI\Presenter Beim Erstellen eines Links lässt sich der Wert eines persistenten Parameters ändern: ```latte -Detail auf Tschechisch +Detail auf Tschechisch ``` Oder er lässt sich *zurücksetzen*, also aus der URL entfernen. Er nimmt dann seinen Standardwert an: ```latte -klicken +klicken ``` diff --git a/application/en/ajax.texy b/application/en/ajax.texy index 50a618f208..fb4a3e0cf3 100644 --- a/application/en/ajax.texy +++ b/application/en/ajax.texy @@ -209,7 +209,7 @@ OK {control productGrid} will not work: -{control productGrid $arg, $arg} +{control productGrid, $arg, $arg} {control productGrid:paginator} ``` diff --git a/application/en/components.texy b/application/en/components.texy index b0da2bfe5f..31d270bf88 100644 --- a/application/en/components.texy +++ b/application/en/components.texy @@ -107,7 +107,7 @@ public function render(): void The `{control}` tag allows passing parameters to the `render()` method: ```latte -{control poll $id, $message} +{control poll, $id, $message} ``` ```php .{file:PollControl.php} @@ -136,7 +136,7 @@ For a better understanding, it's good to know how this tag translates into PHP c ```latte {control poll} -{control poll:paginator 123, 'hello'} +{control poll:paginator, 123, 'hello'} ``` translates to: @@ -200,7 +200,7 @@ public function handleClick(int $x, int $y): void A link that calls a signal is created in the usual way, i.e., in the template with the `n:href` attribute or the `{link}` tag, in the code with the `link()` method. More in the chapter [Creating URL Links |creating-links#Links to Signal]. ```latte -click here +click here ``` A signal is always called on the current presenter and action; it is not possible to invoke it on another presenter or action. @@ -281,13 +281,13 @@ We recommend specifying the data type for the property (e.g., `int`), and you ca When creating a link, the value of a persistent parameter can be changed: ```latte -next +next ``` Or it can be *reset*, i.e., removed from the URL. It will then assume its default value: ```latte -reset +reset ``` diff --git a/application/en/creating-links.texy b/application/en/creating-links.texy index 625ee37bcf..191169cdfd 100644 --- a/application/en/creating-links.texy +++ b/application/en/creating-links.texy @@ -29,13 +29,13 @@ Notice that instead of the HTML attribute `href`, we used the [n:attribute |latt Clicking on a link is, simply put, something like calling the `ProductPresenter::renderShow()` method. And if it has parameters in its signature, we can call it with arguments: ```latte -product detail +product detail ``` It is also possible to pass named parameters. The following link passes the parameter `lang` with the value `en`: ```latte -product detail +product detail ``` If the `ProductPresenter::renderShow()` method does not have `$lang` in its signature, it can retrieve the parameter's value using `$lang = $this->getParameter('lang')` or from a [property |presenters#Request Parameters]. @@ -162,7 +162,7 @@ At the same time, all parameters specified in the signature of the `actionrefresh +refresh ``` The `isLinkCurrent()` function checks if the link target is identical to the current page. This can be used, for example, in a template to distinguish links, etc. diff --git a/application/en/how-it-works.texy b/application/en/how-it-works.texy index 5917431664..0445eed8ac 100644 --- a/application/en/how-it-works.texy +++ b/application/en/how-it-works.texy @@ -150,7 +150,7 @@ Speaking of templates, Nette uses the [Latte |latte:] templating system. That's In the template, you [create links |creating-links] to other presenters & actions like this: ```latte -product detail +product detail ``` Simply write the familiar `Presenter:action` pair instead of the actual URL and include any necessary parameters. The trick lies in `n:href`, which tells Nette to process this attribute. It will then generate: diff --git a/application/en/presenters.texy b/application/en/presenters.texy index 50f580bbaa..c331db5633 100644 --- a/application/en/presenters.texy +++ b/application/en/presenters.texy @@ -164,7 +164,7 @@ $url = $this->link('Product:show', [$id, 'lang' => 'en']); In the template, links to other presenters & actions are created like this: ```latte -product detail +product detail ``` Simply write the familiar `Presenter:action` pair instead of the actual URL and include any necessary parameters. The trick lies in `n:href`, which tells Latte to process this attribute and generate the real URL. In Nette, you don't need to think about URLs at all, just about presenters and actions. @@ -282,7 +282,7 @@ For the property, we recommend specifying the data type (e.g., `string`), and Ne When creating a link, you can set the parameter's value directly: ```latte -click +click ``` @@ -330,13 +330,13 @@ class ProductPresenter extends Nette\Application\UI\Presenter When creating a link, the value of a persistent parameter can be changed: ```latte -detail in Czech +detail in Czech ``` Alternatively, it can be *reset*, i.e., removed from the URL. It will then assume its default value: ```latte -click +click ``` diff --git a/application/es/ajax.texy b/application/es/ajax.texy index e7eb69f6cd..4f526c7836 100644 --- a/application/es/ajax.texy +++ b/application/es/ajax.texy @@ -209,7 +209,7 @@ OK {control productGrid} will not work: -{control productGrid $arg, $arg} +{control productGrid, $arg, $arg} {control productGrid:paginator} ``` diff --git a/application/es/components.texy b/application/es/components.texy index a768929b2d..426d72ee2c 100644 --- a/application/es/components.texy +++ b/application/es/components.texy @@ -107,7 +107,7 @@ public function render(): void La etiqueta `{control}` permite pasar parámetros al método `render()`: ```latte -{control poll $id, $message} +{control poll, $id, $message} ``` ```php .{file:PollControl.php} @@ -136,7 +136,7 @@ Para entenderlo mejor, conviene saber cómo se traduce esta etiqueta a código P ```latte {control poll} -{control poll:paginator 123, 'hello'} +{control poll:paginator, 123, 'hello'} ``` se traduce a: @@ -200,7 +200,7 @@ public function handleClick(int $x, int $y): void Un enlace que llama a una señal se crea de la forma habitual, es decir, en la plantilla con el atributo `n:href` o la etiqueta `{link}`, y en el código con el método `link()`. Más en el capítulo [Creación de enlaces URL |creating-links#Enlaces a una señal]. ```latte -click here +click here ``` Una señal se llama siempre sobre el presenter y la acción actuales; no es posible invocarla sobre otro presenter u otra acción. @@ -281,13 +281,13 @@ Recomendamos indicar el tipo de dato de la propiedad (p. ej. `int`), y también Al crear un enlace se puede cambiar el valor de un parámetro persistente: ```latte -next +next ``` O se puede *resetear*, es decir, eliminar de la URL. Entonces adoptará su valor por defecto: ```latte -reset +reset ``` diff --git a/application/es/creating-links.texy b/application/es/creating-links.texy index 11815e20ca..17bb7234b1 100644 --- a/application/es/creating-links.texy +++ b/application/es/creating-links.texy @@ -29,13 +29,13 @@ Fíjese en que, en lugar del atributo HTML `href`, hemos usado el [n:atributo |l Pulsar un enlace es, dicho de forma sencilla, algo así como llamar al método `ProductPresenter::renderShow()`. Y si tiene parámetros en su firma, podemos llamarlo con argumentos: ```latte -product detail +product detail ``` También es posible pasar parámetros nombrados. El siguiente enlace pasa el parámetro `lang` con el valor `en`: ```latte -product detail +product detail ``` Si el método `ProductPresenter::renderShow()` no tiene `$lang` en su firma, puede obtener el valor del parámetro con `$lang = $this->getParameter('lang')` o desde una [propiedad |presenters#Parámetros de la petición]. @@ -162,7 +162,7 @@ Al mismo tiempo se transfieren todos los parámetros indicados en la firma del m Por supuesto, es posible indicar los parámetros directamente: ```latte -refresh +refresh ``` La función `isLinkCurrent()` comprueba si el destino del enlace es idéntico a la página actual. Esto se puede usar, por ejemplo, en una plantilla para distinguir los enlaces, etc. diff --git a/application/es/how-it-works.texy b/application/es/how-it-works.texy index f09f7e4a0f..09a378001d 100644 --- a/application/es/how-it-works.texy +++ b/application/es/how-it-works.texy @@ -150,7 +150,7 @@ Puesto que hablamos de plantillas, Nette usa el sistema de plantillas [Latte |la En la plantilla, los [enlaces |creating-links] a otros presenters y acciones se crean así: ```latte -product detail +product detail ``` Basta con escribir la conocida pareja `Presenter:acción` en lugar de la URL real e incluir los parámetros necesarios. El truco está en `n:href`, que le dice a Nette que procese ese atributo. Generará entonces: diff --git a/application/es/presenters.texy b/application/es/presenters.texy index e714797364..da45ae7a80 100644 --- a/application/es/presenters.texy +++ b/application/es/presenters.texy @@ -164,7 +164,7 @@ $url = $this->link('Product:show', [$id, 'lang' => 'en']); En la plantilla, los enlaces a otros presenters y acciones se crean así: ```latte -product detail +product detail ``` Simplemente escriba en lugar de la URL real el conocido par `Presenter:action` e indique los parámetros que hagan falta. El truco está en `n:href`, que le dice a Latte que procese este atributo y genere la URL real. En Nette no tiene que pensar en absoluto en las URL, solo en los presenters y las acciones. @@ -282,7 +282,7 @@ Para la propiedad recomendamos indicar el tipo de dato (p. ej. `string`) y Nette Al crear un enlace puede establecer directamente el valor del parámetro: ```latte -click +click ``` @@ -330,13 +330,13 @@ class ProductPresenter extends Nette\Application\UI\Presenter Al crear un enlace se puede cambiar el valor de un parámetro persistente: ```latte -detail in Czech +detail in Czech ``` O se puede *resetear*, es decir, eliminar de la URL. Entonces adoptará su valor por defecto: ```latte -click +click ``` diff --git a/application/fr/ajax.texy b/application/fr/ajax.texy index 7abb4466fa..bca4d9b42a 100644 --- a/application/fr/ajax.texy +++ b/application/fr/ajax.texy @@ -209,7 +209,7 @@ OK {control productGrid} ne fonctionnera pas : -{control productGrid $arg, $arg} +{control productGrid, $arg, $arg} {control productGrid:paginator} ``` diff --git a/application/fr/components.texy b/application/fr/components.texy index 561d497835..3435eed77d 100644 --- a/application/fr/components.texy +++ b/application/fr/components.texy @@ -107,7 +107,7 @@ public function render(): void La balise `{control}` permet de passer des paramètres à la méthode `render()` : ```latte -{control poll $id, $message} +{control poll, $id, $message} ``` ```php .{file:PollControl.php} @@ -136,7 +136,7 @@ Pour une meilleure compréhension, il est bon de savoir comment cette balise est ```latte {control poll} -{control poll:paginator 123, 'hello'} +{control poll:paginator, 123, 'hello'} ``` se traduit par : @@ -200,7 +200,7 @@ public function handleClick(int $x, int $y): void Nous créons un lien qui appelle un signal de la manière habituelle, c'est-à-dire dans le template avec l'attribut `n:href` ou la balise `{link}`, dans le code avec la méthode `link()`. Plus d'informations dans le chapitre [Création de liens URL |creating-links#Liens vers un signal]. ```latte -cliquez ici +cliquez ici ``` Un signal est toujours appelé sur le presenter et l'action actuels ; il n'est pas possible de l'appeler sur un autre presenter ou une autre action. @@ -281,13 +281,13 @@ Nous recommandons d'indiquer également le type de données pour la propriété Lors de la création d'un lien, la valeur du paramètre persistant peut être modifiée : ```latte -suivant +suivant ``` Ou il peut être *réinitialisé*, c'est-à-dire supprimé de l'URL. Il prendra alors sa valeur par défaut : ```latte -réinitialiser +réinitialiser ``` diff --git a/application/fr/creating-links.texy b/application/fr/creating-links.texy index 1df0b3cecb..26f7af2fcd 100644 --- a/application/fr/creating-links.texy +++ b/application/fr/creating-links.texy @@ -29,13 +29,13 @@ Notez qu'au lieu de l'attribut HTML `href`, nous avons utilisé un [n:attribut | Cliquer sur le lien est, pour simplifier, quelque chose comme appeler la méthode `ProductPresenter::renderShow()`. Et si elle a des paramètres dans sa signature, nous pouvons l'appeler avec des arguments : ```latte -détail du produit +détail du produit ``` Il est également possible de passer des paramètres nommés. Le lien suivant passe le paramètre `lang` avec la valeur `cs` : ```latte -détail du produit +détail du produit ``` Si la méthode `ProductPresenter::renderShow()` n'a pas `$lang` dans sa signature, elle peut récupérer la valeur du paramètre en utilisant `$lang = $this->getParameter('lang')` ou depuis une [propriété |presenters#Paramètres de la requête]. @@ -44,7 +44,7 @@ Si les paramètres sont stockés dans un tableau, ils peuvent être développés ```latte {var $args = [$product->id, lang => cs]} -détail du produit +détail du produit ``` Les liens transmettent également automatiquement les [paramètres persistants |presenters#Paramètres persistants]. @@ -162,7 +162,7 @@ En même temps, tous les paramètres spécifiés dans la signature de la méthod Bien sûr, il est possible de spécifier les paramètres directement : ```latte -rafraîchir +rafraîchir ``` La fonction `isLinkCurrent()` vérifie si la cible du lien est identique à la page actuelle. Cela peut être utilisé, par exemple, dans un template pour distinguer les liens, etc. diff --git a/application/fr/how-it-works.texy b/application/fr/how-it-works.texy index 78d5411595..579b3e71fb 100644 --- a/application/fr/how-it-works.texy +++ b/application/fr/how-it-works.texy @@ -150,7 +150,7 @@ Puisque nous parlons de templates, Nette utilise le système de templates [Latte Dans le template, des [liens |creating-links] sont créés vers d'autres presenters & actions comme ceci : ```latte -détail du produit +détail du produit ``` Au lieu d'une URL réelle, écrivez simplement la paire connue `Presenter:action` et spécifiez d'éventuels paramètres. L'astuce réside dans `n:href`, qui indique que cet attribut sera traité par Nette. Et il générera : diff --git a/application/fr/presenters.texy b/application/fr/presenters.texy index a4c22cce50..e479751763 100644 --- a/application/fr/presenters.texy +++ b/application/fr/presenters.texy @@ -164,7 +164,7 @@ $url = $this->link('Product:show', [$id, 'lang' => 'cs']); Dans le template, les liens vers d'autres presenters & actions sont créés de cette manière : ```latte -détail du produit +détail du produit ``` Au lieu d'une URL réelle, écrivez simplement la paire connue `Presenter:action` et spécifiez d'éventuels paramètres. L'astuce réside dans `n:href`, qui indique que cet attribut sera traité par Latte et générera une URL réelle. Dans Nette, vous n'avez donc pas du tout à penser aux URL, seulement aux presenters et aux actions. @@ -282,7 +282,7 @@ Nous recommandons d'indiquer également le type de données pour la propriété Lors de la création d'un lien, la valeur des paramètres peut être définie directement : ```latte -cliquer +cliquer ``` @@ -330,13 +330,13 @@ class ProductPresenter extends Nette\Application\UI\Presenter Lors de la création d'un lien, la valeur du paramètre persistant peut être modifiée : ```latte -détail en tchèque +détail en tchèque ``` Ou il peut être *réinitialisé*, c'est-à-dire supprimé de l'URL. Il prendra alors sa valeur par défaut : ```latte -cliquer +cliquer ``` diff --git a/application/it/ajax.texy b/application/it/ajax.texy index 0968c573d6..624bfe0181 100644 --- a/application/it/ajax.texy +++ b/application/it/ajax.texy @@ -209,7 +209,7 @@ OK {control productGrid} non funzionerà: -{control productGrid $arg, $arg} +{control productGrid, $arg, $arg} {control productGrid:paginator} ``` diff --git a/application/it/components.texy b/application/it/components.texy index fe52021058..37413b7604 100644 --- a/application/it/components.texy +++ b/application/it/components.texy @@ -107,7 +107,7 @@ public function render(): void Il tag `{control}` permette di passare parametri al metodo `render()`: ```latte -{control poll $id, $message} +{control poll, $id, $message} ``` ```php .{file:PollControl.php} @@ -136,7 +136,7 @@ Per capire meglio è utile sapere come questo tag si traduce in codice PHP. ```latte {control poll} -{control poll:paginator 123, 'hello'} +{control poll:paginator, 123, 'hello'} ``` si traduce in: @@ -200,7 +200,7 @@ public function handleClick(int $x, int $y): void Un link che chiama un segnale si crea nel modo consueto, cioè nel template con l'attributo `n:href` o con il tag `{link}`, nel codice con il metodo `link()`. Maggiori informazioni nel capitolo [Creazione di link URL |creating-links#Link a un segnale]. ```latte -clicca qui +clicca qui ``` Un segnale viene sempre chiamato sul presenter e sull'azione correnti; non è possibile richiamarlo su un altro presenter o su un'altra azione. @@ -281,13 +281,13 @@ Consigliamo di indicare il tipo di dato della proprietà (per esempio `int`) e p Quando si crea un link, il valore di un parametro persistente si può cambiare: ```latte -successiva +successiva ``` Oppure lo si può *azzerare*, cioè rimuovere dall'URL. Assumerà allora il proprio valore predefinito: ```latte -azzera +azzera ``` diff --git a/application/it/creating-links.texy b/application/it/creating-links.texy index 9068de2e9f..b641e316d7 100644 --- a/application/it/creating-links.texy +++ b/application/it/creating-links.texy @@ -29,13 +29,13 @@ Notate che al posto dell'attributo HTML `href` abbiamo usato l'[n:attributo |lat Cliccare su un link è, detta semplicemente, un po' come chiamare il metodo `ProductPresenter::renderShow()`. E se questo ha dei parametri nella propria firma, possiamo chiamarlo con degli argomenti: ```latte -dettaglio del prodotto +dettaglio del prodotto ``` È possibile passare anche parametri nominali. Il link seguente passa il parametro `lang` con il valore `en`: ```latte -dettaglio del prodotto +dettaglio del prodotto ``` Se il metodo `ProductPresenter::renderShow()` non ha `$lang` nella propria firma, può ottenere il valore del parametro con `$lang = $this->getParameter('lang')` oppure da una [proprietà |presenters#Parametri della richiesta]. @@ -162,7 +162,7 @@ Allo stesso tempo vengono trasferiti tutti i parametri indicati nella firma del Naturalmente è possibile indicare i parametri direttamente: ```latte -aggiorna +aggiorna ``` La funzione `isLinkCurrent()` controlla se la destinazione del link coincide con la pagina corrente. Si può usare per esempio in un template per distinguere i link e simili. diff --git a/application/it/how-it-works.texy b/application/it/how-it-works.texy index faf548f9db..5539de6df3 100644 --- a/application/it/how-it-works.texy +++ b/application/it/how-it-works.texy @@ -150,7 +150,7 @@ A proposito di template, Nette usa il sistema di template [Latte |latte:]. Ecco Nel template [create i link |creating-links] verso altri presenter e azioni così: ```latte -dettaglio del prodotto +dettaglio del prodotto ``` Basta scrivere la familiare coppia `Presenter:azione` al posto dell'URL vero e proprio e aggiungere gli eventuali parametri necessari. Il trucco sta in `n:href`, che dice a Nette di elaborare questo attributo. Verrà allora generato: diff --git a/application/it/presenters.texy b/application/it/presenters.texy index 072276889b..b735eb3ca6 100644 --- a/application/it/presenters.texy +++ b/application/it/presenters.texy @@ -164,7 +164,7 @@ $url = $this->link('Product:show', [$id, 'lang' => 'en']); Nel template i link verso altri presenter e azioni si creano così: ```latte -dettaglio del prodotto +dettaglio del prodotto ``` Basta scrivere la familiare coppia `Presenter:azione` al posto dell'URL vero e proprio e aggiungere gli eventuali parametri necessari. Il trucco sta in `n:href`, che dice a Latte di elaborare questo attributo e di generare l'URL reale. In Nette non dovete pensare affatto agli URL, solo ai presenter e alle azioni. @@ -282,7 +282,7 @@ Per la proprietà consigliamo di indicare il tipo di dato (per esempio `string`) Quando create un link potete impostare direttamente il valore del parametro: ```latte -clicca +clicca ``` @@ -330,13 +330,13 @@ class ProductPresenter extends Nette\Application\UI\Presenter Quando si crea un link, il valore di un parametro persistente si può cambiare: ```latte -dettaglio in ceco +dettaglio in ceco ``` In alternativa lo si può *azzerare*, cioè rimuovere dall'URL. Assumerà allora il proprio valore predefinito: ```latte -clicca +clicca ``` diff --git a/application/ja/ajax.texy b/application/ja/ajax.texy index 473d163c99..41c5fba15d 100644 --- a/application/ja/ajax.texy +++ b/application/ja/ajax.texy @@ -209,7 +209,7 @@ OK {control productGrid} 動きません: -{control productGrid $arg, $arg} +{control productGrid, $arg, $arg} {control productGrid:paginator} ``` diff --git a/application/ja/components.texy b/application/ja/components.texy index faf42836b1..d734c1fedd 100644 --- a/application/ja/components.texy +++ b/application/ja/components.texy @@ -107,7 +107,7 @@ public function render(): void `{control}` タグは `render()` メソッドにパラメータを渡せます。 ```latte -{control poll $id, $message} +{control poll, $id, $message} ``` ```php .{file:PollControl.php} @@ -136,7 +136,7 @@ public function renderPaginator(): void ```latte {control poll} -{control poll:paginator 123, 'hello'} +{control poll:paginator, 123, 'hello'} ``` は次に変換されます。 @@ -200,7 +200,7 @@ public function handleClick(int $x, int $y): void シグナルを呼ぶリンクはいつもどおりに作ります。つまりテンプレートでは `n:href` 属性か `{link}` タグ、コードでは `link()` メソッドです。詳しくは [URL リンクの作成 |creating-links#シグナルへのリンク]の章をご覧ください。 ```latte -ここをクリック +ここをクリック ``` シグナルは常に現在のプレゼンターとアクションで呼ばれます。別のプレゼンターやアクションで呼ぶことはできません。 @@ -281,13 +281,13 @@ class PaginatingControl extends Control リンクを作るとき、永続パラメータの値は変えられます。 ```latte -次へ +次へ ``` あるいは*リセット*して URL から取り除けます。その場合は既定値になります。 ```latte -リセット +リセット ``` diff --git a/application/ja/creating-links.texy b/application/ja/creating-links.texy index d08068f318..283a57f846 100644 --- a/application/ja/creating-links.texy +++ b/application/ja/creating-links.texy @@ -29,13 +29,13 @@ HTML の属性 `href` の代わりに [n:属性 |latte:syntax#n:属性]の `n:hr リンクをクリックすることは、簡単にいえば `ProductPresenter::renderShow()` メソッドを呼ぶようなものです。そしてそのシグネチャにパラメータがあれば、引数を付けて呼べます。 ```latte -商品の詳細 +商品の詳細 ``` 名前付きパラメータも渡せます。次のリンクは、値 `en` を持つパラメータ `lang` を渡します。 ```latte -商品の詳細 +商品の詳細 ``` `ProductPresenter::renderShow()` メソッドのシグネチャに `$lang` がなければ、`$lang = $this->getParameter('lang')` か[プロパティ |presenters#リクエストのパラメータ]でその値を取得できます。 @@ -162,7 +162,7 @@ $this->link('Home:default', ['#' => $fragment]); もちろん、パラメータを直接指定することもできます。 ```latte -更新 +更新 ``` `isLinkCurrent()` 関数は、リンクの行き先が現在のページと同じかどうかを調べます。たとえばテンプレートでリンクを見分けるのに使えます。 diff --git a/application/ja/how-it-works.texy b/application/ja/how-it-works.texy index d7d78af3f6..bd9fcbaf5e 100644 --- a/application/ja/how-it-works.texy +++ b/application/ja/how-it-works.texy @@ -150,7 +150,7 @@ class ProductPresenter extends Nette\Application\UI\Presenter テンプレートでは、ほかのプレゼンターやアクションへの[リンクを作ります |creating-links]。次のようにです。 ```latte -商品の詳細 +商品の詳細 ``` 実際の URL の代わりに、見慣れた `Presenter:action` の組を書き、必要なパラメータを添えるだけです。仕掛けは `n:href` にあり、これがこの属性を処理するよう Nette に伝えます。すると次が生成されます。 diff --git a/application/ja/presenters.texy b/application/ja/presenters.texy index 61138b6df4..f5f32a61aa 100644 --- a/application/ja/presenters.texy +++ b/application/ja/presenters.texy @@ -164,7 +164,7 @@ $url = $this->link('Product:show', [$id, 'lang' => 'en']); テンプレートでは、ほかのプレゼンターやアクションへのリンクを次のように作ります。 ```latte -商品の詳細 +商品の詳細 ``` 実際の URL の代わりに、見慣れた `Presenter:action` の組を書き、必要なパラメータを添えるだけです。仕掛けは `n:href` にあり、これがこの属性を処理して本当の URL を生成するよう Latte に伝えます。Nette では URL のことを考える必要はまったくなく、プレゼンターとアクションのことだけを考えればよいのです。 @@ -282,7 +282,7 @@ class HomePresenter extends Nette\Application\UI\Presenter リンクを作るとき、パラメータの値を直接設定できます。 ```latte -クリック +クリック ``` @@ -330,13 +330,13 @@ class ProductPresenter extends Nette\Application\UI\Presenter リンクを作るとき、永続パラメータの値は変えられます。 ```latte -チェコ語での詳細 +チェコ語での詳細 ``` あるいは*リセット*して URL から取り除けます。その場合は既定値になります。 ```latte -クリック +クリック ``` diff --git a/application/pl/ajax.texy b/application/pl/ajax.texy index b7e7b78f9e..ba5e987831 100644 --- a/application/pl/ajax.texy +++ b/application/pl/ajax.texy @@ -209,7 +209,7 @@ OK {control productGrid} nie zadziała: -{control productGrid $arg, $arg} +{control productGrid, $arg, $arg} {control productGrid:paginator} ``` diff --git a/application/pl/components.texy b/application/pl/components.texy index 189db24a74..ee22bce2e1 100644 --- a/application/pl/components.texy +++ b/application/pl/components.texy @@ -107,7 +107,7 @@ public function render(): void Tag `{control}` pozwala przekazać metodzie `render()` parametry: ```latte -{control poll $id, $message} +{control poll, $id, $message} ``` ```php .{file:PollControl.php} @@ -136,7 +136,7 @@ Dla lepszego zrozumienia warto wiedzieć, jak ten tag przekłada się na kod PHP ```latte {control poll} -{control poll:paginator 123, 'hello'} +{control poll:paginator, 123, 'hello'} ``` przekłada się na: @@ -200,7 +200,7 @@ public function handleClick(int $x, int $y): void Odnośnik wywołujący sygnał tworzy się w zwykły sposób, czyli w szablonie atrybutem `n:href` albo tagiem `{link}`, a w kodzie metodą `link()`. Więcej w rozdziale [Tworzenie odnośników URL |creating-links#Odnośniki do sygnału]. ```latte -kliknij tutaj +kliknij tutaj ``` Sygnał wywoływany jest zawsze na bieżącym presenterze i akcji; nie da się wywołać go na innym presenterze albo innej akcji. @@ -281,13 +281,13 @@ Zalecamy podanie typu danych właściwości (np. `int`), możesz też podać war Przy tworzeniu odnośnika wartość parametru trwałego można zmienić: ```latte -dalej +dalej ``` Albo *zresetować*, czyli usunąć z URL. Przyjmie wtedy swoją wartość domyślną: ```latte -resetuj +resetuj ``` diff --git a/application/pl/creating-links.texy b/application/pl/creating-links.texy index b8abbf5d05..59d9c3653f 100644 --- a/application/pl/creating-links.texy +++ b/application/pl/creating-links.texy @@ -29,13 +29,13 @@ Zwróć uwagę, że zamiast atrybutu HTML `href` użyliśmy [n:atrybutu |latte:s Kliknięcie w odnośnik to, mówiąc prosto, coś w rodzaju wywołania metody `ProductPresenter::renderShow()`. A jeśli ma ona w sygnaturze parametry, możemy wywołać ją z argumentami: ```latte -szczegóły produktu +szczegóły produktu ``` Można też przekazywać parametry nazwane. Poniższy odnośnik przekazuje parametr `lang` o wartości `en`: ```latte -szczegóły produktu +szczegóły produktu ``` Jeśli metoda `ProductPresenter::renderShow()` nie ma w sygnaturze `$lang`, może pobrać wartość parametru przez `$lang = $this->getParameter('lang')` albo z [właściwości |presenters#Parametry żądania]. @@ -162,7 +162,7 @@ Jednocześnie przekazywane są wszystkie parametry podane w sygnaturze metody `a Oczywiście parametry można podać bezpośrednio: ```latte -odśwież +odśwież ``` Funkcja `isLinkCurrent()` sprawdza, czy cel odnośnika jest identyczny z bieżącą stroną. Można tego użyć na przykład w szablonie do odróżniania odnośników itd. diff --git a/application/pl/how-it-works.texy b/application/pl/how-it-works.texy index 08541766b4..f8d24ef605 100644 --- a/application/pl/how-it-works.texy +++ b/application/pl/how-it-works.texy @@ -150,7 +150,7 @@ Skoro mowa o szablonach, Nette używa systemu szablonów [Latte |latte:]. Dlateg W szablonie [tworzysz odnośniki |creating-links] do innych presenterów i akcji tak: ```latte -szczegóły produktu +szczegóły produktu ``` Zamiast prawdziwego URL po prostu zapisujesz znajomą parę `Presenter:akcja` i dodajesz ewentualne parametry. Sztuczka tkwi w `n:href`, które mówi Nette, aby ten atrybut przetworzyło. Wygeneruje wtedy: diff --git a/application/pl/presenters.texy b/application/pl/presenters.texy index ac3ce3dd2d..7caffa063b 100644 --- a/application/pl/presenters.texy +++ b/application/pl/presenters.texy @@ -164,7 +164,7 @@ $url = $this->link('Product:show', [$id, 'lang' => 'en']); W szablonie odnośniki do innych presenterów i akcji tworzy się tak: ```latte -szczegóły produktu +szczegóły produktu ``` Zamiast prawdziwego URL po prostu zapisujesz znajomą parę `Presenter:akcja` i dodajesz ewentualne parametry. Sztuczka tkwi w `n:href`, które mówi Latte, aby ten atrybut przetworzyło i wygenerowało prawdziwy URL. W Nette w ogóle nie musisz myśleć o URL, tylko o presenterach i akcjach. @@ -282,7 +282,7 @@ Dla właściwości zalecamy podanie typu danych (np. `string`), a Nette automaty Przy tworzeniu odnośnika możesz ustawić wartość parametru bezpośrednio: ```latte -kliknij +kliknij ``` @@ -330,13 +330,13 @@ class ProductPresenter extends Nette\Application\UI\Presenter Przy tworzeniu odnośnika wartość parametru trwałego można zmienić: ```latte -szczegóły po czesku +szczegóły po czesku ``` Albo *zresetować*, czyli usunąć z URL. Przyjmie wtedy swoją wartość domyślną: ```latte -kliknij +kliknij ``` diff --git a/application/ru/ajax.texy b/application/ru/ajax.texy index a61b4aa5a7..9aedad772c 100644 --- a/application/ru/ajax.texy +++ b/application/ru/ajax.texy @@ -209,7 +209,7 @@ OK {control productGrid} работать не будет: -{control productGrid $arg, $arg} +{control productGrid, $arg, $arg} {control productGrid:paginator} ``` diff --git a/application/ru/components.texy b/application/ru/components.texy index a1942e5f9e..66e9d69bb7 100644 --- a/application/ru/components.texy +++ b/application/ru/components.texy @@ -107,7 +107,7 @@ public function render(): void Тег `{control}` позволяет передать параметры в метод `render()`: ```latte -{control poll $id, $message} +{control poll, $id, $message} ``` ```php .{file:PollControl.php} @@ -136,7 +136,7 @@ public function renderPaginator(): void ```latte {control poll} -{control poll:paginator 123, 'hello'} +{control poll:paginator, 123, 'hello'} ``` превращается в: @@ -200,7 +200,7 @@ public function handleClick(int $x, int $y): void Ссылка, вызывающая сигнал, создаётся обычным способом, то есть в шаблоне атрибутом `n:href` или тегом `{link}`, а в коде методом `link()`. Подробнее в главе [Создание URL-ссылок |creating-links#Ссылки на сигнал]. ```latte -click here +click here ``` Сигнал всегда вызывается на текущем презентере и действии; вызвать его на другом презентере или действии нельзя. @@ -281,13 +281,13 @@ class PaginatingControl extends Control При создании ссылки значение постоянного параметра можно изменить: ```latte -next +next ``` Или его можно *сбросить*, то есть убрать из URL. Тогда он примет значение по умолчанию: ```latte -reset +reset ``` diff --git a/application/ru/creating-links.texy b/application/ru/creating-links.texy index 2643963f02..330e2fc49e 100644 --- a/application/ru/creating-links.texy +++ b/application/ru/creating-links.texy @@ -29,13 +29,13 @@ Щелчок по ссылке, попросту говоря, похож на вызов метода `ProductPresenter::renderShow()`. А если у него есть параметры в сигнатуре, мы можем вызвать его с аргументами: ```latte -product detail +product detail ``` Можно передавать и именованные параметры. Следующая ссылка передаёт параметр `lang` со значением `en`: ```latte -product detail +product detail ``` Если у метода `ProductPresenter::renderShow()` нет `$lang` в сигнатуре, он может получить значение параметра через `$lang = $this->getParameter('lang')` или из [свойства |presenters#Параметры запроса]. @@ -162,7 +162,7 @@ $this->link('Home:default', ['#' => $fragment]); Разумеется, параметры можно указать и напрямую: ```latte -refresh +refresh ``` Функция `isLinkCurrent()` проверяет, совпадает ли цель ссылки с текущей страницей. Это можно использовать, например, в шаблоне, чтобы выделять ссылки и подобное. diff --git a/application/ru/how-it-works.texy b/application/ru/how-it-works.texy index 41a097e559..ab4934da46 100644 --- a/application/ru/how-it-works.texy +++ b/application/ru/how-it-works.texy @@ -150,7 +150,7 @@ class ProductPresenter extends Nette\Application\UI\Presenter В шаблоне вы [создаёте ссылки |creating-links] на другие презентеры и действия вот так: ```latte -product detail +product detail ``` Просто напишите привычную пару `Презентер:действие` вместо настоящего URL и добавьте нужные параметры. Хитрость в `n:href`, которая говорит Nette обработать этот атрибут. Он затем породит: diff --git a/application/ru/presenters.texy b/application/ru/presenters.texy index 3adcc01fcc..5e72db6d5f 100644 --- a/application/ru/presenters.texy +++ b/application/ru/presenters.texy @@ -164,7 +164,7 @@ $url = $this->link('Product:show', [$id, 'lang' => 'en']); В шаблоне ссылки на другие презентеры и действия создаются так: ```latte -product detail +product detail ``` Просто напишите привычную пару `Презентер:действие` вместо настоящего URL и добавьте нужные параметры. Хитрость в `n:href`, которая говорит Latte обработать этот атрибут и породить настоящий URL. В Nette вам вообще не нужно думать об URL, только о презентерах и действиях. @@ -282,7 +282,7 @@ class HomePresenter extends Nette\Application\UI\Presenter При создании ссылки значение параметра можно задать напрямую: ```latte -click +click ``` @@ -330,13 +330,13 @@ class ProductPresenter extends Nette\Application\UI\Presenter При создании ссылки значение постоянного параметра можно изменить: ```latte -detail in Czech +detail in Czech ``` Как вариант, его можно *сбросить*, то есть убрать из URL. Тогда он примет значение по умолчанию: ```latte -click +click ``` diff --git a/application/tr/ajax.texy b/application/tr/ajax.texy index 77de245dba..68afb4e5cb 100644 --- a/application/tr/ajax.texy +++ b/application/tr/ajax.texy @@ -209,7 +209,7 @@ Tamam {control productGrid} çalışmaz: -{control productGrid $arg, $arg} +{control productGrid, $arg, $arg} {control productGrid:paginator} ``` diff --git a/application/tr/components.texy b/application/tr/components.texy index 2d08ea1a4d..3817132cbc 100644 --- a/application/tr/components.texy +++ b/application/tr/components.texy @@ -107,7 +107,7 @@ public function render(): void `{control}` etiketi, `render()` metoduna parametre aktarmayı sağlar: ```latte -{control poll $id, $message} +{control poll, $id, $message} ``` ```php .{file:PollControl.php} @@ -136,7 +136,7 @@ Daha iyi anlamak için bu etiketin PHP koduna nasıl çevrildiğini bilmek iyidi ```latte {control poll} -{control poll:paginator 123, 'hello'} +{control poll:paginator, 123, 'hello'} ``` şuna çevrilir: @@ -200,7 +200,7 @@ public function handleClick(int $x, int $y): void Sinyal çağıran bir bağlantı her zamanki gibi oluşturulur; yani şablonda `n:href` niteliğiyle veya `{link}` etiketiyle, kodda `link()` metoduyla. Daha fazlası [URL bağlantıları oluşturma |creating-links#Sinyallere bağlantılar] bölümünde. ```latte -buraya tıkla +buraya tıkla ``` Sinyal her zaman geçerli presenter ve eylem üzerinde çağrılır; başka bir presenter veya eylem üzerinde çağırmak mümkün değildir. @@ -281,13 +281,13 @@ class PaginatingControl extends Control Bağlantı oluştururken kalıcı parametrenin değeri değiştirilebilir: ```latte -sonraki +sonraki ``` Ya da *sıfırlanabilir*, yani URL'den kaldırılabilir. O zaman varsayılan değerini alır: ```latte -sıfırla +sıfırla ``` diff --git a/application/tr/creating-links.texy b/application/tr/creating-links.texy index ca11c0a42b..b07aec4313 100644 --- a/application/tr/creating-links.texy +++ b/application/tr/creating-links.texy @@ -29,13 +29,13 @@ Bağlantıları çoğu zaman şablonlarda oluştururuz ve `n:href` niteliği har Bir bağlantıya tıklamak, basitçe söylersek, `ProductPresenter::renderShow()` metodunu çağırmak gibi bir şeydir. İmzasında parametreler varsa onu argümanlarla çağırabiliriz: ```latte -ürün detayı +ürün detayı ``` Adlandırılmış parametreler de aktarılabilir. Aşağıdaki bağlantı, `lang` parametresini `en` değeriyle aktarır: ```latte -ürün detayı +ürün detayı ``` `ProductPresenter::renderShow()` metodunun imzasında `$lang` yoksa, parametrenin değerini `$lang = $this->getParameter('lang')` ile veya bir [özellikten |presenters#İsteğin parametreleri] alabilir. @@ -162,7 +162,7 @@ Bu sırada `action()` veya (`action()` tanımlı değilse) `render Elbette parametreleri doğrudan belirtmek de mümkündür: ```latte -yenile +yenile ``` `isLinkCurrent()` fonksiyonu, bağlantının hedefinin geçerli sayfayla aynı olup olmadığını denetler. Bu, örneğin şablonda bağlantıları ayırt etmek için kullanılabilir. diff --git a/application/tr/how-it-works.texy b/application/tr/how-it-works.texy index 14887db71f..ef92ef9b8a 100644 --- a/application/tr/how-it-works.texy +++ b/application/tr/how-it-works.texy @@ -150,7 +150,7 @@ Az önce birçok yeni kavramla karşılaşmış olabilirsiniz, ama bunların anl Şablonda başka presenter'lara ve eylemlere şöyle [bağlantı oluşturursunuz |creating-links]: ```latte -ürün detayı +ürün detayı ``` Gerçek URL yerine tanıdık `Presenter:eylem` çiftini yazın ve gerekli parametreleri ekleyin. İşin püf noktası, Nette'e bu niteliği işlemesini söyleyen `n:href`'tir. Şunu üretecektir: diff --git a/application/tr/presenters.texy b/application/tr/presenters.texy index 842739248d..eba4206c70 100644 --- a/application/tr/presenters.texy +++ b/application/tr/presenters.texy @@ -164,7 +164,7 @@ $url = $this->link('Product:show', [$id, 'lang' => 'en']); Şablonda başka presenter'lara ve eylemlere bağlantılar şöyle oluşturulur: ```latte -ürün detayı +ürün detayı ``` Gerçek URL yerine tanıdık `Presenter:eylem` çiftini yazın ve gerekli parametreleri ekleyin. İşin püf noktası, Latte'ye bu niteliği işlemesini ve gerçek URL'yi üretmesini söyleyen `n:href`'tir. Nette'te URL'leri hiç düşünmeniz gerekmez, yalnızca presenter'ları ve eylemleri. @@ -282,7 +282,7 @@ class HomePresenter extends Nette\Application\UI\Presenter Bağlantı oluştururken parametrenin değerini doğrudan ayarlayabilirsiniz: ```latte -tıkla +tıkla ``` @@ -330,13 +330,13 @@ class ProductPresenter extends Nette\Application\UI\Presenter Bağlantı oluştururken kalıcı parametrenin değeri değiştirilebilir: ```latte -Çekçe detay +Çekçe detay ``` Ya da *sıfırlanabilir*, yani URL'den kaldırılabilir. O zaman varsayılan değerini alır: ```latte -tıkla +tıkla ``` diff --git a/best-practices/cs/dynamic-snippets.texy b/best-practices/cs/dynamic-snippets.texy index 5e5821f8a8..7a8f806fc3 100644 --- a/best-practices/cs/dynamic-snippets.texy +++ b/best-practices/cs/dynamic-snippets.texy @@ -27,9 +27,9 @@ public function handleUnlike(int $articleId): void

{$article->title}

{$article->content}
{if !$article->liked} - to se mi líbí + to se mi líbí {else} - už se mi to nelíbí + už se mi to nelíbí {/if} ``` @@ -56,9 +56,9 @@ Dynamický snippet znamená v terminologii Latte specifický případ užití zn
{$article->content}
{snippet article-{$article->id}} {if !$article->liked} - to se mi líbí + to se mi líbí {else} - už se mi to nelíbí + už se mi to nelíbí {/if} {/snippet} diff --git a/best-practices/cs/post-links.texy b/best-practices/cs/post-links.texy index 5926f5a880..f986978b31 100644 --- a/best-practices/cs/post-links.texy +++ b/best-practices/cs/post-links.texy @@ -17,8 +17,8 @@ Díky tomuto formuláři můžete místo klasického odkazu `` použít tlač {$post->title} - - + + diff --git a/best-practices/de/dynamic-snippets.texy b/best-practices/de/dynamic-snippets.texy index 8d1b40f455..ba9c59e815 100644 --- a/best-practices/de/dynamic-snippets.texy +++ b/best-practices/de/dynamic-snippets.texy @@ -27,9 +27,9 @@ Template:

{$article->title}

{$article->content}
{if !$article->liked} -
gefällt mir + gefällt mir {else} - gefällt mir nicht mehr + gefällt mir nicht mehr {/if} ``` @@ -56,9 +56,9 @@ Ein dynamisches Snippet bezeichnet in der Terminologie von Latte den speziellen
{$article->content}
{snippet article-{$article->id}} {if !$article->liked} - gefällt mir + gefällt mir {else} - gefällt mir nicht mehr + gefällt mir nicht mehr {/if} {/snippet} diff --git a/best-practices/de/post-links.texy b/best-practices/de/post-links.texy index 8f654ea3e5..a50a492a2b 100644 --- a/best-practices/de/post-links.texy +++ b/best-practices/de/post-links.texy @@ -17,8 +17,8 @@ Dank dieses Formulars können Sie statt eines klassischen Links `` eine Schal {$post->title} - - + + diff --git a/best-practices/en/dynamic-snippets.texy b/best-practices/en/dynamic-snippets.texy index 28e52df8d9..7eed68941c 100644 --- a/best-practices/en/dynamic-snippets.texy +++ b/best-practices/en/dynamic-snippets.texy @@ -27,9 +27,9 @@ Template:

{$article->title}

{$article->content}
{if !$article->liked} -
I like it + I like it {else} - I don't like it anymore + I don't like it anymore {/if} ``` @@ -56,9 +56,9 @@ In Latte terminology, a dynamic snippet refers to a specific use of the `{snippe
{$article->content}
{snippet article-{$article->id}} {if !$article->liked} - I like it + I like it {else} - I don't like it anymore + I don't like it anymore {/if} {/snippet} diff --git a/best-practices/en/post-links.texy b/best-practices/en/post-links.texy index 5a6461963d..04d886f05a 100644 --- a/best-practices/en/post-links.texy +++ b/best-practices/en/post-links.texy @@ -17,8 +17,8 @@ Thanks to this form, instead of a standard `` link, you can use a ` - + + diff --git a/best-practices/es/dynamic-snippets.texy b/best-practices/es/dynamic-snippets.texy index 2861259396..dace88c1d9 100644 --- a/best-practices/es/dynamic-snippets.texy +++ b/best-practices/es/dynamic-snippets.texy @@ -27,9 +27,9 @@ Plantilla:

{$article->title}

{$article->content}
{if !$article->liked} -
I like it + I like it {else} - I don't like it anymore + I don't like it anymore {/if} ``` @@ -56,9 +56,9 @@ En la terminología de Latte, un snippet dinámico es un uso concreto de la etiq
{$article->content}
{snippet article-{$article->id}} {if !$article->liked} - I like it + I like it {else} - I don't like it anymore + I don't like it anymore {/if} {/snippet} diff --git a/best-practices/es/post-links.texy b/best-practices/es/post-links.texy index 25956231fa..53aa4d10ea 100644 --- a/best-practices/es/post-links.texy +++ b/best-practices/es/post-links.texy @@ -17,8 +17,8 @@ Gracias a este formulario, en lugar de un enlace `` corriente puede usar un ` {$post->title} - - + + diff --git a/best-practices/fr/dynamic-snippets.texy b/best-practices/fr/dynamic-snippets.texy index 98fbbb5ca0..ed6f1cdd8e 100644 --- a/best-practices/fr/dynamic-snippets.texy +++ b/best-practices/fr/dynamic-snippets.texy @@ -27,9 +27,9 @@ Template :

{$article->title}

{$article->content}
{if !$article->liked} -
J'aime + J'aime {else} - Je n'aime plus + Je n'aime plus {/if} ``` @@ -56,9 +56,9 @@ Dans la terminologie de Latte, un snippet dynamique désigne un usage particulie
{$article->content}
{snippet article-{$article->id}} {if !$article->liked} - J'aime + J'aime {else} - Je n'aime plus + Je n'aime plus {/if} {/snippet} diff --git a/best-practices/fr/post-links.texy b/best-practices/fr/post-links.texy index fba0b19720..e77ed7b7d7 100644 --- a/best-practices/fr/post-links.texy +++ b/best-practices/fr/post-links.texy @@ -17,8 +17,8 @@ Grâce à ce formulaire, au lieu d'un lien `` classique, vous pouvez utiliser {$post->title} - - + + diff --git a/best-practices/it/dynamic-snippets.texy b/best-practices/it/dynamic-snippets.texy index 850c70251b..cb506c1be9 100644 --- a/best-practices/it/dynamic-snippets.texy +++ b/best-practices/it/dynamic-snippets.texy @@ -27,9 +27,9 @@ Template:

{$article->title}

{$article->content}
{if !$article->liked} -
Mi piace + Mi piace {else} - Non mi piace più + Non mi piace più {/if} ``` @@ -56,9 +56,9 @@ Nella terminologia di Latte, snippet dinamico indica un uso particolare del tag
{$article->content}
{snippet article-{$article->id}} {if !$article->liked} - Mi piace + Mi piace {else} - Non mi piace più + Non mi piace più {/if} {/snippet} diff --git a/best-practices/it/post-links.texy b/best-practices/it/post-links.texy index 6d69060c47..875151fe53 100644 --- a/best-practices/it/post-links.texy +++ b/best-practices/it/post-links.texy @@ -17,8 +17,8 @@ Grazie a questo form, al posto di un normale link `` potete usare un ` - + + diff --git a/best-practices/ja/dynamic-snippets.texy b/best-practices/ja/dynamic-snippets.texy index b6ed42e44c..fa5595934c 100644 --- a/best-practices/ja/dynamic-snippets.texy +++ b/best-practices/ja/dynamic-snippets.texy @@ -27,9 +27,9 @@ public function handleUnlike(int $articleId): void

{$article->title}

{$article->content}
{if !$article->liked} -
いいね + いいね {else} - いいねを取り消す + いいねを取り消す {/if} ``` @@ -56,9 +56,9 @@ Latte の用語でいう動的スニペットとは、スニペットの名前
{$article->content}
{snippet article-{$article->id}} {if !$article->liked} - いいね + いいね {else} - いいねを取り消す + いいねを取り消す {/if} {/snippet} diff --git a/best-practices/ja/post-links.texy b/best-practices/ja/post-links.texy index 622400350a..535c45a8cd 100644 --- a/best-practices/ja/post-links.texy +++ b/best-practices/ja/post-links.texy @@ -17,8 +17,8 @@ POST リンクの正しい使い方 {$post->title} - - + + diff --git a/best-practices/pl/dynamic-snippets.texy b/best-practices/pl/dynamic-snippets.texy index 3144061cd0..568db2a845 100644 --- a/best-practices/pl/dynamic-snippets.texy +++ b/best-practices/pl/dynamic-snippets.texy @@ -27,9 +27,9 @@ Szablon:

{$article->title}

{$article->content}
{if !$article->liked} - lubię to + lubię to {else} - już tego nie lubię + już tego nie lubię {/if} ``` @@ -56,9 +56,9 @@ W terminologii Latte dynamiczny snippet oznacza szczególne użycie tagu `{snipp
{$article->content}
{snippet article-{$article->id}} {if !$article->liked} - lubię to + lubię to {else} - już tego nie lubię + już tego nie lubię {/if} {/snippet} diff --git a/best-practices/pl/post-links.texy b/best-practices/pl/post-links.texy index a4f6d15cb3..3a5bd48092 100644 --- a/best-practices/pl/post-links.texy +++ b/best-practices/pl/post-links.texy @@ -17,8 +17,8 @@ Dzięki temu formularzowi zamiast zwykłego odnośnika `` możesz użyć ` {$post->title} - - + + diff --git a/best-practices/ru/dynamic-snippets.texy b/best-practices/ru/dynamic-snippets.texy index 65cd823467..518a2838e2 100644 --- a/best-practices/ru/dynamic-snippets.texy +++ b/best-practices/ru/dynamic-snippets.texy @@ -27,9 +27,9 @@ public function handleUnlike(int $articleId): void

{$article->title}

{$article->content}
{if !$article->liked} -
I like it + I like it {else} - I don't like it anymore + I don't like it anymore {/if} ``` @@ -56,9 +56,9 @@ public function handleUnlike(int $articleId): void
{$article->content}
{snippet article-{$article->id}} {if !$article->liked} - I like it + I like it {else} - I don't like it anymore + I don't like it anymore {/if} {/snippet} diff --git a/best-practices/ru/post-links.texy b/best-practices/ru/post-links.texy index 6560e736a0..fd92f9326f 100644 --- a/best-practices/ru/post-links.texy +++ b/best-practices/ru/post-links.texy @@ -17,8 +17,8 @@ {$post->title} - - + + diff --git a/best-practices/tr/dynamic-snippets.texy b/best-practices/tr/dynamic-snippets.texy index 77edc5fcf3..1cb0d6d957 100644 --- a/best-practices/tr/dynamic-snippets.texy +++ b/best-practices/tr/dynamic-snippets.texy @@ -27,9 +27,9 @@ public function handleUnlike(int $articleId): void

{$article->title}

{$article->content}
{if !$article->liked} - Beğendim + Beğendim {else} - Artık beğenmiyorum + Artık beğenmiyorum {/if} ``` @@ -56,9 +56,9 @@ Latte terminolojisinde dinamik snippet, `{snippet}` etiketinin snippet adında b
{$article->content}
{snippet article-{$article->id}} {if !$article->liked} - Beğendim + Beğendim {else} - Artık beğenmiyorum + Artık beğenmiyorum {/if} {/snippet} diff --git a/best-practices/tr/post-links.texy b/best-practices/tr/post-links.texy index 9dee9339a5..790f444fc0 100644 --- a/best-practices/tr/post-links.texy +++ b/best-practices/tr/post-links.texy @@ -17,8 +17,8 @@ Bu form sayesinde, standart bir `` bağlantısı yerine bir ` - + + diff --git a/latte/cs/cookbook/passing-variables.texy b/latte/cs/cookbook/passing-variables.texy index 90ddda4bfb..ad60a30671 100644 --- a/latte/cs/cookbook/passing-variables.texy +++ b/latte/cs/cookbook/passing-variables.texy @@ -52,7 +52,7 @@ Tag `{define}` slouží k vytváření bloků, které se vykreslí až po zavol {* má přístup ke všem vstupním proměnným šablony *} {/define} -{define hello $name} +{define hello, $name} {* má přístup k parametru $name a vstupním proměnným *} {/define} ``` diff --git a/latte/de/cookbook/passing-variables.texy b/latte/de/cookbook/passing-variables.texy index d547a7cf75..a1040a144f 100644 --- a/latte/de/cookbook/passing-variables.texy +++ b/latte/de/cookbook/passing-variables.texy @@ -52,7 +52,7 @@ Der Tag `{define}` dient dazu, Blöcke zu erstellen, die erst beim Aufruf mit `{ {* hat Zugriff auf alle Eingabevariablen des Templates *} {/define} -{define hello $name} +{define hello, $name} {* hat Zugriff auf den Parameter $name und die Eingabevariablen *} {/define} ``` diff --git a/latte/en/cookbook/passing-variables.texy b/latte/en/cookbook/passing-variables.texy index d6722af606..7606dd2222 100644 --- a/latte/en/cookbook/passing-variables.texy +++ b/latte/en/cookbook/passing-variables.texy @@ -52,7 +52,7 @@ The `{define}` tag is used to create blocks that are rendered only when called u {* has access to all input variables of the template *} {/define} -{define hello $name} +{define hello, $name} {* has access to the $name parameter and input variables *} {/define} ``` diff --git a/latte/es/cookbook/passing-variables.texy b/latte/es/cookbook/passing-variables.texy index 7a3aed772b..2ea4bf3323 100644 --- a/latte/es/cookbook/passing-variables.texy +++ b/latte/es/cookbook/passing-variables.texy @@ -52,7 +52,7 @@ La etiqueta `{define}` sirve para crear bloques que se renderizan solo cuando se {* has access to all input variables of the template *} {/define} -{define hello $name} +{define hello, $name} {* has access to the $name parameter and input variables *} {/define} ``` diff --git a/latte/fr/cookbook/passing-variables.texy b/latte/fr/cookbook/passing-variables.texy index c2fe982d1a..1d7a47b4fb 100644 --- a/latte/fr/cookbook/passing-variables.texy +++ b/latte/fr/cookbook/passing-variables.texy @@ -52,7 +52,7 @@ La balise `{define}` sert à créer des blocs qui ne sont rendus qu'une fois app {* a accès à toutes les variables d'entrée du template *} {/define} -{define hello $name} +{define hello, $name} {* a accès au paramètre $name et aux variables d'entrée *} {/define} ``` diff --git a/latte/it/cookbook/passing-variables.texy b/latte/it/cookbook/passing-variables.texy index 3c95ae9a79..2e8773d3d8 100644 --- a/latte/it/cookbook/passing-variables.texy +++ b/latte/it/cookbook/passing-variables.texy @@ -52,7 +52,7 @@ Il tag `{define}` serve a creare blocchi che vengono renderizzati solo quando li {* ha accesso a tutte le variabili di ingresso del template *} {/define} -{define hello $name} +{define hello, $name} {* ha accesso al parametro $name e alle variabili di ingresso *} {/define} ``` diff --git a/latte/ja/cookbook/passing-variables.texy b/latte/ja/cookbook/passing-variables.texy index c5d6a8e430..77c398df1e 100644 --- a/latte/ja/cookbook/passing-variables.texy +++ b/latte/ja/cookbook/passing-variables.texy @@ -52,7 +52,7 @@ $latte->render('template.latte', ['userName' => 'Jan', 'userAge' => 30]); {* テンプレートのすべての入力変数にアクセスできます *} {/define} -{define hello $name} +{define hello, $name} {* $name パラメータと入力変数にアクセスできます *} {/define} ``` diff --git a/latte/pl/cookbook/passing-variables.texy b/latte/pl/cookbook/passing-variables.texy index a7f23cf07f..64ee340426 100644 --- a/latte/pl/cookbook/passing-variables.texy +++ b/latte/pl/cookbook/passing-variables.texy @@ -52,7 +52,7 @@ Tag `{define}` służy do tworzenia bloków, które są renderowane dopiero po w {* ma dostęp do wszystkich zmiennych wejściowych szablonu *} {/define} -{define hello $name} +{define hello, $name} {* ma dostęp do parametru $name i zmiennych wejściowych *} {/define} ``` diff --git a/latte/ru/cookbook/passing-variables.texy b/latte/ru/cookbook/passing-variables.texy index 34371c45b8..a40e7513f3 100644 --- a/latte/ru/cookbook/passing-variables.texy +++ b/latte/ru/cookbook/passing-variables.texy @@ -52,7 +52,7 @@ $latte->render('template.latte', ['userName' => 'Jan', 'userAge' => 30]); {* имеет доступ ко всем входным переменным шаблона *} {/define} -{define hello $name} +{define hello, $name} {* имеет доступ к параметру $name и входным переменным *} {/define} ``` diff --git a/latte/tr/cookbook/passing-variables.texy b/latte/tr/cookbook/passing-variables.texy index f701b2fc72..2610d5c938 100644 --- a/latte/tr/cookbook/passing-variables.texy +++ b/latte/tr/cookbook/passing-variables.texy @@ -52,7 +52,7 @@ $latte->render('template.latte', ['userName' => 'Jan', 'userAge' => 30]); {* şablonun tüm girdi değişkenlerine erişebilir *} {/define} -{define hello $name} +{define hello, $name} {* $name parametresine ve girdi değişkenlerine erişebilir *} {/define} ``` diff --git a/quickstart/cs/creating-posts.texy b/quickstart/cs/creating-posts.texy index bc2cf6f126..7005fb7e59 100644 --- a/quickstart/cs/creating-posts.texy +++ b/quickstart/cs/creating-posts.texy @@ -175,7 +175,7 @@ Kde se však onen parametr `id` vezme? Jedná se o parametr, který byl vložen Nyní můžeme přidat odkaz do šablony `app/Presentation/Post/show.latte`: ```latte -Upravit příspěvek +Upravit příspěvek ``` diff --git a/quickstart/cs/single-post.texy b/quickstart/cs/single-post.texy index 32aac55f41..495da8acfe 100644 --- a/quickstart/cs/single-post.texy +++ b/quickstart/cs/single-post.texy @@ -40,7 +40,7 @@ Do šablony `Home/default.latte` vložíme odkaz na akci `Post:show`. ```latte .{file:app/Presentation/Home/default.latte} ... -

{$post->title}

+

{$post->title}

... ``` @@ -51,7 +51,7 @@ Totéž můžeme zapsat zkráceně pomocí n:atributu: ```latte .{file:app/Presentation/Home/default.latte} ... -

{$post->title}

+

{$post->title}

... ``` diff --git a/quickstart/de/creating-posts.texy b/quickstart/de/creating-posts.texy index 47c277b90f..9f96686202 100644 --- a/quickstart/de/creating-posts.texy +++ b/quickstart/de/creating-posts.texy @@ -175,7 +175,7 @@ Aber woher kommt die `id`? Es ist der Parameter, der an die Methode `renderEdit` Nun können Sie im Template `app/Presentation/Post/show.latte` einen Link ergänzen: ```latte -Diesen Beitrag bearbeiten +Diesen Beitrag bearbeiten ``` diff --git a/quickstart/de/single-post.texy b/quickstart/de/single-post.texy index 064b80f01b..dd14c86d95 100644 --- a/quickstart/de/single-post.texy +++ b/quickstart/de/single-post.texy @@ -40,7 +40,7 @@ Im Template `Home/default.latte` ergänzen wir einen Link auf die Aktion `Post:s ```latte .{file:app/Presentation/Home/default.latte} ... -

{$post->title}

+

{$post->title}

... ``` @@ -51,7 +51,7 @@ Dasselbe lässt sich mit einem n:Attribut knapper schreiben: ```latte .{file:app/Presentation/Home/default.latte} ... -

{$post->title}

+

{$post->title}

... ``` diff --git a/quickstart/en/creating-posts.texy b/quickstart/en/creating-posts.texy index fd4023c516..43cbba731f 100644 --- a/quickstart/en/creating-posts.texy +++ b/quickstart/en/creating-posts.texy @@ -175,7 +175,7 @@ But where does the `id` come from? It is the parameter passed to the `renderEdit You can now add a link to the `app/Presentation/Post/show.latte` template: ```latte -Edit this post +Edit this post ``` diff --git a/quickstart/en/single-post.texy b/quickstart/en/single-post.texy index 4d182e8030..7d70ea4941 100644 --- a/quickstart/en/single-post.texy +++ b/quickstart/en/single-post.texy @@ -40,7 +40,7 @@ In the `Home/default.latte` template, we add a link to the `Post:show` action: ```latte .{file:app/Presentation/Home/default.latte} ... -

{$post->title}

+

{$post->title}

... ``` @@ -51,7 +51,7 @@ The same can be written concisely using an n:attribute: ```latte .{file:app/Presentation/Home/default.latte} ... -

{$post->title}

+

{$post->title}

... ``` diff --git a/quickstart/es/creating-posts.texy b/quickstart/es/creating-posts.texy index e774bc1302..b6dd495c6a 100644 --- a/quickstart/es/creating-posts.texy +++ b/quickstart/es/creating-posts.texy @@ -175,7 +175,7 @@ Cuando se indica el parámetro `id`, significa que se está editando un artícul Ahora puede añadir un enlace a la plantilla `app/Presentation/Post/show.latte`: ```latte -Edit this post +Edit this post ``` diff --git a/quickstart/es/single-post.texy b/quickstart/es/single-post.texy index bde46a80d9..96d7631d4e 100644 --- a/quickstart/es/single-post.texy +++ b/quickstart/es/single-post.texy @@ -40,7 +40,7 @@ En la plantilla `Home/default.latte` añadimos un enlace a la acción `Post:show ```latte .{file:app/Presentation/Home/default.latte} ... -

{$post->title}

+

{$post->title}

... ``` @@ -51,7 +51,7 @@ Lo mismo se puede escribir de forma concisa con un n:atributo: ```latte .{file:app/Presentation/Home/default.latte} ... -

{$post->title}

+

{$post->title}

... ``` diff --git a/quickstart/fr/creating-posts.texy b/quickstart/fr/creating-posts.texy index 9c034af007..5a818c6959 100644 --- a/quickstart/fr/creating-posts.texy +++ b/quickstart/fr/creating-posts.texy @@ -175,7 +175,7 @@ Mais d'où vient l'`id` ? C'est le paramètre passé à la méthode `renderEdit` Vous pouvez maintenant ajouter un lien au template `app/Presentation/Post/show.latte` : ```latte -Éditer cet article +Éditer cet article ``` diff --git a/quickstart/fr/single-post.texy b/quickstart/fr/single-post.texy index 6829f88755..9728bdddfe 100644 --- a/quickstart/fr/single-post.texy +++ b/quickstart/fr/single-post.texy @@ -40,7 +40,7 @@ Dans le template `Home/default.latte`, nous ajoutons un lien vers l'action `Post ```latte .{file:app/Presentation/Home/default.latte} ... -

{$post->title}

+

{$post->title}

... ``` @@ -51,7 +51,7 @@ La même chose peut s'écrire brièvement à l'aide d'un n:attribut : ```latte .{file:app/Presentation/Home/default.latte} ... -

{$post->title}

+

{$post->title}

... ``` diff --git a/quickstart/it/creating-posts.texy b/quickstart/it/creating-posts.texy index 70814aa8a5..ec9040b9d1 100644 --- a/quickstart/it/creating-posts.texy +++ b/quickstart/it/creating-posts.texy @@ -175,7 +175,7 @@ Ma da dove viene l'`id`? È il parametro passato al metodo `renderEdit`. Ora potete aggiungere un link al template `app/Presentation/Post/show.latte`: ```latte -Modifica questo articolo +Modifica questo articolo ``` diff --git a/quickstart/it/single-post.texy b/quickstart/it/single-post.texy index 8a86441490..95920895a9 100644 --- a/quickstart/it/single-post.texy +++ b/quickstart/it/single-post.texy @@ -40,7 +40,7 @@ Nel template `Home/default.latte` aggiungiamo un link all'azione `Post:show`: ```latte .{file:app/Presentation/Home/default.latte} ... -

{$post->title}

+

{$post->title}

... ``` @@ -51,7 +51,7 @@ La stessa cosa si può scrivere in modo conciso con un n:attributo: ```latte .{file:app/Presentation/Home/default.latte} ... -

{$post->title}

+

{$post->title}

... ``` diff --git a/quickstart/ja/creating-posts.texy b/quickstart/ja/creating-posts.texy index 2d6fa2198b..89af69142d 100644 --- a/quickstart/ja/creating-posts.texy +++ b/quickstart/ja/creating-posts.texy @@ -175,7 +175,7 @@ private function postFormSucceeded(array $data): void これで `app/Presentation/Post/show.latte` のテンプレートにリンクを足せます。 ```latte -この記事を編集 +この記事を編集 ``` diff --git a/quickstart/ja/single-post.texy b/quickstart/ja/single-post.texy index ab08275ac4..bd11989d73 100644 --- a/quickstart/ja/single-post.texy +++ b/quickstart/ja/single-post.texy @@ -40,7 +40,7 @@ final class PostPresenter extends Nette\Application\UI\Presenter ```latte .{file:app/Presentation/Home/default.latte} ... -

{$post->title}

+

{$post->title}

... ``` @@ -51,7 +51,7 @@ final class PostPresenter extends Nette\Application\UI\Presenter ```latte .{file:app/Presentation/Home/default.latte} ... -

{$post->title}

+

{$post->title}

... ``` diff --git a/quickstart/pl/creating-posts.texy b/quickstart/pl/creating-posts.texy index ecb31166a5..b843c646e8 100644 --- a/quickstart/pl/creating-posts.texy +++ b/quickstart/pl/creating-posts.texy @@ -175,7 +175,7 @@ Ale skąd bierze się `id`? To parametr przekazywany metodzie `renderEdit`. Możesz teraz dodać odnośnik do szablonu `app/Presentation/Post/show.latte`: ```latte -Edytuj ten wpis +Edytuj ten wpis ``` diff --git a/quickstart/pl/single-post.texy b/quickstart/pl/single-post.texy index f1ad6b0039..3b4d1a8578 100644 --- a/quickstart/pl/single-post.texy +++ b/quickstart/pl/single-post.texy @@ -40,7 +40,7 @@ W szablonie `Home/default.latte` dodajemy odnośnik do akcji `Post:show`: ```latte .{file:app/Presentation/Home/default.latte} ... -

{$post->title}

+

{$post->title}

... ``` @@ -51,7 +51,7 @@ To samo można zapisać zwięźle za pomocą n:atrybutu: ```latte .{file:app/Presentation/Home/default.latte} ... -

{$post->title}

+

{$post->title}

... ``` diff --git a/quickstart/ru/creating-posts.texy b/quickstart/ru/creating-posts.texy index ccd7562c63..173e08c33c 100644 --- a/quickstart/ru/creating-posts.texy +++ b/quickstart/ru/creating-posts.texy @@ -175,7 +175,7 @@ private function postFormSucceeded(array $data): void Теперь вы можете добавить ссылку в шаблон `app/Presentation/Post/show.latte`: ```latte -Редактировать эту запись +Редактировать эту запись ``` diff --git a/quickstart/ru/single-post.texy b/quickstart/ru/single-post.texy index 6b37595f06..ea53197643 100644 --- a/quickstart/ru/single-post.texy +++ b/quickstart/ru/single-post.texy @@ -40,7 +40,7 @@ final class PostPresenter extends Nette\Application\UI\Presenter ```latte .{file:app/Presentation/Home/default.latte} ... -

{$post->title}

+

{$post->title}

... ``` @@ -51,7 +51,7 @@ final class PostPresenter extends Nette\Application\UI\Presenter ```latte .{file:app/Presentation/Home/default.latte} ... -

{$post->title}

+

{$post->title}

... ``` diff --git a/quickstart/tr/creating-posts.texy b/quickstart/tr/creating-posts.texy index bec2464229..d8903a136c 100644 --- a/quickstart/tr/creating-posts.texy +++ b/quickstart/tr/creating-posts.texy @@ -175,7 +175,7 @@ Peki `id` nereden geliyor? O, `renderEdit` metoduna aktarılan parametredir. Artık `app/Presentation/Post/show.latte` şablonuna bir bağlantı ekleyebilirsiniz: ```latte -Bu gönderiyi düzenle +Bu gönderiyi düzenle ``` diff --git a/quickstart/tr/single-post.texy b/quickstart/tr/single-post.texy index b1862221e9..f9d9e819d9 100644 --- a/quickstart/tr/single-post.texy +++ b/quickstart/tr/single-post.texy @@ -40,7 +40,7 @@ final class PostPresenter extends Nette\Application\UI\Presenter ```latte .{file:app/Presentation/Home/default.latte} ... -

{$post->title}

+

{$post->title}

... ``` @@ -51,7 +51,7 @@ Aynı şey bir n:attribute ile derli toplu biçimde yazılabilir: ```latte .{file:app/Presentation/Home/default.latte} ... -

{$post->title}

+

{$post->title}

... ``` From 67ba2a91eb63dd9b394354b90de587f7e3732e39 Mon Sep 17 00:00:00 2001 From: David Grudl Date: Sat, 7 Nov 2026 15:17:34 +0100 Subject: [PATCH 3/7] caching: split into an overview and the pages Expiration and Invalidation and Storages --- caching/cs/@home.texy | 467 +++++++++---------------------------- caching/cs/@left-menu.texy | 2 + caching/cs/expiration.texy | 241 +++++++++++++++++++ caching/cs/storages.texy | 190 +++++++++++++++ caching/en/@home.texy | 461 +++++++++--------------------------- caching/en/@left-menu.texy | 2 + caching/en/expiration.texy | 241 +++++++++++++++++++ caching/en/storages.texy | 190 +++++++++++++++ 8 files changed, 1077 insertions(+), 717 deletions(-) create mode 100644 caching/cs/expiration.texy create mode 100644 caching/cs/storages.texy create mode 100644 caching/en/expiration.texy create mode 100644 caching/en/storages.texy diff --git a/caching/cs/@home.texy b/caching/cs/@home.texy index b8af5ba974..91206c54bf 100644 --- a/caching/cs/@home.texy +++ b/caching/cs/@home.texy @@ -3,16 +3,17 @@ Nette Caching
-Cache zrychlí vaši aplikaci tím, že jednou náročně získaná data uloží pro příští použití. Ukážeme si: +Počítá vaše aplikace pořád dokola totéž, třeba převádí článek do HTML, spouští pomalý databázový dotaz nebo volá vzdálené API? Nette Caching si výsledek zapamatuje a příště ho vrátí ve zlomku času: -- jak používat cache -- jak změnit úložiště -- jak správně cache invalidovat +- Jedna metoda hodnotu přečte z cache, a když tam chybí, vypočítá a uloží ji +- Data vyexpirují po čase, nebo když se změní soubor, jiná položka či vaše vlastní podmínka +- Tagy smažou přesně ty položky, které souvisejí s právě upraveným článkem +- Nával požadavků na chybějící položku server nepřetíží +- Ukládá do souborů, do Memcached nebo SQLite +- Cachuje části šablon Latte
-Používání cache je v Nette velmi snadné, přitom pokrývá i velmi pokročilé potřeby. Je navrženo pro výkon a 100% odolnost. V základu najdete adaptéry pro nejběžnější backendové úložiště. Umožňuje invalidaci založenou na značkách, časovou expiraci, má ochranu proti cache stampede atd. - Instalace ========= @@ -24,318 +25,165 @@ composer require nette/caching ``` -Základní použití -================ - -Středobodem práce s cache neboli mezipamětí je objekt [api:Nette\Caching\Cache]. Vytvoříme si jeho instanci a jako parametr předáme konstruktoru tzv. úložiště. Což je objekt reprezentující místo, kam se budou data fyzicky ukládat (databáze, Memcached, soubory na disku, ...). K úložišti se dostaneme tak, že si jej necháme předat pomocí [dependency injection |dependency-injection:passing-dependencies] s typem `Nette\Caching\Storage`. Vše podstatné se dozvíte v [části Úložiště |#Úložiště]. +První cache +=========== -.[warning] -Ve verzi 3.0 mělo rozhraní ještě prefix `I`, takže název byl `Nette\Caching\IStorage`. A dále konstanty třídy `Cache` byly psané velkými písmeny, takže třeba `Cache::EXPIRE` místo `Cache::Expire`. +Nejlíp se to ukáže na příkladu. Dejme tomu, že provozujete blog. Pokaždé, když někdo otevře článek, načte ho váš kód z databáze a převede jeho text do HTML. Chvíli to trvá a výsledek je pro všechny návštěvníky stejný, dokud článek neupravíte. Ideální kandidát pro cache. -Pro následující ukázky předpokládejme, že máme vytvořený alias `Cache` a v proměnné `$storage` úložiště. +Napíšeme si to jako krátký skript. Nejprve vytvoříme dva objekty: ```php use Nette\Caching\Cache; +use Nette\Caching\Storages\FileStorage; -$storage = /* ... */; // instance of Nette\Caching\Storage -``` - -Cache je vlastně *key-value store*, tedy data čteme a zapisujeme pod klíči stejně jako u asociativních polí. Aplikace se skládají z řady nezávislých částí a pokud všechny budou používat jedno úložiště (představte si jeden adresář na disku), dříve nebo později by došlo ke kolizi klíčů. Nette Framework problém řeší tak, že celý prostor rozděluje na jmenné prostory (podadresáře). Každá část programu pak používá svůj prostor s unikátním názvem a k žádné kolizi již dojít nemůže. - -Název prostoru uvedeme jako druhý parametr konstruktoru třídy Cache: +require __DIR__ . '/vendor/autoload.php'; -```php -$cache = new Cache($storage, 'Full Html Pages'); +$storage = new FileStorage(__DIR__ . '/temp'); +$cache = new Cache($storage, 'articles'); ``` -V případě potřeby lze z existující instance odvodit novou cache ve vnořeném podprostoru pomocí metody `derive()`: +**Úložiště** určuje, kde data fyzicky leží. `FileStorage` je ukládá do souborů v adresáři `temp`, který musí existovat. **Cache** je objekt, se kterým budete pracovat. Jeho druhý argument, `'articles'`, je jmenný prostor: odděluje články od všeho ostatního, co aplikace cachuje, takže dvě části programu mohou použít stejný klíč, aniž by si překážely. -```php -$subCache = $cache->derive('Images'); -``` - -Nyní můžeme pomocí objektu `$cache` z mezipaměti číst a zapisovat do ní. K obojímu slouží metoda `load()`. Prvním argumentem je klíč a druhým PHP callback, který se zavolá, když klíč není nalezen v cache. Callback hodnotu vygeneruje, vrátí a ta se uloží do cache: +Teď to podstatné. Cache funguje jako asociativní pole: hodnoty čtete a zapisujete pod klíči. Metoda `load()` dělá obojí najednou: ```php -$value = $cache->load($key, function () use ($key) { - $computedValue = /* ... */; // náročný výpočet - return $computedValue; +$html = $cache->load("article/$id", function () use ($id) { + return renderArticle($id); // načte článek z databáze a převede ho do HTML }); ``` -Pokud druhý parametr neuvedeme `$value = $cache->load($key)`, vrátí se `null`, pokud položka v cache není. +Proměnná `$id` je ID zobrazovaného článku. Prvním argumentem `load()` je klíč, druhým funkce, které se říká **generátor**. Když klíč v cache ještě není, `load()` generátor zavolá, uloží, co vrátí, a vrátí to vám. Příště už hodnotu v cache najde a vrátí ji rovnou, generátor vůbec nevolá. -.[tip] -Prima je, že do cache lze ukládat jakékoliv serializovatelné struktury, nemusí to být jen řetězce. A totéž platí dokonce i pro klíče. +Všimněte si, že nikde nezjišťujete, jestli už hodnota v cache je. Jen řeknete, jak ji spočítat. -Položku z mezipaměti vymažeme metodou `remove()`: +A co když stejný článek otevře sto návštěvníků zrovna ve chvíli, kdy v cache ještě není, třeba hned po nasazení? Bez ochrany by ho všech sto požadavků renderovalo naráz a mohlo by server přetížit. Takové situaci se říká [cache stampede |https://en.wikipedia.org/wiki/Cache_stampede] a `FileStorage` jí brání: generátor spustí jen první požadavek, ostatní počkají na jeho výsledek. -```php -$cache->remove($key); -``` - -Uložit položku do mezipaměti lze také metodou `$cache->save($key, $data, ?array $dependencies = null)`. Preferovaný je nicméně výše uvedený způsob pomocí `load()`. - - -Memoizace -========= - -Memoizace znamená cachování výsledku volání funkce nebo metody, abyste jej mohli použít příště bez vypočítávání stejné věci znovu a znovu. - -Memoizovaně lze volat metody a funkce pomocí `call(callable $callback, ...$args)`: - -```php -$result = $cache->call('gethostbyaddr', $ip); -``` - -Funkce `gethostbyaddr()` se tak zavolá pro každý parametr `$ip` jen jednou a příště už se vrátí hodnota z cache. +.[tip] +Do cache můžete ukládat jakoukoliv hodnotu, kterou PHP umí serializovat, nejen řetězce: pole, objekty, čísla. Totéž platí i pro klíče. -Také je možné vytvořit si memoizovaný obal nad metodou nebo funkcí, který lze volat až později: +Pokud chcete hodnotu jen přečíst a negenerovat, zavolejte `load()` jen s klíčem; když položka v cache není, vrátí `null`. Metoda `remove()` položku smaže: ```php -function factorial($num) -{ - return /* ... */; -} - -$memoizedFactorial = $cache->wrap('factorial'); - -$result = $memoizedFactorial(5); // poprvé vypočítá -$result = $memoizedFactorial(5); // podruhé z cache +$cache->remove("article/$id"); ``` -Expirace & invalidace -===================== - -S ukládáním do cache je potřeba řešit otázku, kdy se dříve uložená data stanou neplatná. Nette Framework nabízí mechanismus, jak omezit platnost dat nebo je řízeně mazat (v terminologii frameworku "invalidovat"). - -Platnost dat se nastavuje v okamžiku ukládání, a to pomocí třetího parametru metody `save()`, např.: - -```php -$cache->save($key, $value, [ - $cache::Expire => '20 minutes', -]); -``` +Jak dlouho data platí? +====================== -Nebo pomocí parametru `$dependencies` předávaného referencí do callbacku metody `load()`, např.: +Náš článek v cache se teď nikdy nezmění. Jenže co když v něm opravíte překlep? Návštěvníci by dál viděli starou verzi. Musíte cache říct, kdy položka přestává platit. Nejjednodušší je časový limit: ```php -$value = $cache->load($key, function (&$dependencies) { - $dependencies[Cache::Expire] = '20 minutes'; - return /* ... */; +$html = $cache->load("article/$id", function (&$dependencies) use ($id) { + $dependencies[Cache::Expire] = '1 hour'; + return renderArticle($id); }); ``` -Nebo pomocí 3. parametru v metodě `load()`, např.: - -```php -$value = $cache->load($key, function () { - return /* ... */; -}, [Cache::Expire => '20 minutes']); -``` - -V dalších ukázkách budeme předpokládat druhou variantu a tedy existenci proměnné `$dependencies`. +Generátor teď přijímá referencí parametr `$dependencies`. Je to pole, do kterého generátor zapíše, kdy položka vyexpiruje. Říká se mu závislosti, protože na nich závisí platnost položky. Tady je to jedna hodina. +Čas je jen jedna z možností. Položka může vyexpirovat i ve chvíli, kdy se změní soubor nebo jiná položka v cache, případně když to řekne vaše vlastní podmínka. To všechno popisuje stránka [Expirace a invalidace |expiration]. -Expirace --------- -Nejjednodušší expirace představuje časový limit. Takto uložíme do cache data s platností 20 minut: +Smazat přesně to, co se změnilo +=============================== -```php -// akceptuje i počet sekund nebo UNIX timestamp -$dependencies[Cache::Expire] = '20 minutes'; -``` - -Pokud bychom chtěli prodloužit dobu platnosti s každým čtením, lze toho docílit následovně, ale pozor, režie cache tím vzroste: +Časový limit je kompromis: nastavíte ho krátký a cache moc nepomůže, nastavíte dlouhý a návštěvníci vidí stará data. Lepší je smazat článek z cache přesně ve chvíli, kdy ho upravíte. K tomu slouží **tagy**. Položce je přiřadíte jako libovolné řetězce: ```php -$dependencies[Cache::Sliding] = true; -``` - -Šikovná je možnost nechat data vyexpirovat v okamžiku, kdy se změní soubor či některý z více souborů. Toho lze využít třeba při ukládání dat vzniklých zpracováním těchto souborů do cache. Používejte absolutní cesty. - -```php -$dependencies[Cache::Files] = '/path/to/data.yaml'; -// nebo -$dependencies[Cache::Files] = ['/path/to/data1.yaml', '/path/to/data2.yaml']; -``` - -Můžeme nechat položku v cache vyexpirovat ve chvíli, kdy vyexpiruje jiná položka (či některá z více jiných). Což lze využít tehdy, když ukládáme do cache třeba celou HTML stránku a pod jinými klíči její fragmenty. Jakmile se fragment změní, invaliduje se celá stránka. Pokud fragmenty máme uložené pod klíči např. `frag1` a `frag2`, použijeme: - -```php -$dependencies[Cache::Items] = ['frag1', 'frag2']; -``` - -Expiraci lze řídit i pomocí vlastních funkcí nebo statických metod, které vždy při čtení rozhodnou, zda je položka ještě platná. Takto třeba můžeme nechat položku vyexpirovat vždy, když se změní verze PHP. Vytvoříme funkci, která porovná aktuální verzi s parametrem, a při ukládání přidáme mezi závislosti pole ve tvaru `[nazev funkce, ...argumenty]`: - -```php -function checkPhpVersion($ver): bool -{ - return $ver === PHP_VERSION_ID; -} - -$dependencies[Cache::Callbacks] = [ - ['checkPhpVersion', PHP_VERSION_ID] // expiruj když checkPhpVersion(...) === false -]; +$html = $cache->load("article/$id", function (&$dependencies) use ($id) { + $dependencies[Cache::Tags] = ["article/$id", "comments/$id"]; + return renderArticle($id); +}); ``` -Všechna kritéria je samozřejmě možné kombinovat. Cache pak vyexpiruje, když alespoň jedno kritérium není splněno. +Stránka ukazuje článek i s komentáři, proto jsme jí dali dva tagy. V administraci pak hned po uložení upraveného článku do databáze smažete všechno, co nese jeho tag: ```php -$dependencies[Cache::Expire] = '20 minutes'; -$dependencies[Cache::Files] = '/path/to/data.yaml'; +$cache->clean([Cache::Tags => ["article/$id"]]); ``` +A totéž, když někdo přidá komentář, tentokrát s tagem `comments/$id`. Od teď stránka z cache zmizí přesně ve chvíli, kdy se změní její článek nebo komentáře, a další návštěvník dostane čerstvě vyrenderovanou. -Invalidace pomocí tagů ----------------------- - -Velmi užitečným invalidačním nástrojem jsou tzv. tagy. Každé položce v cache můžeme přiřadit seznam tagů, což jsou libovolné řetězce. Mějme třeba HTML stránku s článkem a komentáři, kterou budeme cachovat. Při ukládání uvedeme tagy: - -```php -$dependencies[Cache::Tags] = ["article/$articleId", "comments/$articleId"]; -``` - -Přesuňme se do administrace. Tady najdeme formulář pro editaci článku. Společně s uložením článku do databáze zavoláme metodu `clean()`, která smaže z cache položky dle tagu: +`FileStorage` si pamatuje, která položka nese který tag, v tzv. journalu, malé SQLite databázi. V aplikaci postavené na Nette je nastavený za vás; v našem skriptu ho vytvoříme a předáme úložišti: ```php -$cache->clean([ - $cache::Tags => ["article/$articleId"], -]); -``` - -Stejně tak v místě přidání nového komentáře (nebo editace komentáře) neopomeneme invalidovat příslušný tag: +use Nette\Caching\Storages\SQLiteJournal; -```php -$cache->clean([ - $cache::Tags => ["comments/$articleId"], -]); +$journal = new SQLiteJournal(__DIR__ . '/temp/journal.s3db'); +$storage = new FileStorage(__DIR__ . '/temp', $journal); ``` -Čeho jsme tím dosáhli? Že se nám HTML cache bude invalidovat (mazat), kdykoliv se změní článek nebo komentáře. Když se edituje článek s ID = 10, dojde k vynucené invalidaci tagu `article/10` a HTML stránka, která uvedený tag nese, se z cache smaže. Totéž nastane při vložení nového komentáře pod příslušný článek. - -.[note] -Tagy vyžadují tzv. [#Journal]. - +Kromě tagů můžete mazat položky podle priority nebo celý jmenný prostor najednou. Viz [Expirace a invalidace |expiration#Mazání položek]. -Invalidace pomocí priority --------------------------- -Jednotlivým položkám v cache můžeme nastavit prioritu, pomocí které je bude možné mazat, když třeba cache přesáhne určitou velikost: +Jmenné prostory +=============== -```php -$dependencies[Cache::Priority] = 50; -``` - -Smažeme všechny položky s prioritou rovnou nebo menší než 100: +Jmenný prostor `'articles'` jsme už potkali v konstruktoru cache. Každá část aplikace by měla mít svůj, aby se její klíče nikdy nepotkaly s cizími. Komentáře by mohly mít třeba vlastní cache: ```php -$cache->clean([ - $cache::Priority => 100, -]); +$commentCache = new Cache($storage, 'comments'); ``` -.[note] -Priority vyžadují tzv. [#Journal]. - - -Smazání cache -------------- - -Parametr `Cache::All` smaže vše: +Metoda `derive()` vytvoří cache ve vnořeném jmenném prostoru: `$cache->derive('previews')` dá prostor `previews` uvnitř `articles`. A když chcete zahodit všechno ve jmenném prostoru, zavolejte: ```php -$cache->clean([ - $cache::All => true, -]); +$cache->clean([Cache::Namespaces => ['articles']]); ``` +Ostatní jmenné prostory, i ty vnořené, zůstanou nedotčené. Mazání podle jmenného prostoru funguje s `FileStorage`, ostatní úložiště ho ignorují. Pozor na `Cache::All`, který smaže celé úložiště včetně všech jmenných prostorů. -Hromadné čtení -============== - -Pro hromadné čtení a zápisy do cache slouží metoda `bulkLoad()`, které předáme pole klíčů a získáme pole hodnot: - -```php -$values = $cache->bulkLoad($keys); -``` - -Metoda `bulkLoad()` funguje podobně jako `load()` i s druhým parametrem callbackem, kterému se předává klíč generované položky: -```php -$values = $cache->bulkLoad($keys, function ($key, &$dependencies) { - $computedValue = /* ... */; // náročný výpočet - return $computedValue; -}); -``` +Memoizace +========= -Naopak pro hromadný zápis více položek najednou slouží metoda `bulkSave()`, které předáme pole dvojic `klíč => hodnota` a volitelně závislosti: +Někdy chcete cachovat výsledek volání funkce. V moderaci komentářů třeba ukazujete u každého autora název počítače podle jeho IP adresy. Zjistit ho funkcí `gethostbyaddr()` znamená zeptat se DNS serveru a to může trvat i sekundy. Metoda `call()` zavolá funkci pro každý argument jen jednou a pak vrací výsledek z cache: ```php -$cache->bulkSave([ - $key1 => $value1, - $key2 => $value2, -], [Cache::Expire => '20 minutes']); +$host = $cache->call('gethostbyaddr', $ip); ``` - -Použití s PSR-16 .{data-version:3.3.1} -====================================== - -Pro použití Nette Cache s rozhraním PSR-16 můžete využít adaptér `PsrCacheAdapter`. Umožňuje hladkou integraci mezi Nette Cache a jakýmkoli kódem nebo knihovnou, která očekává PSR-16 kompatibilní cache. +Proměnná `$ip` je IP adresa autora komentáře. Metoda `wrap()` dělá totéž, ale místo aby funkci hned zavolala, vrátí novou funkci, kterou můžete volat později a kolikrát chcete: ```php -$psrCache = new Nette\Bridges\Psr\PsrCacheAdapter($storage); -``` +$getHost = $cache->wrap('gethostbyaddr'); -Nyní můžete používat `$psrCache` jako PSR-16 cache: - -```php -$psrCache->set('key', 'value', 3600); // uloží hodnotu na 1 hodinu -$value = $psrCache->get('key', 'default'); +$host = $getHost($ip); // poprvé se zeptá DNS serveru +$host = $getHost($ip); // podruhé vrátí výsledek z cache ``` -Adaptér podporuje všechny metody definované v PSR-16, včetně `getMultiple()`, `setMultiple()` a `deleteMultiple()`. +Cachování části stránky +======================= -Cachování výstupu -================= - -Velmi elegantně lze zachytávat a cachovat výstup: +Ne všechno, co chcete cachovat, je návratová hodnota. Někdy je to kus HTML, který nějaký kód vypisuje. Ten zachytí metoda `capture()`: ```php -if ($capture = $cache->capture($key)) { - - // echo ... vypisujeme data - - $capture->end(); // uložíme výstup do cache +if ($capture = $cache->capture('sidebar')) { + // echo ... vypíše postranní panel s nejnovějšími články + $capture->end(); // uloží vypsaný výstup do cache } ``` -V případě, že výstup už je v cache uložen, metoda `capture()` ho vypíše a vrátí `null`, tedy podmínka se nevykoná. V opačném případě začne výstup zachytávat a vrátí objekt `$capture`, pomocí něhož nakonec vypsaná data uložíme do cache. - -.[note] -Ve verzi 3.0 se metoda jmenovala `$cache->start()`. +Když už je výstup v cache, `capture()` ho vypíše a vrátí `null`, takže se blok uvnitř `if` vůbec nevykoná. Jinak začne výstup zachytávat a vrátí objekt, jehož metoda `end()` uloží všechno, co se mezitím vypsalo. Můžete jí předat i závislosti, třeba `$capture->end([Cache::Tags => ['articles']])`. Ve verzi 3.0 se metoda `capture()` jmenovala `start()`. Cachování v Latte ================= -Cachování v šablonách [Latte|latte:] je velmi snadné, stačí část šablony obalit značkami `{cache}...{/cache}`. Cache se automaticky invaliduje ve chvíli, kdy se změní zdrojová šablona (včetně případných vložených šablon uvnitř bloku cache). Značky `{cache}` lze vnořovat do sebe a když se vnořený blok zneplatní (například tagem), zneplatní se i blok nadřazený. - -Ve značce je možné uvést klíče, na které se bude cache vázat (zde proměnná `$id`), nastavit expiraci a [tagy pro zneplatnění |#Invalidace pomocí tagů]. +V šablonách [Latte|latte:] je to ještě jednodušší. Část, kterou chcete cachovat, obalíte značkami `{cache}...{/cache}`: ```latte -{cache $id, expire: '20 minutes', tags: [tag1, tag2]} +{cache expire: '20 minutes', tags: [articles]} +

Nejnovější články

... {/cache} ``` -Všechny položky jsou volitelné, takže nemusíme uvádět ani expiraci, ani tagy, nakonec ani klíče. +Blok se automaticky zneplatní, kdykoliv se změní šablona, včetně šablon vložených uvnitř bloku. Bloky lze vnořovat; když se zneplatní vnořený blok, zneplatní se i ten nadřazený. -Použití cache lze také podmínit pomocí `if` - obsah se pak bude cachovat, pouze pokud bude splněna podmínka: +Všechny parametry jsou volitelné. Bez `expire` blok vyexpiruje po 7 dnech. Pokud obsah závisí na proměnné, uveďte ji na začátku a pro každou hodnotu vznikne vlastní kopie v cache: `{cache $article->id}`. A parametr `if` rozhodne, jestli vůbec cachovat: ```latte {cache $id, if: !$form->isSubmitted()} @@ -344,162 +192,61 @@ Použití cache lze také podmínit pomocí `if` - obsah se pak bude cachovat, p ``` -Úložiště -======== - -Úložiště je objekt reprezentující místo, kam se data fyzicky ukládají. Můžeme použít databázi, server Memcached, nebo nejdostupnější úložiště, což jsou soubory na disku. - -|----------------- -| Úložiště | Popis -|----------------- -| [#FileStorage] | výchozí úložiště s ukládáním do souborů na disk -| [#MemcachedStorage] | využívá `Memcached` server -| [#MemoryStorage] | data jsou dočasně v paměti -| [#SQLiteStorage] | data se ukládají do SQLite databáze -| [#DevNullStorage] | data se neukládají, vhodné pro testování - -K objektu úložiště se dostanete tak, že si jej necháte předat pomocí [dependency injection |dependency-injection:passing-dependencies] s typem `Nette\Caching\Storage`. Jako výchozí úložiště poskytuje Nette objekt FileStorage ukládající data do podsložky `cache` v adresáři pro [dočasné soubory |application:bootstrapping#Dočasné soubory]. - -Změnit úložiště můžete v konfiguraci: - -```neon -services: - cache.storage: Nette\Caching\Storages\DevNullStorage -``` - - -FileStorage ------------ - -Zapisuje cache do souborů na disku. Úložiště `Nette\Caching\Storages\FileStorage` je velmi dobře optimalizované pro výkon a především zajišťuje plnou atomicitu operací. Co to znamená? Že při použití cache se nemůže stát, že přečteme soubor, který ještě není jiným vláknem kompletně zapsaný, nebo že by vám jej někdo "pod rukama" smazal. Použití cache je tedy zcela bezpečné. - -Toto úložiště má také vestavěnou důležitou funkci, která brání před extrémním nárůstem využití CPU ve chvíli, kdy se cache smaže nebo ještě není zahřátá (tj. vytvořená). Jedná se o prevenci před "cache stampede":https://en.wikipedia.org/wiki/Cache_stampede. Stává se, že v jednu chvíli se sejde větší počet souběžných požadavků, které chtějí z cache stejnou věc (např. výsledek drahého SQL dotazu) a protože v mezipaměti není, začnou všechny procesy vykonávat stejný SQL dotaz. Vytížení se tak násobí a může se dokonce stát, že žádné vlákno nestihne odpovědět v časovém limitu, cache se nevytvoří a aplikace zkolabuje. Naštěstí cache v Nette funguje tak, že při více souběžných požadavcích na jednu položku ji generuje pouze první vlákno, ostatní čekají a následně využijí vygenerovaný výsledek. - -Příklad vytvoření FileStorage: - -```php -// úložištěm bude adresář '/path/to/temp' na disku -$storage = new Nette\Caching\Storages\FileStorage('/path/to/temp'); -``` - - -MemcachedStorage ----------------- - -Server [Memcached|https://memcached.org] je vysoce výkonný systém ukládání do distribuované paměti, jehož adaptér je `Nette\Caching\Storages\MemcachedStorage`. V konfiguraci uvedeme IP adresu a port, pokud se liší od standardního 11211. - -.[caution] -Vyžaduje PHP rozšíření `memcached`. - -```neon -services: - cache.storage: Nette\Caching\Storages\MemcachedStorage('10.0.0.5') -``` - - -MemoryStorage -------------- - -`Nette\Caching\Storages\MemoryStorage` je úložiště, které data ukládá do PHP pole, a tedy se s ukončením požadavku ztratí. - - -SQLiteStorage -------------- - -Databáze SQLite a adaptér `Nette\Caching\Storages\SQLiteStorage` nabízí způsob, jak ukládat cache do jediného souboru na disku. V konfiguraci uvedeme cestu k tomuto souboru. - -.[caution] -Vyžaduje PHP rozšíření `pdo` a `pdo_sqlite`. - -```neon -services: - cache.storage: Nette\Caching\Storages\SQLiteStorage('%tempDir%/cache.db') -``` +Kam se data ukládají +==================== +Zatím jsme používali `FileStorage`, kterému stačí adresář. Díky atomickým operacím se soubory je bezpečné, i když najednou čte a zapisuje mnoho požadavků. Je to ale jen jedno z několika úložišť: -DevNullStorage --------------- +|---------------------- +| Úložiště | Kde data leží +|---------------------- +| `FileStorage` | v souborech na disku; výchozí úložiště +| `MemcachedStorage` | na serveru Memcached +| `SQLiteStorage` | v souboru databáze SQLite +| `MemoryStorage` | v paměti, jen do konce požadavku +| `DevNullStorage` | nikde; pro testy a pro vypnutí cache -Speciální implementací úložiště je `Nette\Caching\Storages\DevNullStorage`, které ve skutečnosti data neukládá vůbec. Je tak vhodné pro testování, když chceme eliminovat vliv cache. +Úložiště můžete vyměnit, aniž byste sáhli na kód, který cache používá. Které si vybrat, co které umí a jak ho nastavit, včetně vypnutí cache, popisuje stránka [Úložiště |storages]. -Použití cache v kódu -==================== +Cache v aplikaci Nette +====================== -Při používání cache v kódu máme dva způsoby, jak na to. První z nich je ten, že si necháme předat pomocí [dependency injection |dependency-injection:passing-dependencies] úložiště a vytvoříme objekt `Cache`: +V aplikaci postavené na Nette si úložiště sami nevytváříte. Nette poskytuje `FileStorage`, které ukládá data do podadresáře `cache` v adresáři pro [dočasné soubory |application:bootstrapping#Dočasné soubory], a k němu i journal. Dostanete ho pomocí [dependency injection |dependency-injection:passing-dependencies], když si řeknete o typ `Nette\Caching\Storage` (před verzí 3.1 se jmenoval `Nette\Caching\IStorage`), a cache si vytvoříte v konstruktoru: ```php -use Nette; +use Nette\Caching\Cache; +use Nette\Caching\Storage; -class ClassOne +class ArticleFacade { - private Nette\Caching\Cache $cache; - - public function __construct(Nette\Caching\Storage $storage) - { - $this->cache = new Nette\Caching\Cache($storage, 'my-namespace'); - } -} -``` + private Cache $cache; -Druhá možnost je, že si necháme rovnou předat objekt `Cache`: -```php -class ClassTwo -{ - public function __construct( - private Nette\Caching\Cache $cache, - ) { + public function __construct(Storage $storage) + { + $this->cache = new Cache($storage, 'articles'); } } ``` -Objekt `Cache` se potom vytvoří přímo v konfiguraci tímto způsobem: +Zbytek je stejný jako v našem skriptu. Případně si můžete nechat do konstruktoru předat rovnou objekt `Cache` a nadefinovat ho v konfiguraci: ```neon services: - - ClassTwo( Nette\Caching\Cache(namespace: 'my-namespace') ) + - ArticleFacade( Nette\Caching\Cache(namespace: 'articles') ) ``` +.[note] +Cache šablon Latte a DI kontejneru je samostatná a toto úložiště nepoužívá. Během vývoje ji [není potřeba vypínat |nette:troubleshooting#Jak vypnout cache během vývoje]. -Journal -======= - -Nette si tagy a priority ukládá do tzv. journalu. Standardně se k tomu používá SQLite a soubor `journal.s3db` a **vyžadují se PHP rozšíření `pdo` a `pdo_sqlite`.** - -Změnit journal můžete v konfiguraci: - -```neon -services: - cache.journal: MyJournal -``` - - -Služby DI -========= - -Tyto služby se přidávají do DI kontejneru: - -| Název | Typ | Popis -|---------------------------------------------------------- -| `cache.journal` | [api:Nette\Caching\Storages\Journal] | journal -| `cache.storage` | [api:Nette\Caching\Storage] | úložiště - - -Vypnutí cache -============= - -Jednou z možností, jak vypnout cache v aplikaci, je nastavit jako úložiště [#DevNullStorage]: - -```neon -services: - cache.storage: Nette\Caching\Storages\DevNullStorage -``` - -Toto nastavení nemá vliv na kešování šablon v Latte nebo DI kontejneru, protože tyto knihovny nevyužívají služeb nette/caching a spravují si cache samostatně. Jejich cache ostatně [není potřeba |nette:troubleshooting#Jak vypnout cache během vývoje] ve vývojářském režimu vypínat. +Co dál +====== -Pokud aktualizujete balíček na novější verzi, podívejte se na stránku [upgrade|upgrading]. +- [Expirace a invalidace |expiration] - všechny způsoby, jak cache říct, kdy data vyexpirují, a mazání podle tagů, priority a jmenného prostoru +- [Úložiště |storages] - výběr a nastavení úložiště, PSR-16, vlastní úložiště +- [Upgrade |upgrading] - co se změnilo v jednotlivých verzích {{maintitle: Cache v PHP s Nette: úložiště, expirace a invalidace}} {{description: Zrychlete aplikaci tím, že náročně získaná data uložíte pro příští použití. Cache z Nette v PHP i Latte, změna úložiště a správná invalidace.}} diff --git a/caching/cs/@left-menu.texy b/caching/cs/@left-menu.texy index d24d2ac574..a9d7c652aa 100644 --- a/caching/cs/@left-menu.texy +++ b/caching/cs/@left-menu.texy @@ -1,6 +1,8 @@ Nette Caching ************* - [Úvod |@home] +- [Expirace a invalidace |expiration] +- [Úložiště |storages] - [Upgrade |upgrading] diff --git a/caching/cs/expiration.texy b/caching/cs/expiration.texy new file mode 100644 index 0000000000..3d19a30675 --- /dev/null +++ b/caching/cs/expiration.texy @@ -0,0 +1,241 @@ +Expirace a invalidace +********************* + +
+ +Cache je užitečná jen tak dlouho, dokud nevrací zastaralá data. Tato stránka ukazuje všechny způsoby, jak Nette Caching říct, kdy položka přestává platit: + +- po uplynutí doby, nebo když ji delší dobu nikdo nečetl +- když se změní soubor, PHP konstanta nebo jiná položka v cache +- když to řekne vaše vlastní funkce +- nebo hned, když ji smažete podle tagu, priority či jmenného prostoru + +
+ +Ukázky navazují na blog z [úvodu |@home]: `$cache` je cache ve jmenném prostoru `articles`, `$id` je ID článku a `renderArticle()` zastupuje náročnou práci, kdy se článek načte a převede do HTML. + + +Nastavení závislostí +==================== + +Kdy položka vyexpiruje, popisují **závislosti**, tedy pole s klíči `Cache::*`. Nejpohodlnější je nechat je vyplnit generátor. Stačí deklarovat jeho parametr jako referenci, `&$dependencies`, a `load()` mu předá prázdné pole: + +```php +use Nette\Caching\Cache; + +$html = $cache->load("article/$id", function (&$dependencies) use ($id) { + $dependencies[Cache::Expire] = '1 hour'; + return renderArticle($id); +}); +``` + +Výhoda je, že se generátor může rozhodnout podle toho, co spočítal. Rozepsaný článek může třeba vyexpirovat dřív než publikovaný. + +Když závislosti znáte předem, můžete je místo toho předat jako třetí argument metodě `load()`, případně metodě `save()`, která hodnotu uloží rovnou, bez generátoru: + +```php +$html = $cache->load("article/$id", fn() => renderArticle($id), [Cache::Expire => '1 hour']); + +$cache->save("article/$id", $html, [Cache::Expire => '1 hour', Cache::Tags => ["article/$id"]]); +``` + +Dávejte přednost `load()` s generátorem před `save()`. Když o chybějící položku požádá víc požadavků najednou, `FileStorage` spustí generátor jen u jednoho z nich; se `save()` by hodnotu počítaly všechny. + +Před verzí 3.1.3 se konstanty psaly velkými písmeny, třeba `Cache::EXPIRE` místo `Cache::Expire`. Počítejte s tím, že se pole nekontroluje: klíč s překlepem, třeba `'expir'`, se potichu ignoruje. + + +Expirace podle času +=================== + +Klíč `Cache::Expire` určuje, kdy položka vyexpiruje. Přijímá relativní čas jako řetězec, počet sekund, UNIX timestamp nebo objekt `DateTimeInterface`: + +```php +$dependencies[Cache::Expire] = '20 minutes'; +$dependencies[Cache::Expire] = 3600; // jedna hodina +$dependencies[Cache::Expire] = new DateTimeImmutable('tomorrow'); +``` + +U **klouzavé expirace** každé čtení posune expiraci dál. Článek, který návštěvníci pořád čtou, pak zůstává v cache, zatímco ten, který 20 minut nikdo neotevře, z ní vypadne: + +```php +$dependencies[Cache::Expire] = '20 minutes'; +$dependencies[Cache::Sliding] = true; +``` + +Počítejte s tím, že každé čtení pak položku v úložišti zároveň aktualizuje, což přidává režii. + + +Když se změní soubor +==================== + +Data spočítaná ze souboru by měla vyexpirovat, když se soubor změní. Dejme tomu, že blog čte seznam kategorií ze souboru `categories.neon`. Seznam v cache na tom souboru tedy závisí: + +```php +$categories = $cache->load('categories', function (&$dependencies) { + $dependencies[Cache::Files] = __DIR__ . '/categories.neon'; + return loadCategories(); // přečte a zpracuje categories.neon +}); +``` + +Jakmile `categories.neon` upravíte, cache si toho při dalším čtení všimne a zavolá generátor znovu. Používejte absolutní cesty. Položka může záviset i na více souborech: `$dependencies[Cache::Files] = [$file1, $file2]`. + + +Když se změní konstanta +======================= + +Podobně může položka vyexpirovat, když se změní hodnota PHP konstanty. Hodí se to třeba pro číslo verze, které nastavujete při nasazení, aby každá nová verze začínala s čerstvou cache: + +```php +$dependencies[Cache::Constants] = 'APP_VERSION'; +``` + + +Když se změní jiná položka +========================== + +Položka může záviset na jiných položkách v cache. Dejme tomu, že článek a jeho komentáře cachujete zvlášť, pod klíči `article/$id` a `comments/$id`, a cachujete i celou stránku z nich složenou. Stránka musí vyexpirovat, kdykoliv vyexpiruje některá z jejích částí: + +```php +$page = $cache->load("page/$id", function (&$dependencies) use ($id) { + $dependencies[Cache::Items] = ["article/$id", "comments/$id"]; + return renderPage($id); // poskládá článek a jeho komentáře +}); +``` + +Když se komentáře znovu uloží nebo smažou, vyexpiruje i stránka. + + +Vlastní podmínka +================ + +Když nic z uvedeného nesedí, napište si vlastní funkci. Volá se při každém čtení s argumenty, které jste uložili, a když vrátí `false`, položka vyexpiruje. Dejme tomu, že vyrenderované HTML nesmí přežít upgrade PHP: + +```php +function checkPhpVersion(int $version): bool +{ + return $version === PHP_VERSION_ID; +} + +$dependencies[Cache::Callbacks] = [['checkPhpVersion', PHP_VERSION_ID]]; +``` + +Každá položka je pole: funkce, případně statická metoda zapsaná jako `[ClassName::class, 'method']`, a za ní její argumenty. Funkce se volá při každém čtení, takže by měla být rychlá. + + +Kombinace podmínek +================== + +Všechny tyto podmínky lze kombinovat. Položka vyexpiruje, jakmile přestane platit alespoň jedna z nich: + +```php +$dependencies[Cache::Expire] = '1 day'; +$dependencies[Cache::Files] = __DIR__ . '/categories.neon'; +$dependencies[Cache::Constants] = 'APP_VERSION'; +``` + + +Tagy +==== + +Čekat na expiraci je kompromis. Lepší je položku smazat přesně ve chvíli, kdy se změní data, ze kterých vznikla. To umožňují **tagy**. Jsou to libovolné řetězce, které položce přiřadíte: + +```php +$html = $cache->load("article/$id", function (&$dependencies) use ($id) { + $dependencies[Cache::Tags] = ["article/$id", "comments/$id"]; + return renderArticle($id); +}); +``` + +V administraci pak hned po uložení upraveného článku do databáze smažete všechno, co nese jeho tag: + +```php +$cache->clean([Cache::Tags => ["article/$id"]]); +``` + +Totéž platí pro přidání komentáře, tentokrát s tagem `comments/$id`. Všimněte si, že kód, který položky maže, nemusí znát jejich klíče, ani kolik jich je. Článek může v cache ležet jako celá stránka, jako náhled na úvodní stránce i v RSS kanálu; jedno volání je odstraní všechny. + +Tagy fungují napříč jmennými prostory: `clean([Cache::Tags => [...]])` smaže odpovídající položky ve všech jmenných prostorech úložiště, nejen v prostoru `$cache`. + +.[note] +`FileStorage` a `MemcachedStorage` potřebují pro tagy [journal |storages#Journal], `SQLiteStorage` si je drží samo a `MemoryStorage` je ignoruje. + + +Priorita +======== + +Každé položce můžete dát prioritu, tedy číslo, které říká, jak je důležitá. Když cache příliš naroste, můžete pak smazat nejdřív ty méně důležité. Dejme tomu, že náhledy starých článků mají menší cenu než úvodní stránka: + +```php +$dependencies[Cache::Priority] = 10; +``` + +Takto smažete všechny položky s prioritou 50 nebo menší: + +```php +$cache->clean([Cache::Priority => 50]); +``` + +Položky bez priority se tímto způsobem nikdy nesmažou. + +.[note] +`FileStorage` a `MemcachedStorage` potřebují pro priority [journal |storages#Journal]; `SQLiteStorage` a `MemoryStorage` je ignorují. + + +Mazání položek +============== + +Metoda `clean()` maže položky podle podmínek, které předáte jako pole s klíči `Cache::*`: + +| Klíč | Smaže +|---------------------- +| `Cache::Tags => [...]` | položky s kterýmkoliv z tagů +| `Cache::Priority => 50` | položky s prioritou 50 nebo menší +| `Cache::Namespaces => [...]` | všechny položky v uvedených jmenných prostorech; podporuje jen `FileStorage` +| `Cache::All => true` | vše v úložišti, včetně všech jmenných prostorů + +Podmínky lze kombinovat a smaže se položka, která splňuje kteroukoliv z nich: + +```php +$cache->clean([Cache::Tags => ["article/$id"], Cache::Priority => 50]); +``` + +Podívejme se blíž na `Cache::All`. Smaže celé úložiště včetně položek všech jmenných prostorů, i když ho zavoláte na cache se jmenným prostorem. Pokud chcete smazat jen jeden jmenný prostor, použijte `Cache::Namespaces`; prostory, které z něj vznikly pomocí `derive()`, zůstanou. + +Pole se nekontroluje, takže klíč s překlepem se potichu ignoruje a nic se nesmaže. + +Odstranit položky, které už vyexpirovaly, je věc úložiště: zavolejte `$storage->clean([])`. `FileStorage` a `SQLiteStorage` to ostatně čas od času dělají samy, viz [Úložiště |storages]. + +Jednu položku smažete pomocí `$cache->remove("article/$id")`. + + +Co které úložiště umí +===================== + +Ne každé úložiště umí každý druh závislosti a většina z nich to, co neumí, potichu ignoruje. `SQLiteStorage` třeba ignoruje priority a závislosti na souborech, takže položka podle nich prostě nevyexpiruje, a `MemoryStorage` ignoruje všechny závislosti. Než se na nějakou závislost spolehnete, podívejte se do tabulky na stránce [Úložiště |storages#Výběr úložiště]. + + +Hromadné čtení a zápis +====================== + +Úvodní stránka blogu ukazuje náhledy deseti článků. Číst je z cache jeden po druhém znamená desetkrát se obrátit na úložiště. Metoda `bulkLoad()` je přečte všechny najednou: předáte jí pole `$ids` s jejich ID jako klíči a vrátí pole hodnot indexované těmito klíči: + +```php +$previews = $cache->bulkLoad($ids, function ($id, &$dependencies) { + $dependencies[Cache::Tags] = ["article/$id"]; + return renderPreview($id); // vyrenderuje krátký náhled článku +}); +``` + +Generátor se zavolá jen pro náhledy, které chybí, a dostane klíč a za ním závislosti. Bez generátoru vrátí `bulkLoad($ids)` pro chybějící položky `null`. + +Metoda `bulkSave()` uloží několik položek najednou, všechny se stejnými závislostmi: .{data-version:3.3.0} + +```php +$cache->bulkSave([ + "preview/$id1" => $preview1, + "preview/$id2" => $preview2, +], [Cache::Expire => '1 hour']); +``` + +{{maintitle: Nette Caching: expirace, tagy a invalidace cache}} +{{description: Zajistěte, aby cache nikdy nevracela zastaralá data. Expirace podle času, změny souboru či konstanty a mazání podle tagů, priority a jmenného prostoru.}} diff --git a/caching/cs/storages.texy b/caching/cs/storages.texy new file mode 100644 index 0000000000..f686b32921 --- /dev/null +++ b/caching/cs/storages.texy @@ -0,0 +1,190 @@ +Úložiště +******** + +
+ +Úložiště určuje, kde data z cache fyzicky leží: v souborech na disku, na serveru Memcached nebo v databázi SQLite. Vyměnit ho můžete, aniž byste sáhli na kód, který cache používá. Tato stránka vám pomůže: + +- vybrat správné úložiště a zjistit, co které umí +- nastavit ho v aplikaci Nette, případně cache vypnout +- použít úložiště z Nette jako PSR-16 cache +- napsat si vlastní úložiště + +
+ + +Výběr úložiště +============== + +Pokud si nejste jistí, nechte výchozí `FileStorage`. Stačí mu adresář, je bezpečné, i když najednou čte a zapisuje mnoho požadavků, a podporuje všechny druhy závislostí. + +Když aplikace běží na více serverech, `FileStorage` dá každému z nich vlastní cache. `MemcachedStorage` ukládá data na server, který sdílejí všechny, jenže tagy a priority si drží v [journalu |#journal], což je soubor na každém serveru zvlášť, takže mazání podle tagu na jednom serveru se k ostatním nedostane. + +Úložiště se liší tím, které [závislosti |expiration] umí respektovat: + +|------------------------------------------------------------------------------------------------- +| Úložiště | Tagy, priority | Soubory, konstanty, callbacky | Jiné položky | Klouzavá expirace | Mazání jmenných prostorů | Ochrana proti stampede +|------------------------------------------------------------------------------------------------- +| [#FileStorage] | s [journalem |#journal] | ano | ano | ano | ano | ano +| [#MemcachedStorage] | s [journalem |#journal] | ano | ne | ano | ignoruje | ne +| [#SQLiteStorage] | jen tagy | ignoruje | ignoruje | ano | ignoruje | ne +| [#MemoryStorage] | ignoruje | ignoruje | ignoruje | ignoruje | ignoruje | ne +| [#DevNullStorage] | nic neukládá | | | | | + +Kde tabulka uvádí ignoruje, úložiště závislost potichu zahodí, takže položka podle ní prostě nevyexpiruje. `MemoryStorage` ignoruje dokonce i expiraci. Jen `MemcachedStorage` vyhodí `Nette\NotSupportedException`, a to pro závislost na jiných položkách. + +Ochrana proti stampede znamená, že když o chybějící položku požádá najednou mnoho požadavků, generátor z `load()` spustí jen první z nich a ostatní počkají na jeho výsledek. Bez ní hodnotu počítají všechny zároveň. + + +Konfigurace +=========== + +V aplikaci postavené na Nette poskytuje DI kontejner `FileStorage`, které ukládá data do podadresáře `cache` v adresáři pro [dočasné soubory |application:bootstrapping#Dočasné soubory], a k němu i journal. Dostanete ho pomocí [dependency injection |dependency-injection:passing-dependencies], když si řeknete o typ `Nette\Caching\Storage`. + +Pokud chcete jiné úložiště, nahraďte v konfiguraci službu `cache.storage`: + +```neon +services: + cache.storage: Nette\Caching\Storages\MemcachedStorage('10.0.0.5') +``` + +Kontejner obsahuje tyto dvě služby: + +| Název | Typ | Popis +|---------------------------------------------------------- +| `cache.storage` | [api:Nette\Caching\Storage] | úložiště +| `cache.journal` | [api:Nette\Caching\Storages\Journal] | [journal |#journal] pro tagy a priority + + +Vypnutí cache +------------- + +Pokud chcete cache vypnout, třeba v testech, použijte [#DevNullStorage], které nic neukládá: + +```neon +services: + cache.storage: Nette\Caching\Storages\DevNullStorage +``` + +Na cache šablon Latte a DI kontejneru to nemá vliv, ty jsou samostatné a toto úložiště nepoužívají. Během vývoje je ostatně [není potřeba vypínat |nette:troubleshooting#Jak vypnout cache během vývoje]. + + +FileStorage +=========== + +`Nette\Caching\Storages\FileStorage` zapisuje každou položku do souboru v zadaném adresáři, který musí existovat. Tagy a priority potřebují [journal |#journal]: + +```php +$journal = new Nette\Caching\Storages\SQLiteJournal('/path/to/temp/journal.s3db'); +$storage = new Nette\Caching\Storages\FileStorage('/path/to/temp', $journal); +``` + +Všechny operace jsou atomické. Nikdy nepřečtete soubor, který jiný požadavek ještě nedopsal, a nikdo vám ho nemůže smazat pod rukama, zatímco ho čtete. Úložiště je proto bezpečné i pod velkou zátěží. + +Navíc chrání před [cache stampede |https://en.wikipedia.org/wiki/Cache_stampede]. Když o chybějící položku požádá najednou mnoho požadavků, třeba hned po nasazení, první z nich soubor zamkne a spustí generátor. Ostatní počkají na zámek a pak přečtou čerstvou hodnotu, místo aby ji počítaly znovu. + +Vyexpirované soubory čas od času smaže konstruktor. Pokud je chcete smazat v okamžiku, který si zvolíte sami, zavolejte `$storage->clean([])`. + + +MemcachedStorage +================ + +`Nette\Caching\Storages\MemcachedStorage` ukládá data na server [Memcached |https://memcached.org]. Konstruktor přijímá adresu serveru a port, výchozí je 11211. Tagy a priority potřebují [journal |#journal]. + +.[caution] +Vyžaduje PHP rozšíření `memcached`. + +```neon +services: + cache.storage: Nette\Caching\Storages\MemcachedStorage('10.0.0.5') +``` + +Memcached neumí vypsat své klíče, takže úložiště mazání podle jmenných prostorů ignoruje. Pro závislost na jiných položkách vyhodí výjimku. Smazání celé cache vyprázdní celý server Memcached včetně dat jiných aplikací. + + +SQLiteStorage +============= + +`Nette\Caching\Storages\SQLiteStorage` drží celou cache v jediném souboru databáze SQLite. Tagy si ukládá do vlastní tabulky, takže nepotřebuje journal. + +.[caution] +Vyžaduje PHP rozšíření `pdo` a `pdo_sqlite`. + +```neon +services: + cache.storage: Nette\Caching\Storages\SQLiteStorage('%tempDir%/cache.db') +``` + +Úložiště podporuje expiraci, klouzavou expiraci a tagy. Priority, závislosti na souborech, konstantách, callbackech a jiných položkách i mazání podle jmenných prostorů potichu ignoruje. + + +MemoryStorage +============= + +`Nette\Caching\Storages\MemoryStorage` drží data v PHP poli, takže se s koncem požadavku ztratí. Hodí se pro testy a pro cachování v rámci jednoho požadavku. + +Ignoruje všechny závislosti včetně expirace a z podmínek metody `clean()` respektuje jen `Cache::All`. Myslete na to, když jím v testech nahrazujete skutečné úložiště: položka, která by tam vyexpirovala, tady zůstane. + + +DevNullStorage +============== + +`Nette\Caching\Storages\DevNullStorage` nic neukládá, takže každé `load()` zavolá generátor. Použijte ho pro [vypnutí cache |#Vypnutí cache]. + + +Journal +======= + +`FileStorage` a `MemcachedStorage` neumí své položky vyhledávat podle tagu nebo priority, proto si vedou samostatný index, tzv. journal. Vestavěný `Nette\Caching\Storages\SQLiteJournal` ho ukládá do databáze SQLite: + +```php +$journal = new Nette\Caching\Storages\SQLiteJournal('/path/to/temp/journal.s3db'); +``` + +.[caution] +Vyžaduje PHP rozšíření `pdo` a `pdo_sqlite`. + +V aplikaci postavené na Nette se journal vytvoří za vás jako služba `cache.journal` v souboru `journal.s3db` a úložišti se předá automaticky. Nahradit ho může vaše vlastní implementace rozhraní `Nette\Caching\Storages\Journal`: + +```neon +services: + cache.journal: MyJournal +``` + +Bez journalu tato úložiště fungují také, jen uložení položky s tagy nebo prioritou vyhodí výjimku. + + +Úložiště jako PSR-16 cache .{data-version:3.3.1} +================================================ + +Některé knihovny očekávají [PSR-16 |https://www.php-fig.org/psr/psr-16/] cache. Adaptér `Nette\Bridges\Psr\PsrCacheAdapter` jim ji poskytne nad libovolným úložištěm z Nette: + +```php +$psrCache = new Nette\Bridges\Psr\PsrCacheAdapter($storage); + +$psrCache->set('key', 'value', 3600); // uloží hodnotu na 1 hodinu +$value = $psrCache->get('key', 'default'); +``` + +Adaptér podporuje všechny metody PSR-16 včetně `getMultiple()`, `setMultiple()` a `deleteMultiple()`. + + +Vlastní úložiště +================ + +Úložiště je třída, která implementuje rozhraní `Nette\Caching\Storage` (před verzí 3.1 se jmenovalo `Nette\Caching\IStorage`) s pěti metodami: + +- `read(string $key)` vrátí uloženou hodnotu, nebo `null`, když položka neexistuje nebo vyexpirovala +- `lock(string $key): void` zamkne položku, než `Cache` spustí generátor; zámek uvolní `write()` nebo `remove()` a úložiště, které před cache stampede nechrání, nechá metodu prázdnou +- `write(string $key, mixed $data, array $dependencies): void` hodnotu uloží +- `remove(string $key): void` položku smaže +- `clean(array $conditions): void` smaže položky podle podmínek metody [clean() |expiration#Mazání položek]; prázdné pole znamená odstranit vyexpirované položky + +Závislosti přicházejí jako pole s klíči `Cache::*`, které už `Cache` zjednodušila: expirace je počet sekund od teď, ze souborů a konstant se staly callbacky a jiné položky jsou dané svými klíči v úložišti. Při čtení položky ověřte její callbacky pomocí `Nette\Caching\Cache::checkCallbacks()`. Pro závislost nebo podmínku, kterou vaše úložiště neumí, vyhoďte `Nette\NotSupportedException`. + +Další schopnosti přidávají volitelná rozhraní. `Nette\Caching\BulkReader` a od verze 3.3 i `Nette\Caching\BulkWriter` umožní úložišti číst a zapisovat více položek najednou. + +Krátkým úplným příkladem je zdrojový kód [SQLiteStorage |https://github.com/nette/caching/blob/v3.4/src/Caching/Storages/SQLiteStorage.php]. + +{{maintitle: Úložiště Nette Caching: soubory, Memcached, SQLite}} +{{description: Vyberte, kam cache z Nette ukládá data: soubory, Memcached nebo SQLite. Porovnejte, co které úložiště umí, a nastavte ho ve své aplikaci.}} diff --git a/caching/en/@home.texy b/caching/en/@home.texy index 2f6793b527..624a481ff2 100644 --- a/caching/en/@home.texy +++ b/caching/en/@home.texy @@ -3,16 +3,17 @@ Nette Caching
-A cache speeds up your application by storing data that was once computationally expensive to retrieve, allowing for faster access in the future. We will cover: +Does your application compute the same thing over and over, such as turning an article into HTML, running a slow database query or calling a remote API? Nette Caching remembers the result and hands it back next time in a fraction of the time: -- how to use the cache -- how to change the storage backend -- how to correctly invalidate the cache +- One method reads the value from the cache, or computes and stores it when it is missing +- Data expires after a while, or when a file, another item or your own condition changes +- Tags delete exactly the items related to the article you just edited +- A crowd of requests for a missing item does not overload the server +- Stores data in files, Memcached or SQLite +- Caches parts of Latte templates
-Using the cache in Nette is very straightforward, yet it covers sophisticated caching needs. It's designed for performance and 100% durability. It includes adapters for the most common storage backends. It supports tag-based invalidation, time expiration, protection against cache stampede, and more. - Installation ============ @@ -24,318 +25,165 @@ composer require nette/caching ``` -Basic Usage -=========== - -The core element for working with the cache is the [api:Nette\Caching\Cache] object. We create an instance of it, passing a storage backend object to the constructor. This storage object represents the physical location where data will be stored (database, Memcached, files on disk, etc.). You typically obtain the storage object via [dependency injection |dependency-injection:passing-dependencies] by requesting the type `Nette\Caching\Storage`. You'll learn the essentials in the [Storages section |#Storages]. +Your First Cache +================ -.[warning] -In version 3.0, the interface still had the `I` prefix, so the name was `Nette\Caching\IStorage`. Furthermore, constants of the `Cache` class were written in uppercase, e.g., `Cache::EXPIRE` instead of `Cache::Expire`. +The easiest way to show it is with an example. Let's say you run a blog. Every time someone opens an article, your code loads it from the database and turns its text into HTML. That takes a while, and the result is the same for every visitor until you edit the article. A perfect candidate for the cache. -For the following examples, assume we have an alias `Cache` and a storage instance in the `$storage` variable. +We'll write it as a short script. First, we create two objects: ```php use Nette\Caching\Cache; +use Nette\Caching\Storages\FileStorage; -$storage = /* ... */; // instance of Nette\Caching\Storage -``` - -The cache is essentially a *key-value store*, meaning we read and write data using keys, similar to associative arrays. Applications consist of multiple independent parts. If all parts used a single storage (imagine a single directory on disk), key collisions would eventually occur. The Nette Framework addresses this by partitioning the storage space into namespaces (conceptually like subdirectories). Each part of the application then works within its own namespace using a unique name, preventing any collisions. +require __DIR__ . '/vendor/autoload.php'; -Specify the namespace name as the second argument to the `Cache` class constructor: - -```php -$cache = new Cache($storage, 'Full Html Pages'); +$storage = new FileStorage(__DIR__ . '/temp'); +$cache = new Cache($storage, 'articles'); ``` -If needed, you can derive a new cache scoped to a sub-namespace from an existing instance using the `derive()` method: - -```php -$subCache = $cache->derive('Images'); -``` +The **storage** decides where the data physically lives. `FileStorage` keeps it in files in the `temp` directory, which must exist. The **cache** is the object you will work with. Its second argument, `'articles'`, is a namespace: it keeps the articles apart from whatever else the application caches, so two parts of the program can use the same key without clashing. -Now, we can use the `$cache` object to read from and write to the cache. The `load()` method serves both purposes. The first argument is the key, and the second is a PHP callback that gets invoked if the key is not found in the cache. The callback generates the value, returns it, and the `load()` method caches it: +Now the important part. The cache works like an associative array: you read and write values under keys. The method `load()` does both at once: ```php -$value = $cache->load($key, function () use ($key) { - $computedValue = /* ... */; // expensive computation - return $computedValue; +$html = $cache->load("article/$id", function () use ($id) { + return renderArticle($id); // loads the article from the database and turns it into HTML }); ``` -If the second parameter is omitted (`$value = $cache->load($key)`), `load()` returns `null` if the item is not found in the cache. +Here `$id` is the ID of the article being displayed. The first argument of `load()` is the key, the second is a function called the **generator**. When the key is not in the cache yet, `load()` calls the generator, stores what it returns and returns it to you. Next time, it finds the value in the cache and returns it right away, without calling the generator at all. -.[tip] -It's great that any serializable structures can be cached, not just strings. The same applies to keys. - -To delete an item from the cache, use the `remove()` method: - -```php -$cache->remove($key); -``` - -You can also save an item to the cache using the `$cache->save($key, $data, ?array $dependencies = null)` method. However, the `load()` approach shown above is generally preferred. - - -Memoization -=========== +Notice that you never check whether the value is already cached. You only say how to compute it. -Memoization involves caching the result of a function or method call, so the next time it's called with the same arguments, the cached result is returned instead of recalculating it. +And what if a hundred visitors open the same article at the moment it is not cached yet, for example right after a deployment? Without protection, all hundred requests would render it at once and could overload the server. This is called a [cache stampede |https://en.wikipedia.org/wiki/Cache_stampede]. `FileStorage` prevents it: only the first request runs the generator, the others wait for its result. -Methods and functions can be called in a memoized way using `call(callable $callback, ...$args)`: - -```php -$result = $cache->call('gethostbyaddr', $ip); -``` - -The `gethostbyaddr()` function is thus called only once for each unique `$ip` argument. Subsequent calls with the same `$ip` will return the cached value. +.[tip] +You can cache any value PHP can serialize, not just strings: arrays, objects, numbers. The same goes for keys. -It's also possible to create a memoized wrapper around a method or function, which can then be called later: +To read a value without generating it, call `load()` with the key only; it returns `null` when the item is not in the cache. The method `remove()` deletes an item: ```php -function factorial($num) -{ - return /* ... */; -} - -$memoizedFactorial = $cache->wrap('factorial'); - -$result = $memoizedFactorial(5); // calculates it the first time -$result = $memoizedFactorial(5); // returns from cache the second time +$cache->remove("article/$id"); ``` -Expiration & Invalidation -========================= - -When using caching, it's necessary to address the issue of when previously stored data becomes invalid. Nette Framework provides mechanisms to limit data validity or delete it explicitly (referred to as "invalidation" in the framework's terminology). +How Long Is the Data Valid? +=========================== -Data validity is set at the time of saving, typically using the third parameter of the `save()` method, e.g.: +Our cached article now never changes. But what if you fix a typo in it? Visitors would keep seeing the old version. You need to tell the cache when an item stops being valid. The simplest way is a time limit: ```php -$cache->save($key, $value, [ - $cache::Expire => '20 minutes', -]); -``` - -Alternatively, it can be set using the `$dependencies` parameter passed by reference to the callback in the `load()` method, e.g.: - -```php -$value = $cache->load($key, function (&$dependencies) { - $dependencies[Cache::Expire] = '20 minutes'; - return /* ... */; +$html = $cache->load("article/$id", function (&$dependencies) use ($id) { + $dependencies[Cache::Expire] = '1 hour'; + return renderArticle($id); }); ``` -Or by using the 3rd parameter of the `load()` method itself, e.g.: - -```php -$value = $cache->load($key, function () { - return /* ... */; -}, [Cache::Expire => '20 minutes']); -``` +The generator now takes the parameter `$dependencies` by reference. It is an array into which the generator writes when the item expires. It is called dependencies because the validity of the item depends on them. Here it is one hour. -In the following examples, we'll assume the second variant, utilizing the `$dependencies` variable within the callback. +Time is just one option. An item can also expire when a file changes, when another item in the cache changes, or when your own condition says so. All of that is described on the page [Expiration and Invalidation |expiration]. -Expiration ----------- +Deleting Exactly What Changed +============================= -The simplest form of expiration is a time limit. This caches data with a validity of 20 minutes: +A time limit is a compromise: set it short, and the cache helps little; set it long, and visitors see stale data. It is better to delete the article from the cache exactly when you edit it. That is what **tags** are for. You attach them to an item as arbitrary strings: ```php -// accepts number of seconds or a UNIX timestamp as well -$dependencies[Cache::Expire] = '20 minutes'; -``` - -If you want the validity period to extend with each read (sliding expiration), you can achieve this as follows, but be aware that this increases cache overhead: - -```php -$dependencies[Cache::Sliding] = true; -``` - -A useful option is to have data expire when a specific file or one of several files is modified. This is useful, for example, when caching data derived from processing these files. Use absolute paths. - -```php -$dependencies[Cache::Files] = '/path/to/data.yaml'; -// or -$dependencies[Cache::Files] = ['/path/to/data1.yaml', '/path/to/data2.yaml']; -``` - -We can make a cache item expire when another specific item (or one of several others) expires. This is useful when caching, for instance, an entire HTML page and its fragments under different keys. When a fragment changes, the entire page should be invalidated. If the fragments are stored under keys like `frag1` and `frag2`, use: - -```php -$dependencies[Cache::Items] = ['frag1', 'frag2']; -``` - -Expiration can also be controlled using custom functions or static methods. These are called upon each read to determine if the item is still valid. For example, we can make an item expire whenever the PHP version changes. Create a function that compares the current version with a parameter, and when saving, add an array in the format `[function name, ...arguments]` to the dependencies: - -```php -function checkPhpVersion($ver): bool -{ - return $ver === PHP_VERSION_ID; -} - -$dependencies[Cache::Callbacks] = [ - ['checkPhpVersion', PHP_VERSION_ID] // expire when checkPhpVersion(...) === false -]; +$html = $cache->load("article/$id", function (&$dependencies) use ($id) { + $dependencies[Cache::Tags] = ["article/$id", "comments/$id"]; + return renderArticle($id); +}); ``` -Naturally, all these criteria can be combined. The cache item expires if at least one criterion is no longer met. +The page shows the article together with its comments, so we gave it two tags. Then, in the administration, right after you save the edited article to the database, you delete everything tagged with it: ```php -$dependencies[Cache::Expire] = '20 minutes'; -$dependencies[Cache::Files] = '/path/to/data.yaml'; +$cache->clean([Cache::Tags => ["article/$id"]]); ``` +And the same when someone adds a comment, this time with the tag `comments/$id`. From now on, the cached page disappears exactly when its article or its comments change, and the next visitor gets a freshly rendered one. -Invalidation Using Tags ------------------------ - -Tags provide a very useful invalidation mechanism. We can assign a list of tags (arbitrary strings) to each item stored in the cache. For example, suppose we have an HTML page displaying an article and its comments, which we want to cache. When saving, we specify the relevant tags: - -```php -$dependencies[Cache::Tags] = ["article/$articleId", "comments/$articleId"]; -``` - -Now, let's move to the administration section. Here, we have a form for editing articles. Along with saving the article to the database, we call the `clean()` method to delete cached items based on their tag: +`FileStorage` remembers which item carries which tag in a so-called journal, a small SQLite database. In a Nette application it is set up for you; in our script, we create it and pass it to the storage: ```php -$cache->clean([ - $cache::Tags => ["article/$articleId"], -]); -``` +use Nette\Caching\Storages\SQLiteJournal; -Similarly, when adding a new comment (or editing one), we must remember to invalidate the corresponding tag: - -```php -$cache->clean([ - $cache::Tags => ["comments/$articleId"], -]); +$journal = new SQLiteJournal(__DIR__ . '/temp/journal.s3db'); +$storage = new FileStorage(__DIR__ . '/temp', $journal); ``` -What have we achieved? Our HTML cache will now be invalidated (deleted) whenever the associated article or its comments change. When editing the article with ID = 10, the tag `article/10` is invalidated, and the cached HTML page carrying this tag is deleted. The same occurs when a new comment is added under the respective article. +Besides tags, you can delete items by priority or a whole namespace at once. See [Expiration and Invalidation |expiration#Deleting Items]. -.[note] -Tags require a [#Journal]. - - -Invalidation by Priority ------------------------- -We can assign priorities to individual cache items. This allows for controlled deletion, for example, when the cache exceeds a certain size limit: - -```php -$dependencies[Cache::Priority] = 50; -``` +Namespaces +========== -To delete all items with a priority equal to or less than 100: +We already met the namespace `'articles'` in the constructor of the cache. Each part of the application should have its own, so their keys never collide. The comments could use their own cache, for example: ```php -$cache->clean([ - $cache::Priority => 100, -]); +$commentCache = new Cache($storage, 'comments'); ``` -.[note] -Priorities require a so-called [#Journal]. - - -Clear Cache ------------ - -The `Cache::All` parameter clears everything: +The method `derive()` creates a cache in a nested namespace: `$cache->derive('previews')` gives the namespace `previews` inside `articles`. And when you want to throw away everything in a namespace, call: ```php -$cache->clean([ - $cache::All => true, -]); +$cache->clean([Cache::Namespaces => ['articles']]); ``` +Other namespaces, the nested ones included, stay untouched. Cleaning by namespace works with `FileStorage`; other storages ignore it. Be careful with `Cache::All`, which deletes the entire storage, all namespaces included. -Bulk Reading -============ - -For bulk reading from and writing to the cache, use the `bulkLoad()` method. Pass it an array of keys, and it returns an array of corresponding values: - -```php -$values = $cache->bulkLoad($keys); -``` -The `bulkLoad()` method works similarly to `load()`, also accepting a second callback parameter. This callback receives the key of the item being generated: - -```php -$values = $cache->bulkLoad($keys, function ($key, &$dependencies) { - $computedValue = /* ... */; // expensive computation - return $computedValue; -}); -``` +Memoization +=========== -Conversely, to write multiple items at once, use the `bulkSave()` method, which takes an array of `key => value` pairs and optional dependencies: +Sometimes you want to cache the result of a function call. In the comment moderation, for example, you show the host name of each author's IP address. Finding it out with `gethostbyaddr()` asks a DNS server and can take seconds. The method `call()` calls the function only once for each argument and then returns the result from the cache: ```php -$cache->bulkSave([ - $key1 => $value1, - $key2 => $value2, -], [Cache::Expire => '20 minutes']); +$host = $cache->call('gethostbyaddr', $ip); ``` - -Using with PSR-16 .{data-version:3.3.1} -======================================= - -To use Nette Cache with a PSR-16 interface, you can utilize the `PsrCacheAdapter`. It enables seamless integration between Nette Cache and any code or library expecting a PSR-16 compatible cache implementation. +Here `$ip` is the IP address of a comment's author. The method `wrap()` does the same, but instead of calling the function right away, it returns a new function you can call later, as many times as you like: ```php -$psrCache = new Nette\Bridges\Psr\PsrCacheAdapter($storage); -``` - -Now you can use `$psrCache` as a standard PSR-16 cache: +$getHost = $cache->wrap('gethostbyaddr'); -```php -$psrCache->set('key', 'value', 3600); // stores the value for 1 hour -$value = $psrCache->get('key', 'default'); +$host = $getHost($ip); // asks the DNS server the first time +$host = $getHost($ip); // returns the cached result the second time ``` -The adapter supports all methods defined in PSR-16, including `getMultiple()`, `setMultiple()`, and `deleteMultiple()`. - -Output Caching -============== +Caching Part of a Page +====================== -Output can be captured and cached very elegantly: +Not everything you want to cache is a return value. Sometimes it is a block of HTML that a piece of code prints. The method `capture()` catches it: ```php -if ($capture = $cache->capture($key)) { - - // echo ... printing some data - - $capture->end(); // save the output to the cache +if ($capture = $cache->capture('sidebar')) { + // echo ... prints the sidebar with the latest articles + $capture->end(); // stores the printed output in the cache } ``` -If the output is already present in the cache, the `capture()` method prints it and returns `null`, so the `if` condition block is skipped. Otherwise, it starts buffering the output and returns a `$capture` object, which you use to finally save the captured data to the cache via its `end()` method. - -.[note] -In version 3.0, this method was named `$cache->start()`. +When the output is already cached, `capture()` prints it and returns `null`, so the block inside `if` does not run at all. Otherwise it starts capturing the output and returns an object whose method `end()` stores everything printed in the meantime. You can pass it dependencies, for example `$capture->end([Cache::Tags => ['articles']])`. In version 3.0, the method `capture()` was named `start()`. Caching in Latte ================ -Caching in [Latte|latte:] templates is very simple. Just wrap the portion of the template you want to cache with the `{cache}...{/cache}` tags. The cache is automatically invalidated whenever the source template file changes (including any templates included within the cached block). The `{cache}` tags can be nested. When a nested block is invalidated (e.g., via a tag), its parent block is also invalidated. - -Within the tag, you can specify keys to which the cache entry will be bound (here, the variable `$id`), set an expiration time, and define [invalidation tags |#Invalidation Using Tags]. +In [Latte|latte:] templates, it is even easier. Wrap the part you want to cache in the tags `{cache}...{/cache}`: ```latte -{cache $id, expire: '20 minutes', tags: [tag1, tag2]} +{cache expire: '20 minutes', tags: [articles]} +

Latest Articles

... {/cache} ``` -All these parameters are optional, so you don't need to specify expiration, tags, or even keys. +The block is invalidated automatically whenever the template changes, including any templates included inside the block. Blocks can be nested; when a nested block is invalidated, its parent block is invalidated too. -The use of caching can also be made conditional using `if` - the content will only be cached if the condition is met: +All the parameters are optional. Without `expire`, the block expires after 7 days. If the content depends on a variable, list it at the start, and each value gets its own cached copy: `{cache $article->id}`. And the parameter `if` decides whether to cache at all: ```latte {cache $id, if: !$form->isSubmitted()} @@ -344,162 +192,61 @@ The use of caching can also be made conditional using `if` - the content will on ``` -Storages -======== +Where the Data Is Stored +======================== -A storage is an object representing the physical location where data is stored. We can use a database, a Memcached server, or the most readily available storage: files on disk. +So far, we have used `FileStorage`, which needs nothing but a directory. Thanks to atomic file operations, it is safe even when many requests read and write at once. But it is just one of several storages: |---------------------- -| Storage | Description +| Storage | Where the data lives |---------------------- -| [#FileStorage] | Default storage, saves cache to files on disk. -| [#MemcachedStorage] | Uses a `Memcached` server for storage. -| [#MemoryStorage] | Data is stored temporarily in memory (lost on request end). -| [#SQLiteStorage] | Data is stored in an SQLite database file. -| [#DevNullStorage] | Data isn't actually stored; useful for testing. - -You obtain the storage object via [dependency injection |dependency-injection:passing-dependencies] by requesting the type `Nette\Caching\Storage`. By default, Nette provides a `FileStorage` object that stores data in the `cache` subdirectory within the directory for [temporary files |application:bootstrapping#Temporary Files]. - -You can change the default storage in the configuration: - -```neon -services: - cache.storage: Nette\Caching\Storages\DevNullStorage -``` - - -FileStorage ------------ - -Writes cache entries to files on disk. The `Nette\Caching\Storages\FileStorage` storage is highly optimized for performance and, crucially, ensures full atomicity of operations. What does this mean? When using the cache, it cannot happen that you read a file that hasn't been completely written by another thread yet, or that someone deletes it while you are reading it. Therefore, using this cache storage is completely safe. - -This storage also includes an important built-in feature that prevents an extreme surge in CPU usage when the cache is cleared or is still "cold" (i.e., not yet created). This is known as "cache stampede":https://en.wikipedia.org/wiki/Cache_stampede prevention. It occurs when multiple concurrent requests simultaneously ask for the same cached item (e.g., the result of an expensive SQL query). If the item isn't currently cached, all these processes might start executing the same expensive operation (like the SQL query). This multiplies the server load, and it can even happen that no thread manages to respond within the time limit, the cache doesn't get created, and the application may crash. Fortunately, Nette's cache handles this: when multiple concurrent requests are made for the same item, only the first thread generates it. The other threads wait and then use the result generated by the first one. - -Example of creating a `FileStorage`: - -```php -// the storage will be the directory '/path/to/temp' on disk -$storage = new Nette\Caching\Storages\FileStorage('/path/to/temp'); -``` - - -MemcachedStorage ----------------- - -The [Memcached |https://memcached.org] server is a high-performance distributed memory object caching system. Its adapter in Nette is `Nette\Caching\Storages\MemcachedStorage`. In the configuration, specify the server's IP address and port if it differs from the standard 11211. - -.[caution] -Requires the `memcached` PHP extension. - -```neon -services: - cache.storage: Nette\Caching\Storages\MemcachedStorage('10.0.0.5') -``` - +| `FileStorage` | in files on disk; the default storage +| `MemcachedStorage` | on a Memcached server +| `SQLiteStorage` | in an SQLite database file +| `MemoryStorage` | in memory, only until the request ends +| `DevNullStorage` | nowhere; for tests and for turning the cache off -MemoryStorage -------------- +You can switch the storage without touching the code that uses the cache. Which one to choose, what each supports and how to configure it, including turning the cache off, is described on the page [Storages |storages]. -`Nette\Caching\Storages\MemoryStorage` is a storage that holds data within a PHP array. Consequently, the data is lost when the request ends. +Cache in a Nette Application +============================ -SQLiteStorage -------------- - -The SQLite database, along with the `Nette\Caching\Storages\SQLiteStorage` adapter, provides a method for caching data within a single file on disk. The configuration specifies the path to this database file. - -.[caution] -Requires the `pdo` and `pdo_sqlite` PHP extensions. - -```neon -services: - cache.storage: Nette\Caching\Storages\SQLiteStorage('%tempDir%/cache.db') -``` - - -DevNullStorage --------------- - -A special storage implementation is `Nette\Caching\Storages\DevNullStorage`, which doesn't actually store any data. It is therefore suitable for testing purposes when you want to eliminate the effects of caching. - - -Using Cache in Code -=================== - -When using caching in your code, there are two main approaches. The first is to obtain the storage object via [dependency injection |dependency-injection:passing-dependencies] and then create the `Cache` object yourself: +In a Nette application, you do not create the storage yourself. Nette provides a `FileStorage` that stores data in the `cache` subdirectory of the directory for [temporary files |application:bootstrapping#Temporary Files], together with a journal. You get it via [dependency injection |dependency-injection:passing-dependencies] by asking for the type `Nette\Caching\Storage` (before version 3.1 named `Nette\Caching\IStorage`), and create your cache in the constructor: ```php -use Nette; +use Nette\Caching\Cache; +use Nette\Caching\Storage; -class ClassOne +class ArticleFacade { - private Nette\Caching\Cache $cache; - - public function __construct(Nette\Caching\Storage $storage) - { - $this->cache = new Nette\Caching\Cache($storage, 'my-namespace'); - } -} -``` + private Cache $cache; -The second option is to request the `Cache` object directly: -```php -class ClassTwo -{ - public function __construct( - private Nette\Caching\Cache $cache, - ) { + public function __construct(Storage $storage) + { + $this->cache = new Cache($storage, 'articles'); } } ``` -The `Cache` object must then be defined in the configuration, for example like this: +The rest is the same as in our script. Alternatively, you can have the `Cache` object itself passed to the constructor and define it in the configuration: ```neon services: - - ClassTwo( Nette\Caching\Cache(namespace: 'my-namespace') ) + - ArticleFacade( Nette\Caching\Cache(namespace: 'articles') ) ``` - -Journal -======= - -Nette stores tag and priority information in a so-called journal. By default, SQLite is used for this purpose via the file `journal.s3db`, and **the `pdo` and `pdo_sqlite` PHP extensions are required.** - -You can change the journal implementation in the configuration: - -```neon -services: - cache.journal: MyJournal -``` +.[note] +The caches of Latte templates and of the DI container are separate and do not use this storage. They [do not need to be turned off |nette:troubleshooting#How to Disable Cache During Development] during development. -DI Services +What's Next =========== -These services are added to the DI container: - -| Name | Type | Description -|---------------------------------------------------------- -| `cache.journal` | [api:Nette\Caching\Storages\Journal] | The cache journal storage -| `cache.storage` | [api:Nette\Caching\Storage] | The primary cache storage - - -Turning Off Cache -================= - -One way to disable caching in your application is to set the storage backend to [#DevNullStorage]: - -```neon -services: - cache.storage: Nette\Caching\Storages\DevNullStorage -``` - -This setting does not affect the caching of Latte templates or the DI container, as these libraries do not utilize `nette/caching` services and manage their caches independently. Furthermore, their caches [do not typically need to be disabled |nette:troubleshooting#How to Disable Cache During Development] in development mode. - - -If you are upgrading to a newer version, see the [upgrading] page. +- [Expiration and Invalidation |expiration] - every way to tell the cache when data expires, deleting by tags, priority and namespace +- [Storages |storages] - choosing and configuring a storage, PSR-16, writing your own storage +- [Upgrading |upgrading] - what changed in each version {{maintitle: PHP Caching with Nette: Storages, Expiration, Invalidation}} {{description: Speed up your application by storing expensive results for later. Use the Nette cache in PHP and Latte, change storages and invalidate data correctly.}} diff --git a/caching/en/@left-menu.texy b/caching/en/@left-menu.texy index 18196494d3..aa44a28806 100644 --- a/caching/en/@left-menu.texy +++ b/caching/en/@left-menu.texy @@ -1,6 +1,8 @@ Nette Caching ************* - [Overview |@home] +- [Expiration and Invalidation |expiration] +- [Storages |storages] - [Upgrading] diff --git a/caching/en/expiration.texy b/caching/en/expiration.texy new file mode 100644 index 0000000000..8fa91c6a65 --- /dev/null +++ b/caching/en/expiration.texy @@ -0,0 +1,241 @@ +Expiration and Invalidation +*************************** + +
+ +A cache is only useful as long as it does not serve outdated data. This page shows every way to tell Nette Caching when an item stops being valid: + +- after a period of time, or when nobody has read it for a while +- when a file, a PHP constant or another item in the cache changes +- when your own function says so +- or right away, when you delete it by tag, priority or namespace + +
+ +The examples continue the blog from the [overview |@home]: `$cache` is a cache in the namespace `articles`, `$id` is the ID of an article, and `renderArticle()` stands for the expensive work of loading an article and turning it into HTML. + + +Setting Dependencies +==================== + +**Dependencies** describe when an item expires. They are an array with `Cache::*` keys. The most convenient way is to let the generator fill it in. Declare its parameter as a reference, `&$dependencies`, and `load()` passes it an empty array: + +```php +use Nette\Caching\Cache; + +$html = $cache->load("article/$id", function (&$dependencies) use ($id) { + $dependencies[Cache::Expire] = '1 hour'; + return renderArticle($id); +}); +``` + +The advantage is that the generator can decide based on what it computed. An article that is still being drafted can expire sooner than a published one, for example. + +When the dependencies are known in advance, you can pass them as the third argument of `load()` instead, or of `save()`, which stores a value directly without a generator: + +```php +$html = $cache->load("article/$id", fn() => renderArticle($id), [Cache::Expire => '1 hour']); + +$cache->save("article/$id", $html, [Cache::Expire => '1 hour', Cache::Tags => ["article/$id"]]); +``` + +Prefer `load()` with a generator to `save()`. When several requests ask for a missing item at once, `FileStorage` lets only one of them run the generator; with `save()`, they would all compute the value. + +Before version 3.1.3, the constants were written in uppercase, such as `Cache::EXPIRE` instead of `Cache::Expire`. Keep in mind that the array is not checked: a key with a typo, such as `'expir'`, is silently ignored. + + +Expiration by Time +================== + +The key `Cache::Expire` sets when the item expires. It accepts a relative time as a string, a number of seconds, a UNIX timestamp or a `DateTimeInterface` object: + +```php +$dependencies[Cache::Expire] = '20 minutes'; +$dependencies[Cache::Expire] = 3600; // one hour +$dependencies[Cache::Expire] = new DateTimeImmutable('tomorrow'); +``` + +With **sliding expiration**, every read moves the expiration further. An article that visitors keep reading then stays in the cache, while one nobody opens for 20 minutes is dropped: + +```php +$dependencies[Cache::Expire] = '20 minutes'; +$dependencies[Cache::Sliding] = true; +``` + +Keep in mind that every read then also updates the item in the storage, which adds some overhead. + + +When a File Changes +=================== + +Data computed from a file should expire when the file changes. Let's say the blog reads its list of categories from the file `categories.neon`. The cached list then depends on that file: + +```php +$categories = $cache->load('categories', function (&$dependencies) { + $dependencies[Cache::Files] = __DIR__ . '/categories.neon'; + return loadCategories(); // reads and processes categories.neon +}); +``` + +As soon as you edit `categories.neon`, the cache notices on the next read and calls the generator again. Use absolute paths. An item can depend on several files: `$dependencies[Cache::Files] = [$file1, $file2]`. + + +When a Constant Changes +======================= + +Similarly, an item can expire when the value of a PHP constant changes. That is handy for a version number you set at deployment, for example, so that every new version starts with a fresh cache: + +```php +$dependencies[Cache::Constants] = 'APP_VERSION'; +``` + + +When Another Item Changes +========================= + +An item can depend on other items in the cache. Let's say the article and its comments are cached separately, under the keys `article/$id` and `comments/$id`, and the whole page put together from them is cached as well. The page must expire whenever one of its parts does: + +```php +$page = $cache->load("page/$id", function (&$dependencies) use ($id) { + $dependencies[Cache::Items] = ["article/$id", "comments/$id"]; + return renderPage($id); // puts together the article and its comments +}); +``` + +When the comments are saved again or removed, the page expires as well. + + +Custom Condition +================ + +When none of the above fits, write your own function. It is called on every read with the arguments you stored, and when it returns `false`, the item expires. Let's say the rendered HTML must not survive an upgrade of PHP: + +```php +function checkPhpVersion(int $version): bool +{ + return $version === PHP_VERSION_ID; +} + +$dependencies[Cache::Callbacks] = [['checkPhpVersion', PHP_VERSION_ID]]; +``` + +Each entry is an array: the function, or a static method written as `[ClassName::class, 'method']`, followed by its arguments. The function is called on every read, so it should be fast. + + +Combining Conditions +==================== + +All these conditions can be combined. The item expires as soon as at least one of them is no longer met: + +```php +$dependencies[Cache::Expire] = '1 day'; +$dependencies[Cache::Files] = __DIR__ . '/categories.neon'; +$dependencies[Cache::Constants] = 'APP_VERSION'; +``` + + +Tags +==== + +Waiting for expiration is a compromise. It is better to delete an item exactly when the data it was made from changes. **Tags** let you do that. They are arbitrary strings you attach to an item: + +```php +$html = $cache->load("article/$id", function (&$dependencies) use ($id) { + $dependencies[Cache::Tags] = ["article/$id", "comments/$id"]; + return renderArticle($id); +}); +``` + +In the administration, right after saving an edited article to the database, you delete everything tagged with it: + +```php +$cache->clean([Cache::Tags => ["article/$id"]]); +``` + +The same goes for adding a comment, this time with the tag `comments/$id`. Notice that the code deleting the items does not need to know their keys, or even how many there are. The article may sit in the cache as a whole page, as a preview on the homepage and in the RSS feed; one call removes them all. + +Tags work across namespaces: `clean([Cache::Tags => [...]])` deletes the matching items in every namespace of the storage, not just in the namespace of `$cache`. + +.[note] +`FileStorage` and `MemcachedStorage` need a [journal |storages#Journal] for tags, `SQLiteStorage` keeps them itself and `MemoryStorage` ignores them. + + +Priority +======== + +Each item can be given a priority, a number saying how important it is. When the cache grows too big, you can then delete the less important items first. Let's say previews of old articles are less valuable than the homepage: + +```php +$dependencies[Cache::Priority] = 10; +``` + +This deletes every item with a priority of 50 or less: + +```php +$cache->clean([Cache::Priority => 50]); +``` + +Items without a priority are never deleted this way. + +.[note] +`FileStorage` and `MemcachedStorage` need a [journal |storages#Journal] for priorities; `SQLiteStorage` and `MemoryStorage` ignore them. + + +Deleting Items +============== + +The method `clean()` deletes items by conditions, which you pass as an array with `Cache::*` keys: + +| Key | Deletes +|---------------------- +| `Cache::Tags => [...]` | items with any of the tags +| `Cache::Priority => 50` | items with a priority of 50 or less +| `Cache::Namespaces => [...]` | all items in the listed namespaces; only `FileStorage` supports it +| `Cache::All => true` | everything in the storage, all namespaces included + +The conditions can be combined, and an item matching any of them is deleted: + +```php +$cache->clean([Cache::Tags => ["article/$id"], Cache::Priority => 50]); +``` + +Let's take a closer look at `Cache::All`. It deletes the entire storage, the items of all namespaces included, even when you call it on a cache with a namespace. To delete just one namespace, use `Cache::Namespaces`; the namespaces created from it by `derive()` stay. + +The array is not checked, so a key with a typo is silently ignored and nothing is deleted. + +Removing items that have already expired is a matter of the storage: call `$storage->clean([])`. `FileStorage` and `SQLiteStorage` also do it on their own now and then, see [Storages |storages]. + +To delete a single item, use `$cache->remove("article/$id")`. + + +What Each Storage Supports +========================== + +Not every storage can honor every kind of dependency, and most of them silently ignore what they cannot do. `SQLiteStorage`, for example, ignores priorities and dependencies on files, so such an item simply does not expire that way, and `MemoryStorage` ignores all dependencies. Before relying on a dependency, check the table on the page [Storages |storages#Choosing a Storage]. + + +Bulk Reading and Writing +======================== + +The homepage of the blog shows previews of ten articles. Reading them from the cache one by one means ten round trips to the storage. The method `bulkLoad()` reads them all at once: you pass it the array `$ids` with their IDs as keys, and it returns an array of values indexed by those keys: + +```php +$previews = $cache->bulkLoad($ids, function ($id, &$dependencies) { + $dependencies[Cache::Tags] = ["article/$id"]; + return renderPreview($id); // renders a short preview of the article +}); +``` + +The generator is called only for the previews that are missing, and it receives the key followed by the dependencies. Without a generator, `bulkLoad($ids)` returns `null` for the missing items. + +The method `bulkSave()` stores several items at once, all with the same dependencies: .{data-version:3.3.0} + +```php +$cache->bulkSave([ + "preview/$id1" => $preview1, + "preview/$id2" => $preview2, +], [Cache::Expire => '1 hour']); +``` + +{{maintitle: Nette Caching: Expiration, Tags and Cache Invalidation}} +{{description: Make sure the cache never serves outdated data. Expire items by time, file or constant change, and delete them by tags, priority or namespace.}} diff --git a/caching/en/storages.texy b/caching/en/storages.texy new file mode 100644 index 0000000000..b5fa2f06bf --- /dev/null +++ b/caching/en/storages.texy @@ -0,0 +1,190 @@ +Storages +******** + +
+ +The storage decides where cached data physically lives: in files on disk, on a Memcached server or in an SQLite database. You can switch it without touching the code that uses the cache. This page helps you: + +- choose the right storage and see what each one supports +- configure it in a Nette application, or turn the cache off +- use a Nette storage as a PSR-16 cache +- write a storage of your own + +
+ + +Choosing a Storage +================== + +If you are not sure, keep the default `FileStorage`. It needs nothing but a directory, it is safe when many requests read and write at once, and it supports every kind of dependency. + +When your application runs on several servers, `FileStorage` gives each of them its own cache. `MemcachedStorage` stores the data on a server shared by all of them, but it keeps tags and priorities in a [#journal], a file local to each server, so deleting by tag on one server does not reach the others. + +The storages differ in which [dependencies |expiration] they can honor: + +|------------------------------------------------------------------------------------------------- +| Storage | Tags, priorities | Files, constants, callbacks | Other items | Sliding | Cleaning namespaces | Stampede protection +|------------------------------------------------------------------------------------------------- +| [#FileStorage] | with [#journal] | yes | yes | yes | yes | yes +| [#MemcachedStorage] | with [#journal] | yes | no | yes | ignored | no +| [#SQLiteStorage] | tags only | ignored | ignored | yes | ignored | no +| [#MemoryStorage] | ignored | ignored | ignored | ignored | ignored | no +| [#DevNullStorage] | stores nothing | | | | | + +Where the table says ignored, the storage silently drops the dependency, so the item just does not expire that way. `MemoryStorage` ignores even the expiration. Only `MemcachedStorage` throws `Nette\NotSupportedException`, for the dependency on other items. + +Stampede protection means that when many requests ask for a missing item at once, only the first one runs the generator of `load()` and the others wait for its result. Without it, all of them compute the value at the same time. + + +Configuration +============= + +In a Nette application, the DI container provides a `FileStorage` that stores data in the `cache` subdirectory of the directory for [temporary files |application:bootstrapping#Temporary Files], together with a journal. You get it via [dependency injection |dependency-injection:passing-dependencies] by asking for the type `Nette\Caching\Storage`. + +To use another storage, replace the service `cache.storage` in the configuration: + +```neon +services: + cache.storage: Nette\Caching\Storages\MemcachedStorage('10.0.0.5') +``` + +The container holds these two services: + +| Name | Type | Description +|---------------------------------------------------------- +| `cache.storage` | [api:Nette\Caching\Storage] | the storage +| `cache.journal` | [api:Nette\Caching\Storages\Journal] | the [#journal] for tags and priorities + + +Turning Off the Cache +--------------------- + +To turn the cache off, for example in tests, use [#DevNullStorage], which stores nothing: + +```neon +services: + cache.storage: Nette\Caching\Storages\DevNullStorage +``` + +This does not affect the caches of Latte templates and of the DI container, which are separate and do not use this storage. They [do not need to be turned off |nette:troubleshooting#How to Disable Cache During Development] during development either. + + +FileStorage +=========== + +`Nette\Caching\Storages\FileStorage` writes each item into a file in the given directory, which must exist. Tags and priorities need a [#journal]: + +```php +$journal = new Nette\Caching\Storages\SQLiteJournal('/path/to/temp/journal.s3db'); +$storage = new Nette\Caching\Storages\FileStorage('/path/to/temp', $journal); +``` + +All operations are atomic. You can never read a file another request has not finished writing yet, and nobody can delete it while you are reading it. That makes the storage safe even under heavy load. + +It also protects against the [cache stampede |https://en.wikipedia.org/wiki/Cache_stampede]. When many requests ask for a missing item at once, for example right after a deployment, the first one locks the file and runs the generator. The others wait for the lock and then read the fresh value instead of computing it again. + +Expired files are removed now and then by the constructor. To remove them at a moment of your choosing, call `$storage->clean([])`. + + +MemcachedStorage +================ + +`Nette\Caching\Storages\MemcachedStorage` stores data on a [Memcached |https://memcached.org] server. The constructor takes the host and the port, 11211 by default. Tags and priorities need a [#journal]. + +.[caution] +Requires the `memcached` PHP extension. + +```neon +services: + cache.storage: Nette\Caching\Storages\MemcachedStorage('10.0.0.5') +``` + +Memcached cannot list its keys, so the storage ignores cleaning by namespaces. For the dependency on other items, it throws an exception. Clearing the whole cache empties the entire Memcached server, including the data of other applications. + + +SQLiteStorage +============= + +`Nette\Caching\Storages\SQLiteStorage` keeps the whole cache in a single SQLite database file. It stores tags in its own table, so it needs no journal. + +.[caution] +Requires the `pdo` and `pdo_sqlite` PHP extensions. + +```neon +services: + cache.storage: Nette\Caching\Storages\SQLiteStorage('%tempDir%/cache.db') +``` + +The storage supports expiration, sliding expiration and tags. Priorities, dependencies on files, constants, callbacks and other items, and cleaning by namespaces are silently ignored. + + +MemoryStorage +============= + +`Nette\Caching\Storages\MemoryStorage` keeps data in a PHP array, so it is lost when the request ends. It is handy in tests and for caching within a single request. + +It ignores all dependencies, expiration included, and of the conditions of `clean()` it honors only `Cache::All`. Keep that in mind when you use it in tests instead of a real storage: an item that would expire there stays here. + + +DevNullStorage +============== + +`Nette\Caching\Storages\DevNullStorage` stores nothing, so every `load()` calls the generator. Use it to [turn the cache off |#Turning Off the Cache]. + + +Journal +======= + +`FileStorage` and `MemcachedStorage` cannot search their items by tag or priority, so they keep a separate index, the so-called journal. The built-in `Nette\Caching\Storages\SQLiteJournal` stores it in an SQLite database: + +```php +$journal = new Nette\Caching\Storages\SQLiteJournal('/path/to/temp/journal.s3db'); +``` + +.[caution] +Requires the `pdo` and `pdo_sqlite` PHP extensions. + +In a Nette application, the journal is created for you as the service `cache.journal` in the file `journal.s3db` and passed to the storage automatically. Your own implementation of the interface `Nette\Caching\Storages\Journal` can replace it: + +```neon +services: + cache.journal: MyJournal +``` + +Without a journal, these storages work too, but storing an item with tags or a priority throws an exception. + + +Using a Storage as a PSR-16 Cache .{data-version:3.3.1} +======================================================= + +Some libraries expect a [PSR-16 |https://www.php-fig.org/psr/psr-16/] cache. The adapter `Nette\Bridges\Psr\PsrCacheAdapter` gives them one on top of any Nette storage: + +```php +$psrCache = new Nette\Bridges\Psr\PsrCacheAdapter($storage); + +$psrCache->set('key', 'value', 3600); // stores the value for 1 hour +$value = $psrCache->get('key', 'default'); +``` + +The adapter supports all methods of PSR-16, including `getMultiple()`, `setMultiple()` and `deleteMultiple()`. + + +Writing Your Own Storage +======================== + +A storage is a class implementing the interface `Nette\Caching\Storage` (before version 3.1 named `Nette\Caching\IStorage`) with five methods: + +- `read(string $key)` returns the stored value, or `null` when the item does not exist or has expired +- `lock(string $key): void` locks the item before `Cache` runs a generator; the lock is released by `write()` or `remove()`, and a storage that does not protect against the cache stampede leaves the method empty +- `write(string $key, mixed $data, array $dependencies): void` stores the value +- `remove(string $key): void` deletes the item +- `clean(array $conditions): void` deletes items by the conditions of [clean() |expiration#Deleting Items]; an empty array means removing the expired items + +The dependencies arrive as an array with `Cache::*` keys, already simplified by `Cache`: the expiration is a number of seconds from now, files and constants have become callbacks, and other items are given by their storage keys. When reading an item, check its callbacks with `Nette\Caching\Cache::checkCallbacks()`. Throw `Nette\NotSupportedException` for a dependency or condition your storage cannot honor. + +Optional interfaces add more. `Nette\Caching\BulkReader` and, since version 3.3, `Nette\Caching\BulkWriter` let the storage read and write several items in one round trip. + +A short complete example is the source code of [SQLiteStorage |https://github.com/nette/caching/blob/v3.4/src/Caching/Storages/SQLiteStorage.php]. + +{{maintitle: Nette Caching Storages: Files, Memcached, SQLite}} +{{description: Choose where the Nette cache stores data: files, Memcached or SQLite. Compare what each storage supports and configure it in your application.}} From 0d7d4bb58d54704dcbca65a6857002d6cfd92598 Mon Sep 17 00:00:00 2001 From: David Grudl Date: Sat, 7 Nov 2026 15:18:00 +0100 Subject: [PATCH 4/7] caching: updated for version 4.0 --- caching/cs/@home.texy | 34 ++++++++------ caching/cs/expiration.texy | 96 +++++++++++++++++++------------------- caching/cs/storages.texy | 92 +++++++++++++++++++++++++++--------- caching/cs/upgrading.texy | 29 +++++++++++- caching/en/@home.texy | 34 ++++++++------ caching/en/expiration.texy | 96 +++++++++++++++++++------------------- caching/en/storages.texy | 92 +++++++++++++++++++++++++++--------- caching/en/upgrading.texy | 29 +++++++++++- caching/meta.json | 2 +- 9 files changed, 331 insertions(+), 173 deletions(-) diff --git a/caching/cs/@home.texy b/caching/cs/@home.texy index 91206c54bf..78f886e24d 100644 --- a/caching/cs/@home.texy +++ b/caching/cs/@home.texy @@ -9,7 +9,7 @@ Počítá vaše aplikace pořád dokola totéž, třeba převádí článek do H - Data vyexpirují po čase, nebo když se změní soubor, jiná položka či vaše vlastní podmínka - Tagy smažou přesně ty položky, které souvisejí s právě upraveným článkem - Nával požadavků na chybějící položku server nepřetíží -- Ukládá do souborů, do Memcached nebo SQLite +- Ukládá do souborů, do Redisu, Memcached, SQLite nebo libovolné PSR-16 cache - Cachuje části šablon Latte @@ -24,6 +24,8 @@ Knihovnu stáhnete a nainstalujete pomocí nástroje [Composer|best-practices:co composer require nette/caching ``` +Vyžaduje PHP verze 8.4 a podporuje PHP až do verze 8.6. + První cache =========== @@ -74,13 +76,15 @@ Jak dlouho data platí? Náš článek v cache se teď nikdy nezmění. Jenže co když v něm opravíte překlep? Návštěvníci by dál viděli starou verzi. Musíte cache říct, kdy položka přestává platit. Nejjednodušší je časový limit: ```php -$html = $cache->load("article/$id", function (&$dependencies) use ($id) { - $dependencies[Cache::Expire] = '1 hour'; +use Nette\Caching\Dependencies; + +$html = $cache->load("article/$id", function (Dependencies $dp) use ($id) { + $dp->expire = '1 hour'; return renderArticle($id); }); ``` -Generátor teď přijímá referencí parametr `$dependencies`. Je to pole, do kterého generátor zapíše, kdy položka vyexpiruje. Říká se mu závislosti, protože na nich závisí platnost položky. Tady je to jedna hodina. +Generátor teď přijímá parametr typu `Dependencies` a `load()` mu předá objekt, ve kterém generátor popíše, kdy položka vyexpiruje. Říká se mu závislosti, protože na nich závisí platnost položky. Tady je to jedna hodina. Čas je jen jedna z možností. Položka může vyexpirovat i ve chvíli, kdy se změní soubor nebo jiná položka v cache, případně když to řekne vaše vlastní podmínka. To všechno popisuje stránka [Expirace a invalidace |expiration]. @@ -91,8 +95,8 @@ Smazat přesně to, co se změnilo Časový limit je kompromis: nastavíte ho krátký a cache moc nepomůže, nastavíte dlouhý a návštěvníci vidí stará data. Lepší je smazat článek z cache přesně ve chvíli, kdy ho upravíte. K tomu slouží **tagy**. Položce je přiřadíte jako libovolné řetězce: ```php -$html = $cache->load("article/$id", function (&$dependencies) use ($id) { - $dependencies[Cache::Tags] = ["article/$id", "comments/$id"]; +$html = $cache->load("article/$id", function (Dependencies $dp) use ($id) { + $dp->tags = ["article/$id", "comments/$id"]; return renderArticle($id); }); ``` @@ -100,7 +104,7 @@ $html = $cache->load("article/$id", function (&$dependencies) use ($id) { Stránka ukazuje článek i s komentáři, proto jsme jí dali dva tagy. V administraci pak hned po uložení upraveného článku do databáze smažete všechno, co nese jeho tag: ```php -$cache->clean([Cache::Tags => ["article/$id"]]); +$cache->clean(tags: ["article/$id"]); ``` A totéž, když někdo přidá komentář, tentokrát s tagem `comments/$id`. Od teď stránka z cache zmizí přesně ve chvíli, kdy se změní její článek nebo komentáře, a další návštěvník dostane čerstvě vyrenderovanou. @@ -126,13 +130,13 @@ Jmenný prostor `'articles'` jsme už potkali v konstruktoru cache. Každá čá $commentCache = new Cache($storage, 'comments'); ``` -Metoda `derive()` vytvoří cache ve vnořeném jmenném prostoru: `$cache->derive('previews')` dá prostor `previews` uvnitř `articles`. A když chcete zahodit všechno ve jmenném prostoru, zavolejte: +Metoda `derive()` vytvoří cache ve vnořeném jmenném prostoru: `$cache->derive('previews')` dá prostor `previews` uvnitř `articles`. A když chcete zahodit všechno ve jmenném prostoru včetně vnořených, zavolejte: ```php -$cache->clean([Cache::Namespaces => ['articles']]); +$cache->clean(all: true); ``` -Ostatní jmenné prostory, i ty vnořené, zůstanou nedotčené. Mazání podle jmenného prostoru funguje s `FileStorage`, ostatní úložiště ho ignorují. Pozor na `Cache::All`, který smaže celé úložiště včetně všech jmenných prostorů. +Ostatní jmenné prostory zůstanou nedotčené. Jen cache vytvořená bez jmenného prostoru, `new Cache($storage)`, takhle smaže celé úložiště. Memoizace @@ -166,7 +170,7 @@ if ($capture = $cache->capture('sidebar')) { } ``` -Když už je výstup v cache, `capture()` ho vypíše a vrátí `null`, takže se blok uvnitř `if` vůbec nevykoná. Jinak začne výstup zachytávat a vrátí objekt, jehož metoda `end()` uloží všechno, co se mezitím vypsalo. Můžete jí předat i závislosti, třeba `$capture->end([Cache::Tags => ['articles']])`. Ve verzi 3.0 se metoda `capture()` jmenovala `start()`. +Když už je výstup v cache, `capture()` ho vypíše a vrátí `null`, takže se blok uvnitř `if` vůbec nevykoná. Jinak začne výstup zachytávat a vrátí objekt, jehož metoda `end()` uloží všechno, co se mezitím vypsalo. Můžete jí předat i závislosti, třeba `$capture->end(new Dependencies(tags: ['articles']))`. Cachování v Latte @@ -201,9 +205,11 @@ Zatím jsme používali `FileStorage`, kterému stačí adresář. Díky atomick | Úložiště | Kde data leží |---------------------- | `FileStorage` | v souborech na disku; výchozí úložiště +| `RedisStorage` | na serveru Redis | `MemcachedStorage` | na serveru Memcached | `SQLiteStorage` | v souboru databáze SQLite | `MemoryStorage` | v paměti, jen do konce požadavku +| `Psr16Storage` | v libovolné PSR-16 cache | `DevNullStorage` | nikde; pro testy a pro vypnutí cache Úložiště můžete vyměnit, aniž byste sáhli na kód, který cache používá. Které si vybrat, co které umí a jak ho nastavit, včetně vypnutí cache, popisuje stránka [Úložiště |storages]. @@ -212,7 +218,7 @@ Zatím jsme používali `FileStorage`, kterému stačí adresář. Díky atomick Cache v aplikaci Nette ====================== -V aplikaci postavené na Nette si úložiště sami nevytváříte. Nette poskytuje `FileStorage`, které ukládá data do podadresáře `cache` v adresáři pro [dočasné soubory |application:bootstrapping#Dočasné soubory], a k němu i journal. Dostanete ho pomocí [dependency injection |dependency-injection:passing-dependencies], když si řeknete o typ `Nette\Caching\Storage` (před verzí 3.1 se jmenoval `Nette\Caching\IStorage`), a cache si vytvoříte v konstruktoru: +V aplikaci postavené na Nette si úložiště sami nevytváříte. Nette poskytuje `FileStorage`, které ukládá data do podadresáře `cache` v adresáři pro [dočasné soubory |application:bootstrapping#Dočasné soubory], a k němu i journal. Dostanete ho pomocí [dependency injection |dependency-injection:passing-dependencies], když si řeknete o typ `Nette\Caching\Storage`, a cache si vytvoříte v konstruktoru: ```php use Nette\Caching\Cache; @@ -245,8 +251,8 @@ Co dál ====== - [Expirace a invalidace |expiration] - všechny způsoby, jak cache říct, kdy data vyexpirují, a mazání podle tagů, priority a jmenného prostoru -- [Úložiště |storages] - výběr a nastavení úložiště, PSR-16, vlastní úložiště -- [Upgrade |upgrading] - co se změnilo v jednotlivých verzích +- [Úložiště |storages] - výběr a nastavení úložiště, PSR-16 oběma směry, vlastní úložiště +- [Upgrade |upgrading] - co se změnilo ve verzi 4.0 {{maintitle: Cache v PHP s Nette: úložiště, expirace a invalidace}} {{description: Zrychlete aplikaci tím, že náročně získaná data uložíte pro příští použití. Cache z Nette v PHP i Latte, změna úložiště a správná invalidace.}} diff --git a/caching/cs/expiration.texy b/caching/cs/expiration.texy index 3d19a30675..14940c2b89 100644 --- a/caching/cs/expiration.texy +++ b/caching/cs/expiration.texy @@ -18,48 +18,48 @@ Ukázky navazují na blog z [úvodu |@home]: `$cache` je cache ve jmenném prost Nastavení závislostí ==================== -Kdy položka vyexpiruje, popisují **závislosti**, tedy pole s klíči `Cache::*`. Nejpohodlnější je nechat je vyplnit generátor. Stačí deklarovat jeho parametr jako referenci, `&$dependencies`, a `load()` mu předá prázdné pole: +Kdy položka vyexpiruje, popisují **závislosti**, tedy objekt `Nette\Caching\Dependencies`. Nejpohodlnější je nechat je vyplnit generátor. Stačí deklarovat jeho parametr s typem `Dependencies` a `load()` mu předá prázdný objekt: ```php -use Nette\Caching\Cache; +use Nette\Caching\Dependencies; -$html = $cache->load("article/$id", function (&$dependencies) use ($id) { - $dependencies[Cache::Expire] = '1 hour'; +$html = $cache->load("article/$id", function (Dependencies $dp) use ($id) { + $dp->expire = '1 hour'; return renderArticle($id); }); ``` Výhoda je, že se generátor může rozhodnout podle toho, co spočítal. Rozepsaný článek může třeba vyexpirovat dřív než publikovaný. -Když závislosti znáte předem, můžete je místo toho předat jako třetí argument metodě `load()`, případně metodě `save()`, která hodnotu uloží rovnou, bez generátoru: +Když závislosti znáte předem, můžete je místo toho předat jako třetí argument metodě `load()`, případně metodě `save()`, která hodnotu uloží rovnou, bez generátoru. Konstruktor přijímá všechny vlastnosti jako pojmenované argumenty: ```php -$html = $cache->load("article/$id", fn() => renderArticle($id), [Cache::Expire => '1 hour']); +$html = $cache->load("article/$id", fn() => renderArticle($id), new Dependencies(expire: '1 hour')); -$cache->save("article/$id", $html, [Cache::Expire => '1 hour', Cache::Tags => ["article/$id"]]); +$cache->save("article/$id", $html, new Dependencies(expire: '1 hour', tags: ["article/$id"])); ``` -Dávejte přednost `load()` s generátorem před `save()`. Když o chybějící položku požádá víc požadavků najednou, `FileStorage` spustí generátor jen u jednoho z nich; se `save()` by hodnotu počítaly všechny. +Dávejte přednost `load()` s generátorem před `save()`. Když o chybějící položku požádá víc požadavků najednou, `FileStorage` a `RedisStorage` spustí generátor jen u jednoho z nich; se `save()` by hodnotu počítaly všechny. -Před verzí 3.1.3 se konstanty psaly velkými písmeny, třeba `Cache::EXPIRE` místo `Cache::Expire`. Počítejte s tím, že se pole nekontroluje: klíč s překlepem, třeba `'expir'`, se potichu ignoruje. +Závislosti lze zapsat i jako pole s klíči `Cache::*`, třeba `[Cache::Expire => '1 hour', Cache::Tags => ["article/$id"]]`. Generátor, jehož parametr nemá typ `Dependencies`, dostane toto pole referencí a přidává do něj: `function (&$dependencies)`. Neznámý klíč nebo hodnota špatného typu v poli vyhodí výjimku, takže překlep jako `'expir'` nenechá položku potichu bez expirace. Expirace podle času =================== -Klíč `Cache::Expire` určuje, kdy položka vyexpiruje. Přijímá relativní čas jako řetězec, počet sekund, UNIX timestamp nebo objekt `DateTimeInterface`: +Vlastnost `expire` určuje, kdy položka vyexpiruje. Přijímá relativní čas jako řetězec, počet sekund, UNIX timestamp nebo objekt `DateTimeInterface`: ```php -$dependencies[Cache::Expire] = '20 minutes'; -$dependencies[Cache::Expire] = 3600; // jedna hodina -$dependencies[Cache::Expire] = new DateTimeImmutable('tomorrow'); +$dp->expire = '20 minutes'; +$dp->expire = 3600; // jedna hodina +$dp->expire = new DateTimeImmutable('tomorrow'); ``` U **klouzavé expirace** každé čtení posune expiraci dál. Článek, který návštěvníci pořád čtou, pak zůstává v cache, zatímco ten, který 20 minut nikdo neotevře, z ní vypadne: ```php -$dependencies[Cache::Expire] = '20 minutes'; -$dependencies[Cache::Sliding] = true; +$dp->expire = '20 minutes'; +$dp->sliding = true; ``` Počítejte s tím, že každé čtení pak položku v úložišti zároveň aktualizuje, což přidává režii. @@ -71,13 +71,13 @@ Když se změní soubor Data spočítaná ze souboru by měla vyexpirovat, když se soubor změní. Dejme tomu, že blog čte seznam kategorií ze souboru `categories.neon`. Seznam v cache na tom souboru tedy závisí: ```php -$categories = $cache->load('categories', function (&$dependencies) { - $dependencies[Cache::Files] = __DIR__ . '/categories.neon'; +$categories = $cache->load('categories', function (Dependencies $dp) { + $dp->files[] = __DIR__ . '/categories.neon'; return loadCategories(); // přečte a zpracuje categories.neon }); ``` -Jakmile `categories.neon` upravíte, cache si toho při dalším čtení všimne a zavolá generátor znovu. Používejte absolutní cesty. Položka může záviset i na více souborech: `$dependencies[Cache::Files] = [$file1, $file2]`. +Jakmile `categories.neon` upravíte, cache si toho při dalším čtení všimne a zavolá generátor znovu. Používejte absolutní cesty. Položka může záviset i na více souborech: `$dp->files = [$file1, $file2]`. Když se změní konstanta @@ -86,7 +86,7 @@ Když se změní konstanta Podobně může položka vyexpirovat, když se změní hodnota PHP konstanty. Hodí se to třeba pro číslo verze, které nastavujete při nasazení, aby každá nová verze začínala s čerstvou cache: ```php -$dependencies[Cache::Constants] = 'APP_VERSION'; +$dp->constants[] = 'APP_VERSION'; ``` @@ -96,8 +96,8 @@ Když se změní jiná položka Položka může záviset na jiných položkách v cache. Dejme tomu, že článek a jeho komentáře cachujete zvlášť, pod klíči `article/$id` a `comments/$id`, a cachujete i celou stránku z nich složenou. Stránka musí vyexpirovat, kdykoliv vyexpiruje některá z jejích částí: ```php -$page = $cache->load("page/$id", function (&$dependencies) use ($id) { - $dependencies[Cache::Items] = ["article/$id", "comments/$id"]; +$page = $cache->load("page/$id", function (Dependencies $dp) use ($id) { + $dp->items = ["article/$id", "comments/$id"]; return renderPage($id); // poskládá článek a jeho komentáře }); ``` @@ -116,7 +116,7 @@ function checkPhpVersion(int $version): bool return $version === PHP_VERSION_ID; } -$dependencies[Cache::Callbacks] = [['checkPhpVersion', PHP_VERSION_ID]]; +$dp->callbacks[] = ['checkPhpVersion', PHP_VERSION_ID]; ``` Každá položka je pole: funkce, případně statická metoda zapsaná jako `[ClassName::class, 'method']`, a za ní její argumenty. Funkce se volá při každém čtení, takže by měla být rychlá. @@ -128,9 +128,9 @@ Kombinace podmínek Všechny tyto podmínky lze kombinovat. Položka vyexpiruje, jakmile přestane platit alespoň jedna z nich: ```php -$dependencies[Cache::Expire] = '1 day'; -$dependencies[Cache::Files] = __DIR__ . '/categories.neon'; -$dependencies[Cache::Constants] = 'APP_VERSION'; +$dp->expire = '1 day'; +$dp->files[] = __DIR__ . '/categories.neon'; +$dp->constants[] = 'APP_VERSION'; ``` @@ -140,8 +140,8 @@ Tagy Čekat na expiraci je kompromis. Lepší je položku smazat přesně ve chvíli, kdy se změní data, ze kterých vznikla. To umožňují **tagy**. Jsou to libovolné řetězce, které položce přiřadíte: ```php -$html = $cache->load("article/$id", function (&$dependencies) use ($id) { - $dependencies[Cache::Tags] = ["article/$id", "comments/$id"]; +$html = $cache->load("article/$id", function (Dependencies $dp) use ($id) { + $dp->tags = ["article/$id", "comments/$id"]; return renderArticle($id); }); ``` @@ -149,15 +149,15 @@ $html = $cache->load("article/$id", function (&$dependencies) use ($id) { V administraci pak hned po uložení upraveného článku do databáze smažete všechno, co nese jeho tag: ```php -$cache->clean([Cache::Tags => ["article/$id"]]); +$cache->clean(tags: ["article/$id"]); ``` Totéž platí pro přidání komentáře, tentokrát s tagem `comments/$id`. Všimněte si, že kód, který položky maže, nemusí znát jejich klíče, ani kolik jich je. Článek může v cache ležet jako celá stránka, jako náhled na úvodní stránce i v RSS kanálu; jedno volání je odstraní všechny. -Tagy fungují napříč jmennými prostory: `clean([Cache::Tags => [...]])` smaže odpovídající položky ve všech jmenných prostorech úložiště, nejen v prostoru `$cache`. +Tagy fungují napříč jmennými prostory: `clean(tags: [...])` smaže odpovídající položky ve všech jmenných prostorech úložiště, nejen v prostoru `$cache`. .[note] -`FileStorage` a `MemcachedStorage` potřebují pro tagy [journal |storages#Journal], `SQLiteStorage` si je drží samo a `MemoryStorage` je ignoruje. +`FileStorage`, `MemcachedStorage` a `Psr16Storage` potřebují pro tagy [journal |storages#Journal]; ostatní úložiště si je drží sama. Priorita @@ -166,44 +166,44 @@ Priorita Každé položce můžete dát prioritu, tedy číslo, které říká, jak je důležitá. Když cache příliš naroste, můžete pak smazat nejdřív ty méně důležité. Dejme tomu, že náhledy starých článků mají menší cenu než úvodní stránka: ```php -$dependencies[Cache::Priority] = 10; +$dp->priority = 10; ``` Takto smažete všechny položky s prioritou 50 nebo menší: ```php -$cache->clean([Cache::Priority => 50]); +$cache->clean(priority: 50); ``` Položky bez priority se tímto způsobem nikdy nesmažou. .[note] -`FileStorage` a `MemcachedStorage` potřebují pro priority [journal |storages#Journal]; `SQLiteStorage` a `MemoryStorage` je ignorují. +`FileStorage`, `MemcachedStorage` a `Psr16Storage` potřebují pro priority [journal |storages#Journal], `RedisStorage` a `MemoryStorage` si je drží samy a `SQLiteStorage` je nepodporuje. Mazání položek ============== -Metoda `clean()` maže položky podle podmínek, které předáte jako pole s klíči `Cache::*`: +Metoda `clean()` maže položky podle podmínek, které předáte jako pojmenované argumenty: -| Klíč | Smaže +| Argument | Smaže |---------------------- -| `Cache::Tags => [...]` | položky s kterýmkoliv z tagů -| `Cache::Priority => 50` | položky s prioritou 50 nebo menší -| `Cache::Namespaces => [...]` | všechny položky v uvedených jmenných prostorech; podporuje jen `FileStorage` -| `Cache::All => true` | vše v úložišti, včetně všech jmenných prostorů +| `tags: [...]` | položky s kterýmkoliv z tagů +| `priority: 50` | položky s prioritou 50 nebo menší +| `namespaces: [...]` | všechny položky v uvedených jmenných prostorech, včetně prostorů z nich odvozených +| `all: true` | vše ve jmenném prostoru této cache, včetně prostorů z něj odvozených Podmínky lze kombinovat a smaže se položka, která splňuje kteroukoliv z nich: ```php -$cache->clean([Cache::Tags => ["article/$id"], Cache::Priority => 50]); +$cache->clean(tags: ["article/$id"], priority: 50); ``` -Podívejme se blíž na `Cache::All`. Smaže celé úložiště včetně položek všech jmenných prostorů, i když ho zavoláte na cache se jmenným prostorem. Pokud chcete smazat jen jeden jmenný prostor, použijte `Cache::Namespaces`; prostory, které z něj vznikly pomocí `derive()`, zůstanou. +Podívejme se blíž na `all`. Smaže celý jmenný prostor cache spolu s prostory, které z něj vznikly pomocí `derive()`, a ostatních jmenných prostorů se nedotkne. Jen cache vytvořená bez jmenného prostoru, `new Cache($storage)`, takhle smaže celé úložiště. -Pole se nekontroluje, takže klíč s překlepem se potichu ignoruje a nic se nesmaže. +Podmínky lze zapsat i jako pole s klíči `Cache::*`, třeba `$cache->clean([Cache::Tags => ["article/$id"]])`. Stejně jako u závislostí vyhodí neznámý klíč nebo hodnota špatného typu výjimku. -Odstranit položky, které už vyexpirovaly, je věc úložiště: zavolejte `$storage->clean([])`. `FileStorage` a `SQLiteStorage` to ostatně čas od času dělají samy, viz [Úložiště |storages]. +Volání `clean()` bez jakékoliv podmínky vyhodí výjimku také, protože není jasné, co by mělo smazat. Odstranit položky, které už vyexpirovaly, je věc úložiště: zavolejte `$storage->clean([])`. Většina úložišť to ostatně dělá sama, viz [Úložiště |storages]. Jednu položku smažete pomocí `$cache->remove("article/$id")`. @@ -211,7 +211,7 @@ Jednu položku smažete pomocí `$cache->remove("article/$id")`. Co které úložiště umí ===================== -Ne každé úložiště umí každý druh závislosti a většina z nich to, co neumí, potichu ignoruje. `SQLiteStorage` třeba ignoruje priority a závislosti na souborech, takže položka podle nich prostě nevyexpiruje, a `MemoryStorage` ignoruje všechny závislosti. Než se na nějakou závislost spolehnete, podívejte se do tabulky na stránce [Úložiště |storages#Výběr úložiště]. +Ne každé úložiště umí každý druh závislosti. Úložiště, které některou neumí, vyhodí `Nette\NotSupportedException`, místo aby ji potichu ignorovalo, takže na to přijdete hned, a ne až podle zastaralých dat. `SQLiteStorage` třeba nepodporuje priority ani závislosti na souborech. Jedinou výjimkou je `MemoryStorage`, které ignoruje, co neumí. Úplný přehled najdete v tabulce na stránce [Úložiště |storages#Výběr úložiště]. Hromadné čtení a zápis @@ -220,21 +220,21 @@ Hromadné čtení a zápis Úvodní stránka blogu ukazuje náhledy deseti článků. Číst je z cache jeden po druhém znamená desetkrát se obrátit na úložiště. Metoda `bulkLoad()` je přečte všechny najednou: předáte jí pole `$ids` s jejich ID jako klíči a vrátí pole hodnot indexované těmito klíči: ```php -$previews = $cache->bulkLoad($ids, function ($id, &$dependencies) { - $dependencies[Cache::Tags] = ["article/$id"]; +$previews = $cache->bulkLoad($ids, function ($id, Dependencies $dp) { + $dp->tags = ["article/$id"]; return renderPreview($id); // vyrenderuje krátký náhled článku }); ``` Generátor se zavolá jen pro náhledy, které chybí, a dostane klíč a za ním závislosti. Bez generátoru vrátí `bulkLoad($ids)` pro chybějící položky `null`. -Metoda `bulkSave()` uloží několik položek najednou, všechny se stejnými závislostmi: .{data-version:3.3.0} +Metoda `bulkSave()` uloží několik položek najednou, všechny se stejnými závislostmi: ```php $cache->bulkSave([ "preview/$id1" => $preview1, "preview/$id2" => $preview2, -], [Cache::Expire => '1 hour']); +], new Dependencies(expire: '1 hour')); ``` {{maintitle: Nette Caching: expirace, tagy a invalidace cache}} diff --git a/caching/cs/storages.texy b/caching/cs/storages.texy index f686b32921..312141b9a1 100644 --- a/caching/cs/storages.texy +++ b/caching/cs/storages.texy @@ -3,11 +3,11 @@
-Úložiště určuje, kde data z cache fyzicky leží: v souborech na disku, na serveru Memcached nebo v databázi SQLite. Vyměnit ho můžete, aniž byste sáhli na kód, který cache používá. Tato stránka vám pomůže: +Úložiště určuje, kde data z cache fyzicky leží: v souborech na disku, na serveru Redis nebo Memcached, v databázi SQLite nebo v PSR-16 cache jiného frameworku. Vyměnit ho můžete, aniž byste sáhli na kód, který cache používá. Tato stránka vám pomůže: - vybrat správné úložiště a zjistit, co které umí - nastavit ho v aplikaci Nette, případně cache vypnout -- použít úložiště z Nette jako PSR-16 cache +- použít úložiště z Nette jako PSR-16 cache, a obráceně - napsat si vlastní úložiště
@@ -18,7 +18,7 @@ Výběr úložiště Pokud si nejste jistí, nechte výchozí `FileStorage`. Stačí mu adresář, je bezpečné, i když najednou čte a zapisuje mnoho požadavků, a podporuje všechny druhy závislostí. -Když aplikace běží na více serverech, `FileStorage` dá každému z nich vlastní cache. `MemcachedStorage` ukládá data na server, který sdílejí všechny, jenže tagy a priority si drží v [journalu |#journal], což je soubor na každém serveru zvlášť, takže mazání podle tagu na jednom serveru se k ostatním nedostane. +Po `RedisStorage` sáhněte, když aplikace běží na více serverech. Se soubory by měl každý server vlastní cache, a když byste smazali článek podle tagu na jednom serveru, na ostatních by zůstaly jeho zastaralé kopie. Server Redis sdílejí všechny. Úložiště se liší tím, které [závislosti |expiration] umí respektovat: @@ -26,12 +26,14 @@ Když aplikace běží na více serverech, `FileStorage` dá každému z nich vl | Úložiště | Tagy, priority | Soubory, konstanty, callbacky | Jiné položky | Klouzavá expirace | Mazání jmenných prostorů | Ochrana proti stampede |------------------------------------------------------------------------------------------------- | [#FileStorage] | s [journalem |#journal] | ano | ano | ano | ano | ano -| [#MemcachedStorage] | s [journalem |#journal] | ano | ne | ano | ignoruje | ne -| [#SQLiteStorage] | jen tagy | ignoruje | ignoruje | ano | ignoruje | ne -| [#MemoryStorage] | ignoruje | ignoruje | ignoruje | ignoruje | ignoruje | ne +| [#RedisStorage] | ano | ano | ne | ano | ano | ano +| [#MemcachedStorage] | s [journalem |#journal] | ano | ne | ano | ne | ne +| [#SQLiteStorage] | jen tagy | ne | ne | ano | ano | ne +| [#MemoryStorage] | ano | ignoruje | ignoruje | ano | ano | ne +| [#Psr16Storage] | s [journalem |#journal] | ano | ne | ne | ne | ne | [#DevNullStorage] | nic neukládá | | | | | -Kde tabulka uvádí ignoruje, úložiště závislost potichu zahodí, takže položka podle ní prostě nevyexpiruje. `MemoryStorage` ignoruje dokonce i expiraci. Jen `MemcachedStorage` vyhodí `Nette\NotSupportedException`, a to pro závislost na jiných položkách. +Úložiště, které některou závislost neumí, vyhodí `Nette\NotSupportedException`, místo aby ji potichu ignorovalo, takže na to přijdete hned, a ne až podle zastaralých dat. Jedinou výjimkou je `MemoryStorage`, které ignoruje, co neumí. Ochrana proti stampede znamená, že když o chybějící položku požádá najednou mnoho požadavků, generátor z `load()` spustí jen první z nich a ostatní počkají na jeho výsledek. Bez ní hodnotu počítají všechny zároveň. @@ -45,7 +47,7 @@ Pokud chcete jiné úložiště, nahraďte v konfiguraci službu `cache.storage` ```neon services: - cache.storage: Nette\Caching\Storages\MemcachedStorage('10.0.0.5') + cache.storage: Nette\Caching\Storages\RedisStorage('10.0.0.5') ``` Kontejner obsahuje tyto dvě služby: @@ -83,7 +85,31 @@ Všechny operace jsou atomické. Nikdy nepřečtete soubor, který jiný požada Navíc chrání před [cache stampede |https://en.wikipedia.org/wiki/Cache_stampede]. Když o chybějící položku požádá najednou mnoho požadavků, třeba hned po nasazení, první z nich soubor zamkne a spustí generátor. Ostatní počkají na zámek a pak přečtou čerstvou hodnotu, místo aby ji počítaly znovu. -Vyexpirované soubory čas od času smaže konstruktor. Pokud je chcete smazat v okamžiku, který si zvolíte sami, zavolejte `$storage->clean([])`. +Vyexpirované soubory se mažou postupně. Čas od času jim konstruktor věnuje nejvýš 20 ms, takže ani velká cache požadavek znatelně nezdrží. Všechny vyexpirované soubory najednou smažete voláním `$storage->clean([])`. + +Data se ukládají pomocí PHP funkce `serialize()`. Pokud chcete jiný formát, vytvořte potomka a přepište metody `serializeData()` a `unserializeData()`. + + +RedisStorage +============ + +`Nette\Caching\Storages\RedisStorage` ukládá data na server [Redis |https://redis.io]. Tagy a priority si drží sám, takže nepotřebuje journal, a chrání před cache stampede stejně jako `FileStorage`. + +.[caution] +Vyžaduje PHP rozšíření `redis`. + +```neon +services: + cache.storage: Nette\Caching\Storages\RedisStorage('10.0.0.5') +``` + +Konstruktor přijímá adresu serveru a port, výchozí je 6379. Pokud už máte připojený objekt `Redis`, předejte ho místo adresy. + +Všechny klíče dostanou prefix `nette.cache:`, takže databázi můžete sdílet s jinými daty; změníte ho parametrem `prefix`. Prázdný prefix znamená, že celá databáze patří cache, a smazání cache pak databázi vyprázdní. + +Zatímco jeden proces chybějící položku generuje, ostatní na ni čekají, standardně nejvýš 30 sekund (parametr `lockTimeout`). Generátor, který trvá déle, znamená jen to, že stejnou hodnotu spočítá i další proces, nikdy to, že se uloží špatná hodnota. + +Úložiště nepodporuje závislost na jiných položkách. MemcachedStorage @@ -99,7 +125,9 @@ services: cache.storage: Nette\Caching\Storages\MemcachedStorage('10.0.0.5') ``` -Memcached neumí vypsat své klíče, takže úložiště mazání podle jmenných prostorů ignoruje. Pro závislost na jiných položkách vyhodí výjimku. Smazání celé cache vyprázdní celý server Memcached včetně dat jiných aplikací. +Memcached neumí vypsat své klíče, takže úložiště neumí mazat jmenné prostory. Nepodporuje ani závislost na jiných položkách. Smazání celé cache vyprázdní celý server Memcached včetně dat jiných aplikací. + +Když Memcached položku odmítne uložit, typicky takovou, která přesahuje jeho limit velikosti, úložiště vyvolá varování. SQLiteStorage @@ -115,7 +143,9 @@ services: cache.storage: Nette\Caching\Storages\SQLiteStorage('%tempDir%/cache.db') ``` -Úložiště podporuje expiraci, klouzavou expiraci a tagy. Priority, závislosti na souborech, konstantách, callbackech a jiných položkách i mazání podle jmenných prostorů potichu ignoruje. +Databáze běží v režimu WAL, ve kterém čtení nečeká na zápis. SQLite si pak vedle databáze zakládá další dva soubory, takže PHP musí mít právo zapisovat do jejího adresáře. + +Úložiště podporuje expiraci, klouzavou expiraci, tagy a mazání jmenných prostorů. Nepodporuje priority ani závislosti na souborech, konstantách, callbackech a jiných položkách. MemoryStorage @@ -123,7 +153,22 @@ MemoryStorage `Nette\Caching\Storages\MemoryStorage` drží data v PHP poli, takže se s koncem požadavku ztratí. Hodí se pro testy a pro cachování v rámci jednoho požadavku. -Ignoruje všechny závislosti včetně expirace a z podmínek metody `clean()` respektuje jen `Cache::All`. Myslete na to, když jím v testech nahrazujete skutečné úložiště: položka, která by tam vyexpirovala, tady zůstane. +Respektuje expiraci, klouzavou expiraci, tagy, priority a mazání jmenných prostorů. Závislosti na souborech, konstantách, callbackech a jiných položkách potichu ignoruje. Myslete na to, když jím v testech nahrazujete skutečné úložiště: položka, která by tam vyexpirovala, tady zůstane. + + +Psr16Storage +============ + +`Nette\Bridges\Psr\Psr16Storage` vám umožní použít jako úložiště pro Nette libovolnou [PSR-16 |https://www.php-fig.org/psr/psr-16/] cache, třeba cache jiného frameworku, který už vaše aplikace používá. Tagy a priority potřebují [journal |#journal]: + +```php +// $simpleCache je libovolná Psr\SimpleCache\CacheInterface +$storage = new Nette\Bridges\Psr\Psr16Storage($simpleCache, journal: $journal); +``` + +PSR-16 povoluje v klíčích jen některé znaky, proto úložiště každý klíč převede na hash. Před každý z nich přidá parametr `prefix`, nejvýš 32 písmen, číslic, podtržítek a teček. + +PSR-16 neumí prodloužit platnost položky ani vypsat klíče, takže úložiště nepodporuje klouzavou expiraci ani mazání jmenných prostorů. Nepodporuje ani závislost na jiných položkách. Smazání celé cache zavolá `clear()` na PSR-16 cache, takže smaže i data všech, kdo ji sdílejí, bez ohledu na prefix. DevNullStorage @@ -135,7 +180,7 @@ DevNullStorage Journal ======= -`FileStorage` a `MemcachedStorage` neumí své položky vyhledávat podle tagu nebo priority, proto si vedou samostatný index, tzv. journal. Vestavěný `Nette\Caching\Storages\SQLiteJournal` ho ukládá do databáze SQLite: +`FileStorage`, `MemcachedStorage` a `Psr16Storage` neumí své položky vyhledávat podle tagu nebo priority, proto si vedou samostatný index, tzv. journal. Vestavěný `Nette\Caching\Storages\SQLiteJournal` ho ukládá do databáze SQLite: ```php $journal = new Nette\Caching\Storages\SQLiteJournal('/path/to/temp/journal.s3db'); @@ -154,8 +199,8 @@ services: Bez journalu tato úložiště fungují také, jen uložení položky s tagy nebo prioritou vyhodí výjimku. -Úložiště jako PSR-16 cache .{data-version:3.3.1} -================================================ +Úložiště jako PSR-16 cache +========================== Některé knihovny očekávají [PSR-16 |https://www.php-fig.org/psr/psr-16/] cache. Adaptér `Nette\Bridges\Psr\PsrCacheAdapter` jim ji poskytne nad libovolným úložištěm z Nette: @@ -166,25 +211,26 @@ $psrCache->set('key', 'value', 3600); // uloží hodnotu na 1 hodinu $value = $psrCache->get('key', 'default'); ``` -Adaptér podporuje všechny metody PSR-16 včetně `getMultiple()`, `setMultiple()` a `deleteMultiple()`. +Adaptér podporuje všechny metody PSR-16 včetně `getMultiple()`, `setMultiple()` a `deleteMultiple()`. Jak PSR-16 vyžaduje, odmítne prázdný klíč i klíč obsahující některý ze znaků `{}()/\@:`, třeba `user:1`. + +Opačný směr, tedy PSR-16 cache použitou jako úložiště pro Nette, pokrývá [#Psr16Storage]. Vlastní úložiště ================ -Úložiště je třída, která implementuje rozhraní `Nette\Caching\Storage` (před verzí 3.1 se jmenovalo `Nette\Caching\IStorage`) s pěti metodami: +Úložiště je třída, která implementuje rozhraní `Nette\Caching\Storage` se čtyřmi metodami: -- `read(string $key)` vrátí uloženou hodnotu, nebo `null`, když položka neexistuje nebo vyexpirovala -- `lock(string $key): void` zamkne položku, než `Cache` spustí generátor; zámek uvolní `write()` nebo `remove()` a úložiště, které před cache stampede nechrání, nechá metodu prázdnou +- `read(string $key): mixed` vrátí uloženou hodnotu, nebo `null`, když položka neexistuje nebo vyexpirovala - `write(string $key, mixed $data, array $dependencies): void` hodnotu uloží - `remove(string $key): void` položku smaže - `clean(array $conditions): void` smaže položky podle podmínek metody [clean() |expiration#Mazání položek]; prázdné pole znamená odstranit vyexpirované položky Závislosti přicházejí jako pole s klíči `Cache::*`, které už `Cache` zjednodušila: expirace je počet sekund od teď, ze souborů a konstant se staly callbacky a jiné položky jsou dané svými klíči v úložišti. Při čtení položky ověřte její callbacky pomocí `Nette\Caching\Cache::checkCallbacks()`. Pro závislost nebo podmínku, kterou vaše úložiště neumí, vyhoďte `Nette\NotSupportedException`. -Další schopnosti přidávají volitelná rozhraní. `Nette\Caching\BulkReader` a od verze 3.3 i `Nette\Caching\BulkWriter` umožní úložišti číst a zapisovat více položek najednou. +Další schopnosti přidávají volitelná rozhraní. `Nette\Caching\BulkReader` a `Nette\Caching\BulkWriter` umožní úložišti číst a zapisovat více položek najednou. `Nette\Caching\LockingReader` přidává metodu `readOrGenerate()`, která chrání před cache stampede: dostane generátor z `load()` jako funkci a musí ji spustit pod zámkem. Funkce si výsledek uloží sama, pomocí `write()` nebo `remove()` téhož úložiště, takže tyto metody musí fungovat, i když je zámek držený. -Krátkým úplným příkladem je zdrojový kód [SQLiteStorage |https://github.com/nette/caching/blob/v3.4/src/Caching/Storages/SQLiteStorage.php]. +Krátkým úplným příkladem je zdrojový kód [SQLiteStorage |https://github.com/nette/caching/blob/master/src/Caching/Storages/SQLiteStorage.php]. -{{maintitle: Úložiště Nette Caching: soubory, Memcached, SQLite}} -{{description: Vyberte, kam cache z Nette ukládá data: soubory, Memcached nebo SQLite. Porovnejte, co které úložiště umí, a nastavte ho ve své aplikaci.}} +{{maintitle: Úložiště Nette Caching: soubory, Redis, Memcached, SQLite, PSR-16}} +{{description: Vyberte, kam cache z Nette ukládá data: soubory, Redis, Memcached, SQLite nebo libovolná PSR-16 cache. Porovnejte, co které umí, a nastavte ho.}} diff --git a/caching/cs/upgrading.texy b/caching/cs/upgrading.texy index 01f8e08f6f..34325e258c 100644 --- a/caching/cs/upgrading.texy +++ b/caching/cs/upgrading.texy @@ -2,6 +2,33 @@ Upgrade ******* +Upgrade na verzi 4.0 +==================== + +Minimální požadovaná verze PHP je 8.4. Značka `{cache}` vyžaduje Latte 3.1. + +.[tip] +Část práce za vás udělá [DressCode |tools:coding-standard#Novější PHP a Nette] s balíčkem `dresscode/upgrade-nette`: přepíše přejmenované třídy a konstanty a ohlásí, co přepsat nedokáže. Viz [Upgrade Nette |https://dresscode.run/cs/upgrading-nette]. + +Rozhraní `Nette\Caching\IStorage`, `Nette\Caching\IBulkReader` a `Nette\Caching\Storages\IJournal` byla odstraněna; použijte `Nette\Caching\Storage`, `Nette\Caching\BulkReader` a `Nette\Caching\Storages\Journal`. Odstraněny byly i aliasy služeb `cacheStorage` a `nette.cacheJournal`; použijte služby `cache.storage` a `cache.journal`, případně autowiring. + +Konstanty psané velkými písmeny, třeba `Cache::EXPIRE` nebo `Cache::TAGS`, a metoda `Cache::start()` nyní vyvolávají `E_USER_DEPRECATED`. Použijte `Cache::Expire`, `Cache::Tags` a `capture()`. Předávat closure jako data do `Cache::save()` je zastaralé, předejte ji jako generátor do `load()`. + +Závislosti lze zapsat novým objektem `Nette\Caching\Dependencies`, viz [Expirace a invalidace |expiration]. Pole s klíči `Cache::*` dál funguje, ale neznámý klíč nebo hodnota špatného typu nyní vyhodí výjimku. Typicky jde o prioritu zapsanou jako řetězec, třeba `'50'`, která musí být celé číslo. + +Metoda `Cache::clean()` přijímá podmínky jako pojmenované argumenty, třeba `$cache->clean(tags: ['article/10'])`; pole se kontroluje stejně jako závislosti. Několik věcí se chová jinak: + +- `clean()` bez jakékoliv podmínky vyhodí výjimku. Vyexpirované položky smažete voláním `clean([])` na úložišti. +- `all` u cache s jmenným prostorem smaže jen tento prostor a prostory z něj odvozené; dříve smazal celé úložiště. Pokud chcete smazat vše, zavolejte ho na cache bez jmenného prostoru, nebo zavolejte `$storage->clean([Cache::All => true])`. +- Mazání podle `Cache::Namespaces` smaže i prostory odvozené od uvedených pomocí `derive()`. + +Úložiště vyhodí `Nette\NotSupportedException` pro závislost nebo podmínku, kterou neumí, místo aby ji potichu ignorovalo. `SQLiteStorage` nepodporuje priority ani závislosti na souborech, konstantách, callbackech a jiných položkách; `MemcachedStorage` nepodporuje mazání podle jmenných prostorů. Viz přehled [úložišť |storages#Výběr úložiště]. + +`PsrCacheAdapter` nyní kontroluje klíče tak, jak vyžaduje PSR-16, takže odmítne klíče obsahující některý ze znaků `{}()/\@:`, třeba `user:1`. + +Pokud jste napsali vlastní úložiště, odstraňte metodu `lock()`, která už neexistuje, a deklarujte návratový typ `mixed` metody `read()`. Úložiště, které má chybějící položku nechat vygenerovat jen jednomu procesu, implementuje rozhraní `Nette\Caching\LockingReader`. Potomek `Cache`, který přepisuje `clean()`, musí deklarovat její nové parametry. + + Upgrade na verzi 3.1 ==================== @@ -20,4 +47,4 @@ Upgrade na verzi 2.3 - prastará a zastaralá ArrayAccess syntaxe `$val = $cache[$key]` nebo `$cache[$key] = $val` vyvolá `E_USER_DEPRECATED`; použijte místo ní `$cache->load($key)` a `$cache->save($key, $val)` {{maintitle: Upgrade Nette Caching: změny v jednotlivých verzích}} -{{description: Co se změnilo v Nette Caching 3.1, 2.4 a 2.3 a jak upravit kód při přechodu na novější verzi.}} +{{description: Co se změnilo v Nette Caching 4.0, 3.1 a starších verzích a jak upravit kód při přechodu na novější verzi.}} diff --git a/caching/en/@home.texy b/caching/en/@home.texy index 624a481ff2..844684113b 100644 --- a/caching/en/@home.texy +++ b/caching/en/@home.texy @@ -9,7 +9,7 @@ Does your application compute the same thing over and over, such as turning an a - Data expires after a while, or when a file, another item or your own condition changes - Tags delete exactly the items related to the article you just edited - A crowd of requests for a missing item does not overload the server -- Stores data in files, Memcached or SQLite +- Stores data in files, Redis, Memcached, SQLite or any PSR-16 cache - Caches parts of Latte templates @@ -24,6 +24,8 @@ Download and install the package using [Composer|best-practices:composer]: composer require nette/caching ``` +It requires PHP version 8.4 and supports PHP up to 8.6. + Your First Cache ================ @@ -74,13 +76,15 @@ How Long Is the Data Valid? Our cached article now never changes. But what if you fix a typo in it? Visitors would keep seeing the old version. You need to tell the cache when an item stops being valid. The simplest way is a time limit: ```php -$html = $cache->load("article/$id", function (&$dependencies) use ($id) { - $dependencies[Cache::Expire] = '1 hour'; +use Nette\Caching\Dependencies; + +$html = $cache->load("article/$id", function (Dependencies $dp) use ($id) { + $dp->expire = '1 hour'; return renderArticle($id); }); ``` -The generator now takes the parameter `$dependencies` by reference. It is an array into which the generator writes when the item expires. It is called dependencies because the validity of the item depends on them. Here it is one hour. +The generator now takes a parameter of the type `Dependencies`, and `load()` passes it an object in which the generator describes when the item expires. It is called dependencies because the validity of the item depends on them. Here it is one hour. Time is just one option. An item can also expire when a file changes, when another item in the cache changes, or when your own condition says so. All of that is described on the page [Expiration and Invalidation |expiration]. @@ -91,8 +95,8 @@ Deleting Exactly What Changed A time limit is a compromise: set it short, and the cache helps little; set it long, and visitors see stale data. It is better to delete the article from the cache exactly when you edit it. That is what **tags** are for. You attach them to an item as arbitrary strings: ```php -$html = $cache->load("article/$id", function (&$dependencies) use ($id) { - $dependencies[Cache::Tags] = ["article/$id", "comments/$id"]; +$html = $cache->load("article/$id", function (Dependencies $dp) use ($id) { + $dp->tags = ["article/$id", "comments/$id"]; return renderArticle($id); }); ``` @@ -100,7 +104,7 @@ $html = $cache->load("article/$id", function (&$dependencies) use ($id) { The page shows the article together with its comments, so we gave it two tags. Then, in the administration, right after you save the edited article to the database, you delete everything tagged with it: ```php -$cache->clean([Cache::Tags => ["article/$id"]]); +$cache->clean(tags: ["article/$id"]); ``` And the same when someone adds a comment, this time with the tag `comments/$id`. From now on, the cached page disappears exactly when its article or its comments change, and the next visitor gets a freshly rendered one. @@ -126,13 +130,13 @@ We already met the namespace `'articles'` in the constructor of the cache. Each $commentCache = new Cache($storage, 'comments'); ``` -The method `derive()` creates a cache in a nested namespace: `$cache->derive('previews')` gives the namespace `previews` inside `articles`. And when you want to throw away everything in a namespace, call: +The method `derive()` creates a cache in a nested namespace: `$cache->derive('previews')` gives the namespace `previews` inside `articles`. And when you want to throw away everything in a namespace, including the nested ones, call: ```php -$cache->clean([Cache::Namespaces => ['articles']]); +$cache->clean(all: true); ``` -Other namespaces, the nested ones included, stay untouched. Cleaning by namespace works with `FileStorage`; other storages ignore it. Be careful with `Cache::All`, which deletes the entire storage, all namespaces included. +Other namespaces stay untouched. Only a cache created without a namespace, `new Cache($storage)`, deletes the entire storage this way. Memoization @@ -166,7 +170,7 @@ if ($capture = $cache->capture('sidebar')) { } ``` -When the output is already cached, `capture()` prints it and returns `null`, so the block inside `if` does not run at all. Otherwise it starts capturing the output and returns an object whose method `end()` stores everything printed in the meantime. You can pass it dependencies, for example `$capture->end([Cache::Tags => ['articles']])`. In version 3.0, the method `capture()` was named `start()`. +When the output is already cached, `capture()` prints it and returns `null`, so the block inside `if` does not run at all. Otherwise it starts capturing the output and returns an object whose method `end()` stores everything printed in the meantime. You can pass it dependencies, for example `$capture->end(new Dependencies(tags: ['articles']))`. Caching in Latte @@ -201,9 +205,11 @@ So far, we have used `FileStorage`, which needs nothing but a directory. Thanks | Storage | Where the data lives |---------------------- | `FileStorage` | in files on disk; the default storage +| `RedisStorage` | on a Redis server | `MemcachedStorage` | on a Memcached server | `SQLiteStorage` | in an SQLite database file | `MemoryStorage` | in memory, only until the request ends +| `Psr16Storage` | in any PSR-16 cache | `DevNullStorage` | nowhere; for tests and for turning the cache off You can switch the storage without touching the code that uses the cache. Which one to choose, what each supports and how to configure it, including turning the cache off, is described on the page [Storages |storages]. @@ -212,7 +218,7 @@ You can switch the storage without touching the code that uses the cache. Which Cache in a Nette Application ============================ -In a Nette application, you do not create the storage yourself. Nette provides a `FileStorage` that stores data in the `cache` subdirectory of the directory for [temporary files |application:bootstrapping#Temporary Files], together with a journal. You get it via [dependency injection |dependency-injection:passing-dependencies] by asking for the type `Nette\Caching\Storage` (before version 3.1 named `Nette\Caching\IStorage`), and create your cache in the constructor: +In a Nette application, you do not create the storage yourself. Nette provides a `FileStorage` that stores data in the `cache` subdirectory of the directory for [temporary files |application:bootstrapping#Temporary Files], together with a journal. You get it via [dependency injection |dependency-injection:passing-dependencies] by asking for the type `Nette\Caching\Storage`, and create your cache in the constructor: ```php use Nette\Caching\Cache; @@ -245,8 +251,8 @@ What's Next =========== - [Expiration and Invalidation |expiration] - every way to tell the cache when data expires, deleting by tags, priority and namespace -- [Storages |storages] - choosing and configuring a storage, PSR-16, writing your own storage -- [Upgrading |upgrading] - what changed in each version +- [Storages |storages] - choosing and configuring a storage, PSR-16 in both directions, writing your own storage +- [Upgrading |upgrading] - what changed in version 4.0 {{maintitle: PHP Caching with Nette: Storages, Expiration, Invalidation}} {{description: Speed up your application by storing expensive results for later. Use the Nette cache in PHP and Latte, change storages and invalidate data correctly.}} diff --git a/caching/en/expiration.texy b/caching/en/expiration.texy index 8fa91c6a65..65faf35e11 100644 --- a/caching/en/expiration.texy +++ b/caching/en/expiration.texy @@ -18,48 +18,48 @@ The examples continue the blog from the [overview |@home]: `$cache` is a cache i Setting Dependencies ==================== -**Dependencies** describe when an item expires. They are an array with `Cache::*` keys. The most convenient way is to let the generator fill it in. Declare its parameter as a reference, `&$dependencies`, and `load()` passes it an empty array: +**Dependencies** describe when an item expires. They are an object `Nette\Caching\Dependencies`. The most convenient way is to let the generator fill it in. Declare its parameter with the type `Dependencies`, and `load()` passes it an empty object: ```php -use Nette\Caching\Cache; +use Nette\Caching\Dependencies; -$html = $cache->load("article/$id", function (&$dependencies) use ($id) { - $dependencies[Cache::Expire] = '1 hour'; +$html = $cache->load("article/$id", function (Dependencies $dp) use ($id) { + $dp->expire = '1 hour'; return renderArticle($id); }); ``` The advantage is that the generator can decide based on what it computed. An article that is still being drafted can expire sooner than a published one, for example. -When the dependencies are known in advance, you can pass them as the third argument of `load()` instead, or of `save()`, which stores a value directly without a generator: +When the dependencies are known in advance, you can pass them as the third argument of `load()` instead, or of `save()`, which stores a value directly without a generator. The constructor takes all the properties as named arguments: ```php -$html = $cache->load("article/$id", fn() => renderArticle($id), [Cache::Expire => '1 hour']); +$html = $cache->load("article/$id", fn() => renderArticle($id), new Dependencies(expire: '1 hour')); -$cache->save("article/$id", $html, [Cache::Expire => '1 hour', Cache::Tags => ["article/$id"]]); +$cache->save("article/$id", $html, new Dependencies(expire: '1 hour', tags: ["article/$id"])); ``` -Prefer `load()` with a generator to `save()`. When several requests ask for a missing item at once, `FileStorage` lets only one of them run the generator; with `save()`, they would all compute the value. +Prefer `load()` with a generator to `save()`. When several requests ask for a missing item at once, `FileStorage` and `RedisStorage` let only one of them run the generator; with `save()`, they would all compute the value. -Before version 3.1.3, the constants were written in uppercase, such as `Cache::EXPIRE` instead of `Cache::Expire`. Keep in mind that the array is not checked: a key with a typo, such as `'expir'`, is silently ignored. +Dependencies can also be written as an array with `Cache::*` keys, such as `[Cache::Expire => '1 hour', Cache::Tags => ["article/$id"]]`. A generator whose parameter is not typed `Dependencies` receives this array by reference and adds to it: `function (&$dependencies)`. An unknown key or a value of a wrong type in the array throws an exception, so a typo such as `'expir'` does not silently leave the item without expiration. Expiration by Time ================== -The key `Cache::Expire` sets when the item expires. It accepts a relative time as a string, a number of seconds, a UNIX timestamp or a `DateTimeInterface` object: +The property `expire` sets when the item expires. It accepts a relative time as a string, a number of seconds, a UNIX timestamp or a `DateTimeInterface` object: ```php -$dependencies[Cache::Expire] = '20 minutes'; -$dependencies[Cache::Expire] = 3600; // one hour -$dependencies[Cache::Expire] = new DateTimeImmutable('tomorrow'); +$dp->expire = '20 minutes'; +$dp->expire = 3600; // one hour +$dp->expire = new DateTimeImmutable('tomorrow'); ``` With **sliding expiration**, every read moves the expiration further. An article that visitors keep reading then stays in the cache, while one nobody opens for 20 minutes is dropped: ```php -$dependencies[Cache::Expire] = '20 minutes'; -$dependencies[Cache::Sliding] = true; +$dp->expire = '20 minutes'; +$dp->sliding = true; ``` Keep in mind that every read then also updates the item in the storage, which adds some overhead. @@ -71,13 +71,13 @@ When a File Changes Data computed from a file should expire when the file changes. Let's say the blog reads its list of categories from the file `categories.neon`. The cached list then depends on that file: ```php -$categories = $cache->load('categories', function (&$dependencies) { - $dependencies[Cache::Files] = __DIR__ . '/categories.neon'; +$categories = $cache->load('categories', function (Dependencies $dp) { + $dp->files[] = __DIR__ . '/categories.neon'; return loadCategories(); // reads and processes categories.neon }); ``` -As soon as you edit `categories.neon`, the cache notices on the next read and calls the generator again. Use absolute paths. An item can depend on several files: `$dependencies[Cache::Files] = [$file1, $file2]`. +As soon as you edit `categories.neon`, the cache notices on the next read and calls the generator again. Use absolute paths. An item can depend on several files: `$dp->files = [$file1, $file2]`. When a Constant Changes @@ -86,7 +86,7 @@ When a Constant Changes Similarly, an item can expire when the value of a PHP constant changes. That is handy for a version number you set at deployment, for example, so that every new version starts with a fresh cache: ```php -$dependencies[Cache::Constants] = 'APP_VERSION'; +$dp->constants[] = 'APP_VERSION'; ``` @@ -96,8 +96,8 @@ When Another Item Changes An item can depend on other items in the cache. Let's say the article and its comments are cached separately, under the keys `article/$id` and `comments/$id`, and the whole page put together from them is cached as well. The page must expire whenever one of its parts does: ```php -$page = $cache->load("page/$id", function (&$dependencies) use ($id) { - $dependencies[Cache::Items] = ["article/$id", "comments/$id"]; +$page = $cache->load("page/$id", function (Dependencies $dp) use ($id) { + $dp->items = ["article/$id", "comments/$id"]; return renderPage($id); // puts together the article and its comments }); ``` @@ -116,7 +116,7 @@ function checkPhpVersion(int $version): bool return $version === PHP_VERSION_ID; } -$dependencies[Cache::Callbacks] = [['checkPhpVersion', PHP_VERSION_ID]]; +$dp->callbacks[] = ['checkPhpVersion', PHP_VERSION_ID]; ``` Each entry is an array: the function, or a static method written as `[ClassName::class, 'method']`, followed by its arguments. The function is called on every read, so it should be fast. @@ -128,9 +128,9 @@ Combining Conditions All these conditions can be combined. The item expires as soon as at least one of them is no longer met: ```php -$dependencies[Cache::Expire] = '1 day'; -$dependencies[Cache::Files] = __DIR__ . '/categories.neon'; -$dependencies[Cache::Constants] = 'APP_VERSION'; +$dp->expire = '1 day'; +$dp->files[] = __DIR__ . '/categories.neon'; +$dp->constants[] = 'APP_VERSION'; ``` @@ -140,8 +140,8 @@ Tags Waiting for expiration is a compromise. It is better to delete an item exactly when the data it was made from changes. **Tags** let you do that. They are arbitrary strings you attach to an item: ```php -$html = $cache->load("article/$id", function (&$dependencies) use ($id) { - $dependencies[Cache::Tags] = ["article/$id", "comments/$id"]; +$html = $cache->load("article/$id", function (Dependencies $dp) use ($id) { + $dp->tags = ["article/$id", "comments/$id"]; return renderArticle($id); }); ``` @@ -149,15 +149,15 @@ $html = $cache->load("article/$id", function (&$dependencies) use ($id) { In the administration, right after saving an edited article to the database, you delete everything tagged with it: ```php -$cache->clean([Cache::Tags => ["article/$id"]]); +$cache->clean(tags: ["article/$id"]); ``` The same goes for adding a comment, this time with the tag `comments/$id`. Notice that the code deleting the items does not need to know their keys, or even how many there are. The article may sit in the cache as a whole page, as a preview on the homepage and in the RSS feed; one call removes them all. -Tags work across namespaces: `clean([Cache::Tags => [...]])` deletes the matching items in every namespace of the storage, not just in the namespace of `$cache`. +Tags work across namespaces: `clean(tags: [...])` deletes the matching items in every namespace of the storage, not just in the namespace of `$cache`. .[note] -`FileStorage` and `MemcachedStorage` need a [journal |storages#Journal] for tags, `SQLiteStorage` keeps them itself and `MemoryStorage` ignores them. +`FileStorage`, `MemcachedStorage` and `Psr16Storage` need a [journal |storages#Journal] for tags; the other storages keep them themselves. Priority @@ -166,44 +166,44 @@ Priority Each item can be given a priority, a number saying how important it is. When the cache grows too big, you can then delete the less important items first. Let's say previews of old articles are less valuable than the homepage: ```php -$dependencies[Cache::Priority] = 10; +$dp->priority = 10; ``` This deletes every item with a priority of 50 or less: ```php -$cache->clean([Cache::Priority => 50]); +$cache->clean(priority: 50); ``` Items without a priority are never deleted this way. .[note] -`FileStorage` and `MemcachedStorage` need a [journal |storages#Journal] for priorities; `SQLiteStorage` and `MemoryStorage` ignore them. +`FileStorage`, `MemcachedStorage` and `Psr16Storage` need a [journal |storages#Journal] for priorities, `RedisStorage` and `MemoryStorage` keep them themselves, and `SQLiteStorage` does not support them. Deleting Items ============== -The method `clean()` deletes items by conditions, which you pass as an array with `Cache::*` keys: +The method `clean()` deletes items by conditions, which you pass as named arguments: -| Key | Deletes +| Argument | Deletes |---------------------- -| `Cache::Tags => [...]` | items with any of the tags -| `Cache::Priority => 50` | items with a priority of 50 or less -| `Cache::Namespaces => [...]` | all items in the listed namespaces; only `FileStorage` supports it -| `Cache::All => true` | everything in the storage, all namespaces included +| `tags: [...]` | items with any of the tags +| `priority: 50` | items with a priority of 50 or less +| `namespaces: [...]` | all items in the listed namespaces, including the namespaces derived from them +| `all: true` | everything in the namespace of this cache, including the namespaces derived from it The conditions can be combined, and an item matching any of them is deleted: ```php -$cache->clean([Cache::Tags => ["article/$id"], Cache::Priority => 50]); +$cache->clean(tags: ["article/$id"], priority: 50); ``` -Let's take a closer look at `Cache::All`. It deletes the entire storage, the items of all namespaces included, even when you call it on a cache with a namespace. To delete just one namespace, use `Cache::Namespaces`; the namespaces created from it by `derive()` stay. +Let's take a closer look at `all`. It deletes the whole namespace of the cache together with the namespaces created from it by `derive()`, and leaves other namespaces untouched. Only a cache created without a namespace, `new Cache($storage)`, deletes the entire storage this way. -The array is not checked, so a key with a typo is silently ignored and nothing is deleted. +The conditions can also be written as an array with `Cache::*` keys, such as `$cache->clean([Cache::Tags => ["article/$id"]])`. Just like with dependencies, an unknown key or a value of a wrong type throws an exception. -Removing items that have already expired is a matter of the storage: call `$storage->clean([])`. `FileStorage` and `SQLiteStorage` also do it on their own now and then, see [Storages |storages]. +Calling `clean()` without any condition throws an exception too, because it is not clear what it should delete. Removing items that have already expired is a matter of the storage: call `$storage->clean([])`. Most storages do it on their own anyway, see [Storages |storages]. To delete a single item, use `$cache->remove("article/$id")`. @@ -211,7 +211,7 @@ To delete a single item, use `$cache->remove("article/$id")`. What Each Storage Supports ========================== -Not every storage can honor every kind of dependency, and most of them silently ignore what they cannot do. `SQLiteStorage`, for example, ignores priorities and dependencies on files, so such an item simply does not expire that way, and `MemoryStorage` ignores all dependencies. Before relying on a dependency, check the table on the page [Storages |storages#Choosing a Storage]. +Not every storage can honor every kind of dependency. A storage that cannot honor one throws `Nette\NotSupportedException` instead of silently ignoring it, so you find out right away, not from stale data. `SQLiteStorage`, for example, does not support priorities or dependencies on files. The only exception is `MemoryStorage`, which ignores what it cannot do. The complete overview is in the table on the page [Storages |storages#Choosing a Storage]. Bulk Reading and Writing @@ -220,21 +220,21 @@ Bulk Reading and Writing The homepage of the blog shows previews of ten articles. Reading them from the cache one by one means ten round trips to the storage. The method `bulkLoad()` reads them all at once: you pass it the array `$ids` with their IDs as keys, and it returns an array of values indexed by those keys: ```php -$previews = $cache->bulkLoad($ids, function ($id, &$dependencies) { - $dependencies[Cache::Tags] = ["article/$id"]; +$previews = $cache->bulkLoad($ids, function ($id, Dependencies $dp) { + $dp->tags = ["article/$id"]; return renderPreview($id); // renders a short preview of the article }); ``` The generator is called only for the previews that are missing, and it receives the key followed by the dependencies. Without a generator, `bulkLoad($ids)` returns `null` for the missing items. -The method `bulkSave()` stores several items at once, all with the same dependencies: .{data-version:3.3.0} +The method `bulkSave()` stores several items at once, all with the same dependencies: ```php $cache->bulkSave([ "preview/$id1" => $preview1, "preview/$id2" => $preview2, -], [Cache::Expire => '1 hour']); +], new Dependencies(expire: '1 hour')); ``` {{maintitle: Nette Caching: Expiration, Tags and Cache Invalidation}} diff --git a/caching/en/storages.texy b/caching/en/storages.texy index b5fa2f06bf..a9ad5cc3ab 100644 --- a/caching/en/storages.texy +++ b/caching/en/storages.texy @@ -3,11 +3,11 @@ Storages
-The storage decides where cached data physically lives: in files on disk, on a Memcached server or in an SQLite database. You can switch it without touching the code that uses the cache. This page helps you: +The storage decides where cached data physically lives: in files on disk, on a Redis or Memcached server, in an SQLite database or in the PSR-16 cache of another framework. You can switch it without touching the code that uses the cache. This page helps you: - choose the right storage and see what each one supports - configure it in a Nette application, or turn the cache off -- use a Nette storage as a PSR-16 cache +- use a Nette storage as a PSR-16 cache, and the other way round - write a storage of your own
@@ -18,7 +18,7 @@ Choosing a Storage If you are not sure, keep the default `FileStorage`. It needs nothing but a directory, it is safe when many requests read and write at once, and it supports every kind of dependency. -When your application runs on several servers, `FileStorage` gives each of them its own cache. `MemcachedStorage` stores the data on a server shared by all of them, but it keeps tags and priorities in a [#journal], a file local to each server, so deleting by tag on one server does not reach the others. +Reach for `RedisStorage` when your application runs on several servers. With files, each server would have its own cache, and deleting an article by its tag on one server would leave the stale copies on the others. A Redis server is shared by all of them. The storages differ in which [dependencies |expiration] they can honor: @@ -26,12 +26,14 @@ The storages differ in which [dependencies |expiration] they can honor: | Storage | Tags, priorities | Files, constants, callbacks | Other items | Sliding | Cleaning namespaces | Stampede protection |------------------------------------------------------------------------------------------------- | [#FileStorage] | with [#journal] | yes | yes | yes | yes | yes -| [#MemcachedStorage] | with [#journal] | yes | no | yes | ignored | no -| [#SQLiteStorage] | tags only | ignored | ignored | yes | ignored | no -| [#MemoryStorage] | ignored | ignored | ignored | ignored | ignored | no +| [#RedisStorage] | yes | yes | no | yes | yes | yes +| [#MemcachedStorage] | with [#journal] | yes | no | yes | no | no +| [#SQLiteStorage] | tags only | no | no | yes | yes | no +| [#MemoryStorage] | yes | ignored | ignored | yes | yes | no +| [#Psr16Storage] | with [#journal] | yes | no | no | no | no | [#DevNullStorage] | stores nothing | | | | | -Where the table says ignored, the storage silently drops the dependency, so the item just does not expire that way. `MemoryStorage` ignores even the expiration. Only `MemcachedStorage` throws `Nette\NotSupportedException`, for the dependency on other items. +A storage that cannot honor a dependency throws `Nette\NotSupportedException` instead of silently ignoring it, so you find out right away, not from stale data. The only exception is `MemoryStorage`, which ignores what it cannot do. Stampede protection means that when many requests ask for a missing item at once, only the first one runs the generator of `load()` and the others wait for its result. Without it, all of them compute the value at the same time. @@ -45,7 +47,7 @@ To use another storage, replace the service `cache.storage` in the configuration ```neon services: - cache.storage: Nette\Caching\Storages\MemcachedStorage('10.0.0.5') + cache.storage: Nette\Caching\Storages\RedisStorage('10.0.0.5') ``` The container holds these two services: @@ -83,7 +85,31 @@ All operations are atomic. You can never read a file another request has not fin It also protects against the [cache stampede |https://en.wikipedia.org/wiki/Cache_stampede]. When many requests ask for a missing item at once, for example right after a deployment, the first one locks the file and runs the generator. The others wait for the lock and then read the fresh value instead of computing it again. -Expired files are removed now and then by the constructor. To remove them at a moment of your choosing, call `$storage->clean([])`. +Expired files are removed gradually. Now and then, the constructor spends at most 20 ms deleting them, so even a large cache does not noticeably slow down a request. To remove all expired files at once, call `$storage->clean([])`. + +Data is stored with PHP's `serialize()`. If you prefer another format, create a subclass and override the methods `serializeData()` and `unserializeData()`. + + +RedisStorage +============ + +`Nette\Caching\Storages\RedisStorage` stores data on a [Redis |https://redis.io] server. It keeps tags and priorities itself, so it needs no journal, and it protects against the cache stampede just like `FileStorage`. + +.[caution] +Requires the `redis` PHP extension. + +```neon +services: + cache.storage: Nette\Caching\Storages\RedisStorage('10.0.0.5') +``` + +The constructor takes the host and the port, 6379 by default. If you already have a connected `Redis` object, pass it instead of the host. + +All keys get the prefix `nette.cache:`, so the database can be shared with other data; the parameter `prefix` changes it. An empty prefix means that the whole database belongs to the cache, and clearing the cache then empties the database. + +While one process generates a missing item, the others wait for it, at most for 30 seconds by default (the parameter `lockTimeout`). A generator that takes longer only means that another process computes the same value too, never that a wrong value is stored. + +The storage does not support the dependency on other items. MemcachedStorage @@ -99,7 +125,9 @@ services: cache.storage: Nette\Caching\Storages\MemcachedStorage('10.0.0.5') ``` -Memcached cannot list its keys, so the storage ignores cleaning by namespaces. For the dependency on other items, it throws an exception. Clearing the whole cache empties the entire Memcached server, including the data of other applications. +Memcached cannot list its keys, so the storage cannot clean namespaces. It does not support the dependency on other items either. Clearing the whole cache empties the entire Memcached server, including the data of other applications. + +When Memcached refuses to store an item, typically one larger than its size limit, the storage triggers a warning. SQLiteStorage @@ -115,7 +143,9 @@ services: cache.storage: Nette\Caching\Storages\SQLiteStorage('%tempDir%/cache.db') ``` -The storage supports expiration, sliding expiration and tags. Priorities, dependencies on files, constants, callbacks and other items, and cleaning by namespaces are silently ignored. +The database runs in the WAL mode, in which reading does not wait for writing. SQLite then creates two more files next to the database, so PHP must be able to write to its directory. + +The storage supports expiration, sliding expiration, tags and cleaning namespaces. It does not support priorities, nor dependencies on files, constants, callbacks and other items. MemoryStorage @@ -123,7 +153,22 @@ MemoryStorage `Nette\Caching\Storages\MemoryStorage` keeps data in a PHP array, so it is lost when the request ends. It is handy in tests and for caching within a single request. -It ignores all dependencies, expiration included, and of the conditions of `clean()` it honors only `Cache::All`. Keep that in mind when you use it in tests instead of a real storage: an item that would expire there stays here. +It honors expiration, sliding expiration, tags, priorities and cleaning namespaces. Dependencies on files, constants, callbacks and other items are silently ignored. Keep that in mind when you use it in tests instead of a real storage: an item that would expire there stays here. + + +Psr16Storage +============ + +`Nette\Bridges\Psr\Psr16Storage` lets you use any [PSR-16 |https://www.php-fig.org/psr/psr-16/] cache as a Nette storage, for example the cache of another framework your application already uses. Tags and priorities need a [#journal]: + +```php +// $simpleCache is any Psr\SimpleCache\CacheInterface +$storage = new Nette\Bridges\Psr\Psr16Storage($simpleCache, journal: $journal); +``` + +PSR-16 allows only some characters in keys, so the storage turns every key into a hash. The parameter `prefix`, at most 32 letters, digits, underscores and dots, is put in front of each of them. + +PSR-16 can neither extend the validity of an item nor list keys, so the storage does not support sliding expiration and cleaning namespaces. It does not support the dependency on other items either. Clearing the whole cache calls `clear()` on the PSR-16 cache, so it also removes the data of anyone else sharing it, whatever the prefix. DevNullStorage @@ -135,7 +180,7 @@ DevNullStorage Journal ======= -`FileStorage` and `MemcachedStorage` cannot search their items by tag or priority, so they keep a separate index, the so-called journal. The built-in `Nette\Caching\Storages\SQLiteJournal` stores it in an SQLite database: +`FileStorage`, `MemcachedStorage` and `Psr16Storage` cannot search their items by tag or priority, so they keep a separate index, the so-called journal. The built-in `Nette\Caching\Storages\SQLiteJournal` stores it in an SQLite database: ```php $journal = new Nette\Caching\Storages\SQLiteJournal('/path/to/temp/journal.s3db'); @@ -154,8 +199,8 @@ services: Without a journal, these storages work too, but storing an item with tags or a priority throws an exception. -Using a Storage as a PSR-16 Cache .{data-version:3.3.1} -======================================================= +Using a Storage as a PSR-16 Cache +================================= Some libraries expect a [PSR-16 |https://www.php-fig.org/psr/psr-16/] cache. The adapter `Nette\Bridges\Psr\PsrCacheAdapter` gives them one on top of any Nette storage: @@ -166,25 +211,26 @@ $psrCache->set('key', 'value', 3600); // stores the value for 1 hour $value = $psrCache->get('key', 'default'); ``` -The adapter supports all methods of PSR-16, including `getMultiple()`, `setMultiple()` and `deleteMultiple()`. +The adapter supports all methods of PSR-16, including `getMultiple()`, `setMultiple()` and `deleteMultiple()`. As PSR-16 requires, it rejects an empty key and a key containing any of the characters `{}()/\@:`, such as `user:1`. + +The opposite direction, a PSR-16 cache used as a Nette storage, is covered by [#Psr16Storage]. Writing Your Own Storage ======================== -A storage is a class implementing the interface `Nette\Caching\Storage` (before version 3.1 named `Nette\Caching\IStorage`) with five methods: +A storage is a class implementing the interface `Nette\Caching\Storage` with four methods: -- `read(string $key)` returns the stored value, or `null` when the item does not exist or has expired -- `lock(string $key): void` locks the item before `Cache` runs a generator; the lock is released by `write()` or `remove()`, and a storage that does not protect against the cache stampede leaves the method empty +- `read(string $key): mixed` returns the stored value, or `null` when the item does not exist or has expired - `write(string $key, mixed $data, array $dependencies): void` stores the value - `remove(string $key): void` deletes the item - `clean(array $conditions): void` deletes items by the conditions of [clean() |expiration#Deleting Items]; an empty array means removing the expired items The dependencies arrive as an array with `Cache::*` keys, already simplified by `Cache`: the expiration is a number of seconds from now, files and constants have become callbacks, and other items are given by their storage keys. When reading an item, check its callbacks with `Nette\Caching\Cache::checkCallbacks()`. Throw `Nette\NotSupportedException` for a dependency or condition your storage cannot honor. -Optional interfaces add more. `Nette\Caching\BulkReader` and, since version 3.3, `Nette\Caching\BulkWriter` let the storage read and write several items in one round trip. +Optional interfaces add more. `Nette\Caching\BulkReader` and `Nette\Caching\BulkWriter` let the storage read and write several items in one round trip. `Nette\Caching\LockingReader` adds the method `readOrGenerate()`, which protects against the cache stampede: it gets the generator of `load()` as a function and has to run it under a lock. The function stores the result itself, through `write()` or `remove()` of the same storage, so these methods must work while the lock is held. -A short complete example is the source code of [SQLiteStorage |https://github.com/nette/caching/blob/v3.4/src/Caching/Storages/SQLiteStorage.php]. +A short complete example is the source code of [SQLiteStorage |https://github.com/nette/caching/blob/master/src/Caching/Storages/SQLiteStorage.php]. -{{maintitle: Nette Caching Storages: Files, Memcached, SQLite}} -{{description: Choose where the Nette cache stores data: files, Memcached or SQLite. Compare what each storage supports and configure it in your application.}} +{{maintitle: Nette Caching Storages: Files, Redis, Memcached, SQLite, PSR-16}} +{{description: Choose where the Nette cache stores data: files, Redis, Memcached, SQLite or any PSR-16 cache. Compare what each supports and configure it.}} diff --git a/caching/en/upgrading.texy b/caching/en/upgrading.texy index 724705f192..274d819ada 100644 --- a/caching/en/upgrading.texy +++ b/caching/en/upgrading.texy @@ -2,6 +2,33 @@ Upgrading ********* +Upgrading to Version 4.0 +======================== + +The minimum required PHP version is 8.4. The `{cache}` tag requires Latte 3.1. + +.[tip] +A part of the work can be done for you by [DressCode |tools:coding-standard#Newer PHP and Nette] with the `dresscode/upgrade-nette` package: it rewrites renamed classes and constants and reports what it cannot rewrite. See [Upgrading Nette |https://dresscode.run/en/upgrading-nette]. + +The interfaces `Nette\Caching\IStorage`, `Nette\Caching\IBulkReader` and `Nette\Caching\Storages\IJournal` have been removed; use `Nette\Caching\Storage`, `Nette\Caching\BulkReader` and `Nette\Caching\Storages\Journal`. The service aliases `cacheStorage` and `nette.cacheJournal` have been removed as well; use the services `cache.storage` and `cache.journal`, or autowiring. + +The uppercase constants such as `Cache::EXPIRE` or `Cache::TAGS` and the method `Cache::start()` now trigger `E_USER_DEPRECATED`. Use `Cache::Expire`, `Cache::Tags` and `capture()`. Passing a closure as the data to `Cache::save()` is deprecated, pass it as the generator of `load()`. + +Dependencies can be written as the new object `Nette\Caching\Dependencies`, see [Expiration and Invalidation |expiration]. The array with `Cache::*` keys still works, but an unknown key or a value of a wrong type now throws an exception. Typically, this concerns a priority written as a string, such as `'50'`, which has to be an integer. + +The method `Cache::clean()` takes the conditions as named arguments, such as `$cache->clean(tags: ['article/10'])`; the array is validated the same way as the dependencies. Several things behave differently: + +- `clean()` without any condition throws an exception. To remove expired items, call `clean([])` on the storage. +- `all` on a cache with a namespace removes only that namespace and those derived from it; previously, it cleared the whole storage. To clear everything, call it on a cache without a namespace, or call `$storage->clean([Cache::All => true])`. +- Cleaning by `Cache::Namespaces` also removes the namespaces derived from the given ones by `derive()`. + +A storage throws `Nette\NotSupportedException` for a dependency or a condition it cannot honor, instead of silently ignoring it. `SQLiteStorage` does not support priorities or dependencies on files, constants, callbacks and other items; `MemcachedStorage` does not support cleaning by namespaces. See the overview of [storages |storages#Choosing a Storage]. + +`PsrCacheAdapter` now validates keys as PSR-16 requires, so it rejects keys containing any of `{}()/\@:`, such as `user:1`. + +If you have written your own storage, remove the method `lock()`, which no longer exists, and declare the return type `mixed` of the method `read()`. A storage that should let only one process generate a missing item implements the interface `Nette\Caching\LockingReader`. A subclass of `Cache` that overrides `clean()` must declare its new parameters. + + Upgrading to Version 3.1 ======================== @@ -20,4 +47,4 @@ Upgrading to Version 2.3 - the ancient and deprecated ArrayAccess syntax `$val = $cache[$key]` or `$cache[$key] = $val` triggers `E_USER_DEPRECATED`; use `$cache->load($key)` and `$cache->save($key, $val)` instead {{maintitle: Upgrading Nette Caching: What Changed in Each Version}} -{{description: What changed in Nette Caching 3.1, 2.4 and 2.3, and how to update your code when moving to a newer version.}} +{{description: What changed in Nette Caching 4.0, 3.1 and older versions, and how to update your code when moving to a newer version.}} diff --git a/caching/meta.json b/caching/meta.json index 00b14c1a59..ae86ba6a38 100644 --- a/caching/meta.json +++ b/caching/meta.json @@ -1,5 +1,5 @@ { - "version": "3.x", + "version": "4.x", "repo": "nette/caching", "composer": "nette/caching", "api": "https://api.nette.org/caching/" From 414b5167659e313cb48347a368516bdbd470757f Mon Sep 17 00:00:00 2001 From: David Grudl Date: Sat, 7 Nov 2026 15:28:42 +0100 Subject: [PATCH 5/7] schema: split into an overview and reference pages on types, validation, merging, JSON Schema and custom elements --- schema/cs/@home.texy | 813 ++++----------------------------- schema/cs/@left-menu.texy | 5 + schema/cs/custom-elements.texy | 111 +++++ schema/cs/json-schema.texy | 65 +++ schema/cs/merging.texy | 117 +++++ schema/cs/normalization.texy | 245 ++++++++++ schema/cs/types.texy | 399 ++++++++++++++++ schema/en/@home.texy | 813 ++++----------------------------- schema/en/@left-menu.texy | 5 + schema/en/custom-elements.texy | 111 +++++ schema/en/json-schema.texy | 65 +++ schema/en/merging.texy | 117 +++++ schema/en/normalization.texy | 245 ++++++++++ schema/en/types.texy | 399 ++++++++++++++++ 14 files changed, 2070 insertions(+), 1440 deletions(-) create mode 100644 schema/cs/custom-elements.texy create mode 100644 schema/cs/json-schema.texy create mode 100644 schema/cs/merging.texy create mode 100644 schema/cs/normalization.texy create mode 100644 schema/cs/types.texy create mode 100644 schema/en/custom-elements.texy create mode 100644 schema/en/json-schema.texy create mode 100644 schema/en/merging.texy create mode 100644 schema/en/normalization.texy create mode 100644 schema/en/types.texy diff --git a/schema/cs/@home.texy b/schema/cs/@home.texy index 24bca67cf6..718656db47 100644 --- a/schema/cs/@home.texy +++ b/schema/cs/@home.texy @@ -1,808 +1,181 @@ Nette Schema ************ -.[perex] -Praktická knihovna pro validaci a normalizaci datových struktur oproti danému schématu s chytrým srozumitelným API. +
-Instalace: +Čte vaše aplikace konfigurační soubor, nebo přijímá data z API? Než na taková data váš kód sáhne, měl by si ověřit, že mají tvar, jaký čeká. Nette Schema to udělá za vás: -```shell -composer require nette/schema -``` +- Očekávaná data popíšete pár řádky srozumitelného PHP kódu +- Ohlásí všechny chyby najednou, i s cestou k položce +- Doplní výchozí hodnoty, převede hodnoty a namapuje je na vaše objekty +- Sloučí konfiguraci z více souborů podle schématu +- Vyexportuje schéma do JSON Schema, takže editory nabízejí doplňování +
-Základní použití ----------------- -V proměnné `$schema` máme validační schéma (co to přesně znamená a jak takové schéma vytvořit si řekneme vzápětí) a v proměnné `$data` datovou strukturu, kterou chceme validovat a normalizovat. Může jít například o data odeslaná uživatelem skrze rozhraní API, konfigurační soubor, atd. +Instalace +========= -Úkol obstará třída [api:Nette\Schema\Processor], která zpracuje vstup a buď vrátí normalizovaná data, nebo v případě chyby vyhodí výjimku [api:Nette\Schema\ValidationException]. - -```php -$processor = new Nette\Schema\Processor; +Knihovnu stáhnete a nainstalujete pomocí nástroje [Composer|best-practices:composer]: -try { - $normalized = $processor->process($schema, $data); -} catch (Nette\Schema\ValidationException $e) { - echo 'Data nejsou platná: ' . $e->getMessage(); -} +```shell +composer require nette/schema ``` -Metoda `$e->getMessages()` vrací pole všech zpráv jakožto řetězců a `$e->getMessageObjects()` vrací všechny zprávy jako objekty "Nette\Schema\Message":https://api.nette.org/schema/master/Nette/Schema/Message.html. +První schéma +============ -Definování schématu -------------------- - -A nyní vytvoříme schéma. K jeho definování slouží třída [api:Nette\Schema\Expect], definujeme vlastně očekávání, jak mají data vypadat. Řekněme, že vstupní data musí tvořit strukturu (například pole) obsahující prvky `processRefund` typu bool a `refundAmount` typu int. - -```php -use Nette\Schema\Expect; - -$schema = Expect::structure([ - 'processRefund' => Expect::bool(), - 'refundAmount' => Expect::int(), -]); -``` - -Věříme, že definice schématu vypadá srozumitelně, i když ji vidíte úplně poprvé. - -Pošleme k validaci následující data: +Nejlíp se to ukáže na příkladu. Dejme tomu, že se vaše aplikace připojuje k databázi a nastavení připojení čte z konfiguračního souboru. Po načtení je konfigurace obyčejné PHP pole, třeba: ```php $data = [ - 'processRefund' => true, - 'refundAmount' => 17, + 'user' => 'admin', + 'port' => 5432, ]; - -$normalized = $processor->process($schema, $data); // OK, projde validací ``` -Výstupem, tedy hodnotou `$normalized`, je objekt `stdClass`. Pokud bychom chtěli, aby výstupem bylo pole, doplníme schéma o přetypování `Expect::structure([...])->castTo('array')`. - -Všechny prvky struktury jsou volitelné a mají výchozí hodnotu `null`. Příklad: +Nic nezaručuje, že soubor obsahuje to, co váš kód potřebuje. Někdo se může překlepnout v klíči, napsat port jako text nebo úplně zapomenout uživatelské jméno. Popíšeme si proto, jak mají data vypadat. Tomuto popisu se říká **schéma** a sestavuje ho třída [api:Nette\Schema\Expect]: ```php -$data = [ - 'refundAmount' => 17, -]; - -$normalized = $processor->process($schema, $data); // OK, projde validací -// $normalized = {'processRefund' => null, 'refundAmount' => 17} -``` - -To, že výchozí hodnotou je `null`, neznamená, že by se akceptovalo ve vstupních datech `'processRefund' => null`. Nikoliv, vstupem musí být boolean, tedy pouze `true` nebo `false`. Povolit `null` bychom museli explicitně pomocí `Expect::bool()->nullable()`. - -Položku lze učinit povinnou pomocí `Expect::bool()->required()`. Výchozí hodnotu změníme třeba na `false` pomocí `Expect::bool()->default(false)` nebo zkráceně `Expect::bool(false)`. - -A co kdybychom chtěli kromě booleanu akceptovat ještě `1` a `0`? Pak uvedeme výčet hodnot, které navíc necháme normalizovat na boolean: +use Nette\Schema\Expect; -```php $schema = Expect::structure([ - 'processRefund' => Expect::anyOf(true, false, 1, 0)->castTo('bool'), - 'refundAmount' => Expect::int(), + 'host' => Expect::string('localhost'), + 'port' => Expect::int(3306), + 'user' => Expect::string()->required(), + 'password' => Expect::string()->nullable(), ]); - -$normalized = $processor->process($schema, $data); -is_bool($normalized->processRefund); // true -``` - -Nyní už znáte základy toho, jak se definuje schéma a jak se chovají jednotlivé prvky struktury. Nyní si ukážeme, jaké všechny další prvky lze při definici schématu použít. - - -Datové typy: type() -------------------- - -Ve schématu lze uvést všechny standardní datové typy PHP: - -```php -Expect::string($default = null) -Expect::int($default = null) -Expect::float($default = null) -Expect::bool($default = null) -Expect::null() -Expect::array($default = []) -Expect::list($default = []) ``` -A dále všechny typy, [podporované třídou Validators |utils:validators#Očekávané typy], například `Expect::type('scalar')` nebo zkráceně `Expect::scalar()`. Také názvy tříd či rozhraní, například `Expect::type('AddressEntity')`. +Čte se to skoro jako věta. Data jsou struktura se čtyřmi položkami: `host` je řetězec, a když chybí, je to `localhost`; `port` je celé číslo, výchozí 3306; `user` je řetězec, který musí být uvedený; a `password` je řetězec, který může být i `null`. -Lze použít i union zápis: +Teď necháme [api:Nette\Schema\Processor] data podle schématu zkontrolovat: ```php -Expect::type('bool|string|array') -``` - -Výchozí hodnota je vždy `null` s výjimkou pro `array` a `list`, kde je to prázdné pole. (List je pole indexované podle vzestupné řady numerických klíčů od nuly, tedy neasociativní pole). - -Ve verzi 1.x znamená typ `'?int[]'` pole, jehož položky jsou celá čísla nebo `null`. Verze 2.0 ho bude číst stejně jako phpDoc, tedy jako pole celých čísel, nebo `null` místo celého pole, a proto jeho použití vyvolá varování `E_USER_DEPRECATED`. Pokud chcete zachovat současný význam, napište `Expect::arrayOf(Expect::type('int')->nullable())`. .{data-version:1.4.0} - - -Pole hodnot: arrayOf() listOf() -------------------------------- - -Pole představuje příliš obecnou strukturu, užitečnější je určit, jaké prvky přesně může obsahovat. Například pole, jehož prvky mohou být pouze řetězce: - -```php -$schema = Expect::arrayOf('string'); - -$processor->process($schema, ['hello', 'world']); // OK -$processor->process($schema, ['a' => 'hello', 'b' => 'world']); // OK -$processor->process($schema, ['key' => 123]); // CHYBA: 123 není string -``` - -Druhým parametrem lze určit klíče (od verze 1.2): - -```php -$schema = Expect::arrayOf('string', 'int'); +$processor = new Nette\Schema\Processor; +$config = $processor->process($schema, $data); -$processor->process($schema, ['hello', 'world']); // OK -$processor->process($schema, ['a' => 'hello']); // CHYBA: 'a' není int +echo $config->host; // 'localhost' +echo $config->port; // 5432 ``` -List je indexované pole: +Výsledkem není stejné pole. Je to objekt `stdClass` se všemi čtyřmi položkami: chybějící `host` dostal výchozí hodnotu a chybějící `password` je `null`. Váš kód se může spolehnout, že tam každá položka je a má správný typ. -```php -$schema = Expect::listOf('string'); -$processor->process($schema, ['a', 'b']); // OK -$processor->process($schema, ['a', 123]); // CHYBA: 123 není string -$processor->process($schema, ['key' => 'a']); // CHYBA: není list -$processor->process($schema, [1 => 'a', 0 => 'b']); // CHYBA: také není list -``` +Když jsou data špatně +===================== -S parametrem `wrap` se přijme i samostatná hodnota a zabalí se do listu o jedné položce: .{data-version:1.4.0} +A co když konfigurace obsahuje chybu? Dejme tomu, že je port napsaný jako text a uživatel chybí: ```php -$schema = Expect::listOf('string', wrap: true); - -$processor->process($schema, 'hello'); // OK, vrátí ['hello'] -$processor->process($schema, ['a', 'b']); // OK -``` - -Parametrem může být i schéma, můžeme tedy zapsat: +$data = [ + 'port' => 'abc', +]; -```php -Expect::arrayOf(Expect::bool()) +try { + $config = $processor->process($schema, $data); +} catch (Nette\Schema\ValidationException $e) { + echo implode("\n", $e->getMessages()); +} ``` -Výchozí hodnota je prázdné pole. Pokud zadáte výchozí hodnotu, bude sloučena s předanými daty. To lze deaktivovat pomocí `mergeDefaults(false)` (od verze 1.1). - - -Výčet: anyOf() --------------- - -`anyOf()` představuje výčet hodnot nebo schémat, kterých může hodnota nabývat. Takto zapíšeme pole prvků, které mohou být buď `'a'`, `true` nebo `null`: - -```php -$schema = Expect::listOf( - Expect::anyOf('a', true, null), -); - -$processor->process($schema, ['a', true, null, 'a']); // OK -$processor->process($schema, ['a', false]); // CHYBA: false tam nepatří ``` - -Prvky výčtu mohou být i schémata: - -```php -$schema = Expect::listOf( - Expect::anyOf(Expect::string(), true, null), -); - -$processor->process($schema, ['foo', true, null, 'bar']); // OK -$processor->process($schema, [123]); // CHYBA +The item 'port' expects to be int, 'abc' given. +The mandatory item 'user' is missing. ``` -Metoda `anyOf()` přijímá varianty jako jednotlivé parametry, nikoliv pole. Pokud jí chcete předat pole hodnot, použijte unpacking operátor `anyOf(...$variants)`. - -Varianty se zkoušejí v pořadí, v jakém jsou zapsané, a vyhraje první, která vyhoví. Jedinou výjimkou je `null`: pokud ho výčet přijímá, vstup `null` dá vždy `null`, i když by ho dříve uvedená varianta se strukturou nebo polem jinak převedla na prázdnou strukturu či pole. - -Výchozí hodnota je `null`. Metodou `firstIsDefault()` učiníme první prvek výchozí: +Všimněte si, že dostanete všechny chyby najednou, ne jen tu první, a každá zpráva říká, které položky se týká. Uživatel opraví celý soubor naráz, místo aby spouštěl aplikaci pořád dokola. -```php -// výchozí je 'hello' -Expect::anyOf(Expect::string('hello'), true, null)->firstIsDefault(); -``` +Metoda `getMessages()` vrací zprávy jako řetězce. Pokud je chcete zobrazit po svém, `getMessageObjects()` vrací objekty, které nesou i cestu k položce a kód chyby. Víc o tom na stránce [Validace a normalizace |normalization#Chyby]. -Výčtové typy: enum() .{data-version:1.4.0} ------------------------------------------- +Popis dat +========= -Konfigurační soubor obsahuje jen prostý řetězec jako `'hearts'`, jenže v kódu byste mnohem raději pracovali s enumem. Metoda `enum()` jedno převede na druhé: předáte jí enum, jehož case mají přiřazené hodnoty (`enum Suit: string`), a ona přijme buď tuto hodnotu, nebo přímo case, a vždy vám vrátí case: +Skutečná konfigurace má víc než čtyři položky. Přesuňme připojení k databázi do vnořené struktury a přidejme seznam e-mailů správců, režim, ve kterém aplikace běží, a datum, kdy se spouští: ```php -enum Suit: string +enum Mode: string { - case Hearts = 'hearts'; - case Spades = 'spades'; + case Development = 'development'; + case Production = 'production'; } -$schema = Expect::enum(Suit::class); - -$processor->process($schema, 'hearts'); // OK, vrátí Suit::Hearts -$processor->process($schema, Suit::Spades); // OK, vrátí Suit::Spades -$processor->process($schema, 'clubs'); // CHYBA: expects to be Suit -``` - -Enumy s celočíselnými hodnotami fungují úplně stejně a platí pro ně vše, co znáte z ostatních prvků, třeba `Expect::enum(Suit::class)->required()` nebo `->default(Suit::Hearts)`. - -Při [generování schématu ze třídy |#mapovani-na-objekty-from] vám vlastnost `public Suit $suit` dá právě tento prvek, takže tam po `enum()` sahat nemusíte. `Expect::type(Suit::class)` je něco jiného: jako u každého názvu třídy přijme jen instanci, tedy samotný case. - - -Struktury ---------- - -Struktury jsou objekty s definovanými klíči. Každá z dvojic klíč => hodnota je označována jako "vlastnost". - -Struktury přijímají pole a objekty a vrací objekty `stdClass`. - -Ve výchozím nastavení jsou všechny vlastnosti volitelné a mají výchozí hodnotu `null`. Povinné vlastnosti můžete definovat pomocí `required()`: - -```php -$schema = Expect::structure([ - 'required' => Expect::string()->required(), - 'optional' => Expect::string(), // výchozí hodnota je null -]); - -$processor->process($schema, ['optional' => '']); -// CHYBA: the mandatory item 'required' is missing - -$processor->process($schema, ['required' => 'foo']); -// OK, vrací {'required' => 'foo', 'optional' => null} -``` - -Samotná struktura je povinná. Pokud je tedy vnořená v jiné struktuře a vstup ji neobsahuje, přesto se vytvoří - a ohlásí chybu ve chvíli, kdy obsahuje povinnou vlastnost. Pomocí `required(false)` učiníte celou vnořenou strukturu volitelnou. Když ve vstupu chybí, na výstupu bude `null`, ale pokud je přítomna, její povinné vlastnosti se vyžadují: - -```php -$schema = Expect::structure([ - 'db' => Expect::structure([ - 'dsn' => Expect::string()->required(), - ])->required(false), -]); - -$processor->process($schema, []); -// OK, vrací {'db' => null} - -$processor->process($schema, ['db' => []]); -// CHYBA: chybí 'db › dsn' -``` - -Pokud nechcete mít na výstupu vlastnosti s výchozí hodnotou, použijte `skipDefaults()`: - -```php -$schema = Expect::structure([ - 'required' => Expect::string()->required(), - 'optional' => Expect::string(), -])->skipDefaults(); - -$processor->process($schema, ['required' => 'foo']); -// OK, vrací {'required' => 'foo'} -``` - -Ačkoliv je `null` výchozí hodnota vlastnosti `optional`, ve vstupních datech povolený není (hodnotou musí být string). Vlastnosti akceptující `null` definujeme pomocí `nullable()`: - -```php -$schema = Expect::structure([ - 'optional' => Expect::string(), - 'nullable' => Expect::string()->nullable(), -]); - -$processor->process($schema, ['optional' => null]); -// CHYBA: 'optional' expects to be string, null given. - -$processor->process($schema, ['nullable' => null]); -// OK, vrací {'optional' => null, 'nullable' => null} -``` - -Pole všech vlastností struktury vrací metoda `getShape()`. - -Ve výchozím nastavení nemohou být ve vstupních datech žádné položky navíc: - -```php -$schema = Expect::structure([ - 'key' => Expect::string(), -]); - -$processor->process($schema, ['additional' => 1]); -// CHYBA: Unexpected item 'additional' -``` - -Což můžeme změnit pomocí `otherItems()`. Jako parametr uvedeme schéma, podle kterého se budou prvky navíc validovat: - -```php -$schema = Expect::structure([ - 'key' => Expect::string(), -])->otherItems(Expect::int()); - -$processor->process($schema, ['additional' => 1]); // OK -$processor->process($schema, ['additional' => true]); // CHYBA -``` - -Novou strukturu můžete vytvořit odvozením od jiné pomocí `extend()`: - -```php -$dog = Expect::structure([ - 'name' => Expect::string(), - 'age' => Expect::int(), -]); - -$dogWithBreed = $dog->extend([ - 'breed' => Expect::string(), -]); -``` - - -Pole .{data-version:1.3.2} --------------------------- - -Pole s definovanými klíči. Platí pro něj vše, co pro [#struktury]. - -```php -$schema = Expect::array([ - 'required' => Expect::string()->required(), - 'optional' => Expect::string(), // výchozí hodnota je null -]); -``` - - -Tuple: tuple() .{data-version:1.4.0} ------------------------------------- - -Tuple je pole pevné velikosti, v němž má každá pozice své vlastní schéma: - -```php -$schema = Expect::tuple([ - Expect::int(), - Expect::string(), - Expect::bool(), -]); - -$processor->process($schema, [1, 'hello', true]); // OK -``` - -Vstupem musí být list, takže pozice zadané klíči nebo v jiném pořadí se odmítnou. Když je vstup kratší, chybějící pozice se chovají jako chybějící položky struktury: dostanou výchozí hodnotu, nebo nahlásí chybu, pokud jsou `required()`. Metoda `otherItems()` dovolí, aby za definovanými pozicemi následovaly další položky, a určí schéma, kterému musí odpovídat, kdežto `extend()` přidá na konec další pozice. - -Když se konfigurace skládají ve vrstvách, pozdější tuple nahradí ten dřívější celý, protože smíchat pozice dvou různých tuplů by dalo jen nesmysl. - -Na rozdíl od struktury nepřijímá tuple `null` jako prázdnou hodnotu; pokud je `null` platnou hodnotou, zavolejte `nullable()`. - - -Zastaralé vlastnosti --------------------- - -Můžete označit vlastnost jako deprecated pomocí metody `deprecated([string $message])`. Informace o ukončení podpory jsou vráceny pomocí `$processor->getWarnings()`: - -```php $schema = Expect::structure([ - 'old' => Expect::int()->deprecated('The item %path% is deprecated'), + 'database' => Expect::structure([ + 'host' => Expect::string('localhost'), + 'port' => Expect::int(3306)->min(1)->max(65535), + 'user' => Expect::string()->required(), + ]), + 'admins' => Expect::listOf('email'), + 'mode' => Expect::enum(Mode::class)->default(Mode::Production), + 'launchDate' => Expect::string()->nullable()->castTo(DateTimeImmutable::class), ]); - -$processor->process($schema, ['old' => 1]); // OK -$processor->getWarnings(); // ["The item 'old' is deprecated"] ``` +Každá položka přesně říká, co přijímá. Port musí být mezi 1 a 65535. `admins` je seznam, ve kterém musí být každá položka platná e-mailová adresa. `mode` přijme ze souboru řetězec `'development'` nebo `'production'` a váš kód dostane case enumu `Mode`. `launchDate` převede řetězec jako `'2026-03-01'` na objekt `DateTimeImmutable`. -Popis: description() .{data-version:1.4.0} ------------------------------------------- - -Každému prvku můžete přidat lidsky čitelný popis. Na validaci nemá vliv, jenže schéma bývá jediné místo, kde je význam konfigurační volby vůbec zapsaný, a `description()` vám ho dovolí napsat přímo tam. Popis se také propíše do [exportu do JSON Schema |#export-do-json-schema]: +Všechny datové typy a jejich volby, od čísel a řetězců po struktury a tuply, popisuje stránka [Datové typy |types]. -```php -$schema = Expect::structure([ - 'host' => Expect::string('localhost')->description('Database server hostname'), - 'port' => Expect::int(3306)->description('Port the server listens on'), -])->description('Database connection'); -``` +Převod dat +========== -Rozsahy: min() max() --------------------- - -Pomocí `min()` a `max()` lze u polí omezit počet prvků: +Validace je jen jedna polovina. Tou druhou je převést data do podoby, se kterou váš kód pracuje nejlíp. Místo `stdClass` budete nejspíš chtít vlastní třídu. `Expect::from()` z ní schéma vytvoří rovnou, podle typů jejích vlastností: ```php -// pole, nejméně 10 položek, maximálně 20 položek -Expect::array()->min(10)->max(20); -``` - -U řetězců omezit jejich délku: - -```php -// řetězec, nejméně 10 bajtů dlouhý, maximálně 20 bajtů -Expect::string()->min(10)->max(20); -``` - -Délka řetězce se měří v bajtech. Pokud chcete u řetězce v UTF-8 počítat znaky, použijte `Expect::unicode()`. - -U čísel omezit jejich hodnotu: - -```php -// celé číslo, mezi 10 a 20 včetně -Expect::int()->min(10)->max(20); -``` - -Samozřejmě je možné uvést pouze `min()`, nebo pouze `max()`: - -```php -// řetězec maximálně 20 bajtů -Expect::string()->max(20); -``` - -U unionu jako `Expect::type('int|string')` není jasné, zda mají `min()` a `max()` omezovat číslo, nebo délku řetězce, proto tam vyvolají varování `E_USER_DEPRECATED`. Omezení místo toho dejte jednotlivým variantám [anyOf() |#vycet-anyof]: .{data-version:1.4.0} - -```php -Expect::anyOf(Expect::int()->min(1), Expect::string()->min(1)); -``` - - -Regulární výrazy: pattern() ---------------------------- - -Pomocí `pattern()` lze uvést regulární výraz, kterému musí odpovídat **celý** vstupní řetězec (tj. jako by byl obalen znaky `^` a `$`): - -```php -// právě 9 čísel -Expect::string()->pattern('\d{9}'); -``` - -Regulární výraz má smysl jen u řetězce. Proto `Expect::string()` vrací prvek třídy `StringType`, zatímco `Expect::int()` a `Expect::float()` vracejí `NumberType` a `Expect::listOf()` i ostatní schémata polí `ArrayType`, a každý z nich nabízí metody svého druhu. Volání `pattern()` u čísla nebo pole vyvolá varování `E_USER_DEPRECATED` a editor vás na zastaralé volání upozorní hned při psaní. .{data-version:1.4.0} - - -Vlastní omezení: assert() -------------------------- - -Libovolná další omezení zadáme pomocí `assert(callable $fn)`. - -```php -$countIsEven = fn($v) => count($v) % 2 === 0; - -$schema = Expect::arrayOf('string') - ->assert($countIsEven); // počet musí být sudý - -$processor->process($schema, ['a', 'b']); // OK -$processor->process($schema, ['a', 'b', 'c']); // CHYBA: 3 není sudý počet -``` - -Nebo - -```php -Expect::string()->assert('is_file'); // soubor musí existovat -``` - -Ke každému omezení můžete přidat vlastní popis. Ten bude součástí chybové zprávy. - -```php -$schema = Expect::arrayOf('string') - ->assert($countIsEven, 'Even items in array'); - -$processor->process($schema, ['a', 'b', 'c']); -// Failed assertion "Even items in array" for item with value array. -``` - -Metodu lze volat opakovaně a přidat tak více omezení. Lze ji prokládat s voláním `transform()` a `castTo()`. - - -Transformace: transform() .{data-version:1.2.5} ------------------------------------------------ - -Úspěšně zvalidovaná data lze upravovat pomocí vlastní funkce: - -```php -// převod na velká písmena: -Expect::string()->transform(fn(string $s) => strtoupper($s)); -``` - -Metodu lze volat opakovaně a přidat tak více transformací. Lze ji prokládat s voláním `assert()` a `castTo()`. Operace se provedou v pořadí, v jakém jsou deklarovány: - -```php -Expect::type('string|int') - ->castTo('string') - ->assert('ctype_lower', 'All characters must be lowercased') - ->transform(fn(string $s) => strtoupper($s)); // převod na velká písmena -``` - -Metoda `transform()` může současně transformovat i validovat hodnotu. To je často jednodušší a méně duplicitní než řetězení `transform()` a `assert()`. K tomuto účelu funkce obdrží objekt [Context |api:Nette\Schema\Context] s metodou `addError()`, kterou lze použít k přidání informací o problémech s validací: - -```php -Expect::string() - ->transform(function (string $s, Nette\Schema\Context $context) { - if (!ctype_lower($s)) { - $context->addError('All characters must be lowercased', 'my.case.error'); - return null; - } - - return strtoupper($s); - }); -``` - - -Přetypování: castTo() ---------------------- - -Úspěšně zvalidovaná data lze přetypovat: - -```php -Expect::scalar()->castTo('string'); -``` - -Kromě nativních PHP typů lze přetypovávat i na třídy. Přitom se rozlišuje, zda jde o jednoduchou třídu bez konstruktoru, nebo třídu s konstruktorem. Pokud třída nemá konstruktor, vytvoří se její instance a všechny prvky struktury se zapíší do properties: - -```php -class Info -{ - public bool $processRefund; - public int $refundAmount; -} - -Expect::structure([ - 'processRefund' => Expect::bool(), - 'refundAmount' => Expect::int(), -])->castTo(Info::class); - -// vytvoří '$obj = new Info' a zapíše do $obj->processRefund a $obj->refundAmount -``` - -Pokud třída konstruktor má, prvky struktury se předají jako pojmenované parametry konstruktoru: - -```php -class Info -{ - public function __construct( - public bool $processRefund, - public int $refundAmount, - ) { - } -} - -// vytvoří $obj = new Info(processRefund: ..., refundAmount: ...) -``` - -Přetypování v kombinaci se skalárním parametrem vytvoří objekt a hodnotu předá jako jediný parametr konstruktoru: - -```php -Expect::string()->castTo(DateTime::class); -// vytvoří new DateTime(...) -``` - -Z hodnoty `null` se objekt nikdy nevytvoří. Pokud je cílem třída nebo enum, `null` zůstane `null`, takže nevyplněná nepovinná položka zůstane prázdná: .{data-version:1.4.0} - -```php -Expect::string()->nullable()->castTo(DateTime::class); -// z '2026-01-01' bude DateTime, null zůstane null -``` - -U nativních typů přidejte otazník, pokud má `null` projít beze změny: `castTo('?string')` hodnotu `null` zachová, kdežto `castTo('string')` z ní udělá prázdný řetězec. .{data-version:1.4.0} - - -Normalizace: before() ---------------------- - -Před samotnou validací lze data normalizovat pomocí metody `before()`. Jako příklad uveďme prvek, který musí být pole řetězců (například `['a', 'b', 'c']`), avšak přijímá vstup ve formě řetězce `a b c`: - -```php -$explode = fn($v) => explode(' ', $v); - -$schema = Expect::arrayOf('string') - ->before($explode); - -$normalized = $processor->process($schema, 'a b c'); -// OK a vrátí ['a', 'b', 'c'] -``` - -Prvek má jedinou obslužnou funkci, takže druhé volání `before()` tu první nahradí. Celou normalizaci proto umístěte do jedné funkce. - -Druhé volání navíc vyvolá varování `E_USER_DEPRECATED`, protože ve verzi 2.0 se obslužné funkce budou řetězit a každá dostane výsledek té předchozí. .{data-version:1.4.0} - - -Mapování na objekty: from() ---------------------------- - -Schéma struktury si můžeme nechat vygenerovat ze třídy. Příklad: - -```php -class Config +class DatabaseConfig { - public string $name; - public string|null $password = null; - public bool $admin = false; -} - -$schema = Expect::from(new Config); - -$data = [ - 'name' => 'franta', -]; - -$normalized = $processor->process($schema, $data); -// $normalized instanceof Config -// $normalized = {'name' => 'franta', 'password' => null, 'admin' => false} -``` - -Podporovány jsou i anonymní třídy: - -```php -$schema = Expect::from(new class { - public string $name; + public string $host = 'localhost'; + public int $port = 3306; + public string $user; public ?string $password = null; - public bool $admin = false; -}); -``` - -Protože informace získané z definice třídy nemusí být dostačující, můžete druhým parametrem doplnit prvkům vlastní schéma: - -```php -$schema = Expect::from(new Config, [ - 'name' => Expect::string()->pattern('\w:.*'), -]); -``` - - -Slučování více konfigurací --------------------------- - -Aplikace často skládají konfiguraci ve vrstvách: existují vestavěné výchozí hodnoty a nad nimi uživatel dodává vlastní nastavení, které má přepsat jen ty položky, jež skutečně uvede. Přesně to dělá `processMultiple()` - vezme několik datových sad, sloučí je v pořadí tak, že pozdější mají přednost, a výsledek zvaliduje jako celek: - -```php -$schema = Expect::structure([ - 'host' => Expect::string(), - 'port' => Expect::int(), - 'logging' => Expect::bool(), -]); - -$defaults = ['host' => 'localhost', 'port' => 3306, 'logging' => false]; -$userConfig = ['port' => 5432, 'logging' => true]; - -$config = $processor->processMultiple($schema, [$defaults, $userConfig]); -// $config = {'host' => 'localhost', 'port' => 5432, 'logging' => true} -``` - -Položka `host` si ponechá výchozí hodnotu, protože ji uživatel nenastavil, zatímco `port` a `logging` přepíše pozdější datová sada. Hodnoty pod řetězcovými klíči se slučují tímto způsobem; položky listu (`listOf()`, `arrayOf()`) se místo přepsání připojují jedna za druhou. - -Pokud připojování nebo slučování podle klíčů není to, co chcete, mohou si pole a struktury zvolit jinou strategii metodou `mergeMode()`: .{data-version:1.4.0} - -```php -use Nette\Schema\MergeMode; +} -Expect::arrayOf('string')->mergeMode(MergeMode::Replace); // pozdější pole nahradí to dřívější +$schema = Expect::from(new DatabaseConfig); +$config = $processor->process($schema, ['user' => 'admin']); // instance DatabaseConfig ``` -`MergeMode::AppendKeys` slučuje podle klíčů a položky listu připojuje, `OverwriteKeys` také slučuje podle klíčů, ale položky listu přepisuje podle jejich pozice, a `Replace` ponechá jen pozdější hodnotu. Bez `mergeMode()` se pole, jehož položky nejsou popsané, třeba `Expect::array()`, slučuje do hloubky. +Kromě toho můžete hodnotu před validací upravit pomocí `before()`, po ní změnit pomocí `transform()`, přetypovat pomocí `castTo()` a přidat vlastní kontroly pomocí `assert()`. To všechno najdete na stránce [Validace a normalizace |normalization]. -Pro cokoliv jiného je tu `mergeWith()`, kterému předáte vlastní funkci, jež pozdější hodnotu zkombinuje s tou dřívější: .{data-version:1.4.0} - -```php -Expect::bool()->mergeWith(fn($value, $base) => $value || $base); // jednou zapnuto, zůstane zapnuto -``` +Konfigurace ve vrstvách +======================= -Export do JSON Schema .{data-version:1.4.0} -------------------------------------------- - -Vaše schéma už je přesným popisem toho, co smí konfigurace obsahovat, a ten popis se hodí i mimo PHP. Metoda `JsonSchema::export()` z něj vytvoří dokument "JSON Schema":https://json-schema.org, tedy formát, který čtou editory, aby rovnou v JSON nebo YAML souboru nabízely doplňování a podtrhávaly chyby: +Aplikace často skládají konfiguraci z více zdrojů: vestavěných výchozích hodnot, společného konfiguračního souboru a lokálního souboru každého vývojáře, přičemž každý přepíše jen ty položky, které uvádí. Metoda `processMultiple()` je sloučí v daném pořadí a výsledek zvaliduje jako celek: ```php -use Nette\Schema\JsonSchema; +$defaults = ['host' => 'localhost', 'port' => 3306]; +$local = ['user' => 'admin', 'port' => 5432]; -$schema = Expect::structure([ - 'host' => Expect::string('localhost')->description('Database server hostname'), - 'port' => Expect::int(3306)->min(1)->max(65535), - 'user' => Expect::string()->required(), -]); - -echo json_encode(JsonSchema::export($schema), JSON_PRETTY_PRINT); -``` - -```json -{ - "type": "object", - "properties": { - "host": {"type": "string", "description": "Database server hostname"}, - "port": {"type": "integer", "minimum": 1, "maximum": 65535}, - "user": {"type": "string"} - }, - "required": ["user"], - "additionalProperties": false -} +$config = $processor->processMultiple($schema, [$defaults, $local]); ``` -Export popisuje **tvar** dat: typy, rozsahy, regulární výrazy, povinné položky, hodnoty výčtů a texty, které jste přidali metodou `description()`. Výchozí hodnoty, `castTo()` a `transform()` v něm záměrně nejsou, protože popisují, co se s daty děje až po validaci, a to JSON Schema vyjádřit neumí. - -Typ, který existuje jen v PHP, třeba třídu (`Expect::type(Address::class)`), callable nebo resource, exportovat vůbec nelze. Místo dokumentu, který by potichu popisoval něco jiného, export vyhodí `Nette\NotSupportedException`. - -Mezi exportem a validací zůstávají dva rozdíly. JSON Schema měří délku řetězce ve znacích, kdežto `Expect::string()` v bajtech, proto pro text, který není čisté ASCII, použijte `Expect::unicode()`. A `pattern()` se exportuje tak, jak je, ale validátor JSON Schema ho čte jako regulární výraz ECMAScriptu, takže konstrukce specifické pro PCRE tam mohou být pochopeny jinak. - +O tom, jak se vrstvy zkombinují, rozhoduje schéma, třeba se položky listu připojí jedna za druhou. Jak to funguje, popisuje stránka [Slučování konfigurací |merging]. -Jak zpracování probíhá ----------------------- -Každý prvek schématu - ať vestavěný, nebo vlastní - implementuje čtyři metody, které dohromady určují, jak nakládá s daty. Tři z nich tvoří zpracovatelskou pipeline: +JSON Schema pro váš editor +========================== -1. **normalize()** - připraví surový vstup. Tady běží háčky `before()` a tady se například objekt převede na pole. Spouští se jako první, zvlášť pro každou datovou sadu. -2. **merge()** - sloučí dvě už normalizované datové sady, přičemž pozdější má přednost. Tento krok využívá jen `processMultiple()`; `process()` ho přeskakuje, protože má jen jednu datovou sadu. -3. **complete()** - provede samotnou validaci, doplní výchozí hodnoty za chybějící položky a aplikuje `assert()`, `transform()` a `castTo()`. Běží jako poslední, nad sloučeným výsledkem. +Vaše schéma už je přesným popisem toho, co smí konfigurace obsahovat. `Nette\Schema\JsonSchema::export()` z něj vytvoří dokument JSON Schema, podle kterého editory nabízejí doplňování a podtrhávají chyby přímo v konfiguračním souboru. Viz [Export do JSON Schema |json-schema]. -Čtvrtou metodu, **completeDefault()**, volá nadřazený prvek pro položku, jež ve vstupu úplně chybí - buď dodá výchozí hodnotu, nebo ohlásí, že chybí `required()` položka. -`process()` tedy provádí *normalize → complete*, zatímco `processMultiple()` provádí *normalize (každou sadu) → merge → complete*. Kvůli tomuto pořadí vidí `before()` surový vstup, kdežto `transform()` už zvalidovanou hodnotu. +Nette Schema v aplikacích Nette +=============================== +Knihovnu používáte, i když ji sami nevoláte: každé rozšíření [DI kontejneru |dependency-injection:] popisuje svou sekci konfigurace schématem v metodě [getConfigSchema() |dependency-injection:extensions#getConfigSchema]. Proto se překlep v konfiguraci vaší aplikace ohlásí srozumitelnou zprávou. -Vlastní prvky schématu ----------------------- -S `assert()`, `transform()` a `before()` se dostanete hodně daleko, takže málokdy potřebujete stavět něco od základu. Když ale chcete znovupoužitelný, samostatný prvek s vlastní logikou validace a slučování, vytvoříte ho implementací rozhraní [api:Nette\Schema\Schema]. Má přesně ty čtyři metody popsané výše: - -```php -interface Schema -{ - function normalize(mixed $value, Context $context); - function merge(mixed $value, mixed $base); - function complete(mixed $value, Context $context); - function completeDefault(Context $context); -} -``` - -Chyby se nevyhazují; místo toho je hlásíte přes objekt [Context |api:Nette\Schema\Context] pomocí `$context->addError()` a vrátíte `null`. `Processor` všechny chyby posbírá a vyhodí je na konci najednou. - -Jako příklad vytvoříme znovupoužitelný prvek pro velikosti zapsané tak, jak je lidé v konfiguraci píší nejraději, třeba `'512kB'` nebo `'2 MB'`. Prvek je zvaliduje a vrátí počet bajtů: - -```php -use Nette\Schema\Context; -use Nette\Schema\Schema; - -class ByteSizeSchema implements Schema -{ - private const Units = ['b' => 1, 'kb' => 1024, 'mb' => 1024 ** 2, 'gb' => 1024 ** 3]; - - public function normalize(mixed $value, Context $context): mixed - { - return is_int($value) ? "$value B" : $value; // sjednotíme oba zápisy - } - - public function merge(mixed $value, mixed $base): mixed - { - return $value ?? $base; // pozdější hodnota vyhrává - } - - public function complete(mixed $value, Context $context): mixed - { - if (!is_string($value) || !preg_match('~^(\d+)\s*([a-zA-Z]+)$~', $value, $m)) { - $context->addError("The item %path% expects to be a size like '512kB'.", 'size.format'); - return null; - } - - $unit = self::Units[strtolower($m[2])] ?? null; - if ($unit === null) { - $context->addError("The item %path% uses an unknown unit '$m[2]'.", 'size.unit'); - return null; - } - - return (int) $m[1] * $unit; - } - - public function completeDefault(Context $context): mixed - { - return null; // hodnota použitá, když položka ve vstupu chybí - } -} -``` - -Použijete ho kdekoli, kde se očekává vestavěný prvek - samostatně i jako součást větší struktury: - -```php -$schema = Expect::structure([ - 'maxUpload' => new ByteSizeSchema, - 'diskQuota' => new ByteSizeSchema, -]); - -$processor->process($schema, ['maxUpload' => '2 MB', 'diskQuota' => 512]); -// OK, vrátí {'maxUpload' => 2097152, 'diskQuota' => 512} - -$processor->process($schema, ['maxUpload' => '5 TB']); -// CHYBA: The item 'maxUpload' uses an unknown unit 'TB'. -``` +Co dál +====== -Protože prvek implementuje celé rozhraní, funguje automaticky i uvnitř `processMultiple()` - `Processor` volá jeho metodu `merge()` stejně jako u kteréhokoli jiného prvku. Jen `JsonSchema::export()` nemůže vědět, co takový prvek přijímá, a proto vyhodí `Nette\NotSupportedException`. +- [Datové typy |types] - všechny prvky schématu a jejich volby +- [Validace a normalizace |normalization] - vlastní kontroly, transformace, přetypování a mapování na objekty +- [Slučování konfigurací |merging] - kombinování vrstev konfigurace +- [Export do JSON Schema |json-schema] - doplňování a kontrola konfigurace v editorech +- [Vlastní prvky |custom-elements] - jak zpracování probíhá a jak napsat vlastní prvek {{maintitle: Nette Schema: validace a normalizace datových struktur v PHP}} {{description: Praktická PHP knihovna pro validaci a normalizaci dat oproti schématu s chytrým a srozumitelným API. Hodí se třeba pro konfiguraci nebo vstupy z API.}} diff --git a/schema/cs/@left-menu.texy b/schema/cs/@left-menu.texy index f96008e04b..9438aca609 100644 --- a/schema/cs/@left-menu.texy +++ b/schema/cs/@left-menu.texy @@ -1,6 +1,11 @@ Nette Schema ************ - [Úvod |@home] +- [Datové typy |types] +- [Validace a normalizace |normalization] +- [Slučování konfigurací |merging] +- [Export do JSON Schema |json-schema] +- [Vlastní prvky |custom-elements] Další četba diff --git a/schema/cs/custom-elements.texy b/schema/cs/custom-elements.texy new file mode 100644 index 0000000000..8ab1f34d24 --- /dev/null +++ b/schema/cs/custom-elements.texy @@ -0,0 +1,111 @@ +Vlastní prvky +************* + +
+ +S `assert()`, `transform()` a `before()` se dostanete hodně daleko, takže málokdy potřebujete stavět něco od základu. Když ale chcete znovupoužitelný, samostatný prvek s vlastní logikou validace a slučování, můžete si ho napsat. Tato stránka vysvětluje: + +- jak procesor s daty krok za krokem zachází +- rozhraní, které implementuje každý prvek +- jak napsat a použít vlastní prvek + +
+ + +Jak zpracování probíhá +====================== + +Každý prvek schématu - ať vestavěný, nebo vlastní - implementuje čtyři metody, které dohromady určují, jak nakládá s daty. Tři z nich tvoří zpracovatelskou pipeline: + +1. **normalize()** - připraví surový vstup. Tady běží háčky `before()` a tady se například objekt převede na pole. Spouští se jako první, zvlášť pro každou datovou sadu. +2. **merge()** - sloučí dvě už normalizované datové sady, přičemž pozdější má přednost. Tento krok využívá jen `processMultiple()`; `process()` ho přeskakuje, protože má jen jednu datovou sadu. +3. **complete()** - provede samotnou validaci, doplní výchozí hodnoty za chybějící položky a aplikuje `assert()`, `transform()` a `castTo()`. Běží jako poslední, nad sloučeným výsledkem. + +Čtvrtou metodu, **completeDefault()**, volá nadřazený prvek pro položku, jež ve vstupu úplně chybí - buď dodá výchozí hodnotu, nebo ohlásí, že chybí `required()` položka. + +`process()` tedy provádí *normalize → complete*, zatímco `processMultiple()` provádí *normalize (každou sadu) → merge → complete*. Kvůli tomuto pořadí vidí `before()` surový vstup, kdežto `transform()` už zvalidovanou hodnotu. + + +Rozhraní Schema +=============== + +Vlastní prvek vytvoříte implementací rozhraní [api:Nette\Schema\Schema]. Má přesně ty čtyři metody popsané výše: + +```php +interface Schema +{ + function normalize(mixed $value, Context $context); + function merge(mixed $value, mixed $base); + function complete(mixed $value, Context $context); + function completeDefault(Context $context); +} +``` + +Chyby se nevyhazují; místo toho je hlásíte přes objekt [Context |api:Nette\Schema\Context] pomocí `$context->addError()` a vrátíte `null`. `Processor` všechny chyby posbírá a vyhodí je na konci najednou. + + +Příklad: velikosti v bajtech +============================ + +Jako příklad vytvoříme znovupoužitelný prvek pro velikosti zapsané tak, jak je lidé v konfiguraci píší nejraději, třeba `'512kB'` nebo `'2 MB'`. Prvek je zvaliduje a vrátí počet bajtů: + +```php +use Nette\Schema\Context; +use Nette\Schema\Schema; + +class ByteSizeSchema implements Schema +{ + private const Units = ['b' => 1, 'kb' => 1024, 'mb' => 1024 ** 2, 'gb' => 1024 ** 3]; + + public function normalize(mixed $value, Context $context): mixed + { + return is_int($value) ? "$value B" : $value; // sjednotíme oba zápisy + } + + public function merge(mixed $value, mixed $base): mixed + { + return $value ?? $base; // pozdější hodnota vyhrává + } + + public function complete(mixed $value, Context $context): mixed + { + if (!is_string($value) || !preg_match('~^(\d+)\s*([a-zA-Z]+)$~', $value, $m)) { + $context->addError("The item %path% expects to be a size like '512kB'.", 'size.format'); + return null; + } + + $unit = self::Units[strtolower($m[2])] ?? null; + if ($unit === null) { + $context->addError("The item %path% uses an unknown unit '$m[2]'.", 'size.unit'); + return null; + } + + return (int) $m[1] * $unit; + } + + public function completeDefault(Context $context): mixed + { + return null; // hodnota použitá, když položka ve vstupu chybí + } +} +``` + +Použijete ho kdekoli, kde se očekává vestavěný prvek - samostatně i jako součást větší struktury: + +```php +$schema = Expect::structure([ + 'maxUpload' => new ByteSizeSchema, + 'diskQuota' => new ByteSizeSchema, +]); + +$processor->process($schema, ['maxUpload' => '2 MB', 'diskQuota' => 512]); +// OK, vrátí {'maxUpload' => 2097152, 'diskQuota' => 512} + +$processor->process($schema, ['maxUpload' => '5 TB']); +// CHYBA: The item 'maxUpload' uses an unknown unit 'TB'. +``` + +Protože prvek implementuje celé rozhraní, funguje automaticky i uvnitř `processMultiple()` - `Processor` volá jeho metodu `merge()` stejně jako u kteréhokoli jiného prvku. Jen [JsonSchema::export() |json-schema] nemůže vědět, co takový prvek přijímá, a proto vyhodí `Nette\NotSupportedException`. + +{{maintitle: Nette Schema: jak probíhá zpracování a vlastní prvky}} +{{description: Podívejte se, jak Nette Schema data normalizuje, slučuje a doplňuje, a napište si znovupoužitelný vlastní prvek s vlastní logikou validace a slučování.}} diff --git a/schema/cs/json-schema.texy b/schema/cs/json-schema.texy new file mode 100644 index 0000000000..e54ce5ce6b --- /dev/null +++ b/schema/cs/json-schema.texy @@ -0,0 +1,65 @@ +Export do JSON Schema +********************* + +
+ +Vaše schéma už je přesným popisem toho, co smí konfigurace obsahovat, a ten popis se hodí i mimo PHP. Vyexportované do JSON Schema umožní editorům: + +- nabízet doplňování klíčů a hodnot přímo v konfiguračním souboru +- podtrhnout chyby dřív, než se aplikace vůbec spustí +- ukazovat popisy voleb jako nápovědu + +
+ + +Export .{data-version:1.4.0} +============================ + +Metoda `JsonSchema::export()` vytvoří z vašeho schématu dokument "JSON Schema":https://json-schema.org, tedy formát, který čtou editory, aby rovnou v JSON nebo YAML souboru nabízely doplňování a podtrhávaly chyby: + +```php +use Nette\Schema\Expect; +use Nette\Schema\JsonSchema; + +$schema = Expect::structure([ + 'host' => Expect::string('localhost')->description('Database server hostname'), + 'port' => Expect::int(3306)->min(1)->max(65535), + 'user' => Expect::string()->required(), +]); + +echo json_encode(JsonSchema::export($schema), JSON_PRETTY_PRINT); +``` + +```json +{ + "type": "object", + "properties": { + "host": {"type": "string", "description": "Database server hostname"}, + "port": {"type": "integer", "minimum": 1, "maximum": 65535}, + "user": {"type": "string"} + }, + "required": ["user"], + "additionalProperties": false +} +``` + +Výsledek uložte do souboru a nasměrujte na něj svůj editor; jak přesně, záleží na editoru a na formátu konfiguračního souboru. + + +Co export obsahuje +================== + +Export popisuje **tvar** dat: typy, rozsahy, regulární výrazy, povinné položky, hodnoty výčtů a texty, které jste přidali metodou [description() |types#Popis: description()]. + +Výchozí hodnoty, `castTo()` a `transform()` v něm záměrně nejsou, protože popisují, co se s daty děje až po validaci, a to JSON Schema vyjádřit neumí. + +Typ, který existuje jen v PHP, třeba třídu (`Expect::type(Address::class)`), callable nebo resource, exportovat vůbec nelze. Místo dokumentu, který by potichu popisoval něco jiného, export vyhodí `Nette\NotSupportedException`. Totéž platí pro [vlastní prvek |custom-elements], jehož pravidla export znát nemůže. + + +Rozdíly oproti validaci +======================= + +Mezi exportem a validací zůstávají dva rozdíly. JSON Schema měří délku řetězce ve znacích, kdežto `Expect::string()` v bajtech, proto pro text, který není čisté ASCII, použijte `Expect::unicode()`. A `pattern()` se exportuje tak, jak je, ale validátor JSON Schema ho čte jako regulární výraz ECMAScriptu, takže konstrukce specifické pro PCRE tam mohou být pochopeny jinak. + +{{maintitle: Nette Schema: export do JSON Schema pro doplňování v editoru}} +{{description: Vyexportujte Nette Schema do JSON Schema, aby editory nabízely doplňování a podtrhávaly chyby v konfiguračních souborech. Co export obsahuje a v čem se liší.}} diff --git a/schema/cs/merging.texy b/schema/cs/merging.texy new file mode 100644 index 0000000000..e0a31055ba --- /dev/null +++ b/schema/cs/merging.texy @@ -0,0 +1,117 @@ +Slučování konfigurací +********************* + +
+ +Aplikace často skládají konfiguraci z více vrstev: vestavěných výchozích hodnot, konfiguračního souboru sdíleného týmem a lokálního souboru každého vývojáře. Každá vrstva přepíše jen ty položky, které uvádí. Tato stránka ukazuje: + +- jak `processMultiple()` vrstvy sloučí a výsledek zvaliduje +- jak se kombinují struktury, pole a listy +- jak zvolit jinou strategii pomocí `mergeMode()` nebo vlastní funkce +- jak se slučují pole, jejichž položky nejsou popsané + +
+ +Ukázky navazují na konfiguraci aplikace z [úvodu |@home]. `$processor` je instance `Nette\Schema\Processor`. + + +Slučování vrstev: processMultiple() +=================================== + +Metoda `processMultiple()` vezme několik datových sad, sloučí je v pořadí tak, že pozdější mají přednost, a výsledek zvaliduje jako celek: + +```php +$schema = Expect::structure([ + 'host' => Expect::string(), + 'port' => Expect::int(), + 'logging' => Expect::bool(), +]); + +$defaults = ['host' => 'localhost', 'port' => 3306, 'logging' => false]; +$local = ['port' => 5432, 'logging' => true]; + +$config = $processor->processMultiple($schema, [$defaults, $local]); +// $config = {'host' => 'localhost', 'port' => 5432, 'logging' => true} +``` + +Položka `host` si ponechá výchozí hodnotu, protože ji lokální soubor nenastavil, zatímco `port` a `logging` přepíše pozdější datová sada. + +Všimněte si, že se výsledek validuje jen jednou, až po sloučení. Samotná vrstva může být neúplná, třeba výchozí hodnotám obvykle chybí heslo, a všechno povinné musí obsahovat až sloučená konfigurace. + + +Jak se hodnoty kombinují +======================== + +O tom, jak se dvě vrstvy zkombinují, rozhoduje schéma: + +- jednoduchou hodnotu, třeba řetězec nebo číslo, nahradí ta pozdější +- struktura a pole s řetězcovými klíči se slučují podle klíčů, rekurzivně podle schémat svých položek +- položky listu (`listOf()`, případně `arrayOf()` s číselnými klíči) se připojují jedna za druhou +- [tuple |types#Tuple: tuple()] se nahradí celý, protože smíchat pozice dvou tuplů by dalo jen nesmysl + +Takže s `'admins' => Expect::listOf('email')` se správci z lokálního souboru přidají k těm ze sdíleného: + +```php +$schema = Expect::structure([ + 'admins' => Expect::listOf('email'), +]); + +$config = $processor->processMultiple($schema, [ + ['admins' => ['jim@example.com']], + ['admins' => ['ann@example.com']], +]); +// $config->admins = ['jim@example.com', 'ann@example.com'] +``` + +Výchozí hodnota pole se s vrstvami také slučuje: její položky zůstanou, pokud je některá vrstva nepřepíše, a k listu se položky vrstev připojí. Pokud to nechcete, zavolejte [mergeDefaults(false) |types#Pole a listy: arrayOf() listOf()]. + + +Volba strategie: mergeMode() .{data-version:1.4.0} +================================================== + +Pokud připojování nebo slučování podle klíčů není to, co chcete, mohou si pole a struktury zvolit jinou strategii metodou `mergeMode()`. Dejme tomu, že lokální soubor má seznam správců nahradit, ne k němu přidávat: + +```php +use Nette\Schema\MergeMode; + +Expect::listOf('email')->mergeMode(MergeMode::Replace); // pozdější list nahradí ten dřívější +``` + +`MergeMode::AppendKeys` slučuje podle klíčů a položky listu připojuje, `OverwriteKeys` také slučuje podle klíčů, ale položky listu přepisuje podle jejich pozice, a `Replace` ponechá jen pozdější hodnotu. + +V konfiguračním souboru NEON aplikace Nette zabrání vykřičník za klíčem, `admins!:`, sloučení té jedné položky, viz [konfigurace DI kontejneru |dependency-injection:configuration#Slučování]. + + +Pole bez popsaných položek +========================== + +Pole, jehož položky nejsou popsané, třeba `Expect::array()`, se slučuje do hloubky, podle klíčů na všech úrovních: + +```php +$schema = Expect::structure([ + 'options' => Expect::array(), +]); + +$processor->processMultiple($schema, [ + ['options' => ['cache' => ['ttl' => 60]]], + ['options' => ['cache' => ['ttl' => 3600]]], +]); +// OK, vrátí {'options' => ['cache' => ['ttl' => 3600]]} +``` + +Počítejte s tím, že schéma pak nemůže zkontrolovat, co pole obsahují. Pokud má pozdější vrstva pole nahradit celé, zvolte `mergeMode(MergeMode::Replace)`. + + +Vlastní funkce: mergeWith() .{data-version:1.4.0} +================================================= + +Pro cokoliv jiného je tu `mergeWith()`, kterému předáte vlastní funkci, jež pozdější hodnotu zkombinuje s tou dřívější. Dejme tomu, že logování má zůstat zapnuté, jakmile ho kterákoliv vrstva zapne: + +```php +Expect::bool()->mergeWith(fn($value, $base) => $value || $base); // jednou zapnuto, zůstane zapnuto +``` + +Funkce jen kombinuje vrstvy; pokud chcete upravit tvar jedné vrstvy, použijte [before() |normalization#Normalizace: before()]. + +{{maintitle: Nette Schema: slučování konfiguračních souborů v PHP}} +{{description: Slučte konfiguraci z výchozích hodnot, sdíleného a lokálního souboru pomocí Nette Schema. Jak se kombinují struktury, pole a listy a jak zvolit strategii.}} diff --git a/schema/cs/normalization.texy b/schema/cs/normalization.texy new file mode 100644 index 0000000000..decd5c58c4 --- /dev/null +++ b/schema/cs/normalization.texy @@ -0,0 +1,245 @@ +Validace a normalizace +********************** + +
+ +Kontrola typů často nestačí. Data z konfiguračního souboru nebo z API potřebují další kontroly a úpravy, než s nimi váš kód může pracovat. Tato stránka ukazuje, jak: + +- přidat vlastní kontroly pomocí `assert()` +- upravit hodnotu před validací pomocí `before()` a po ní pomocí `transform()` +- přetypovat hodnotu na jiný typ nebo třídu pomocí `castTo()` +- sestavit schéma ze třídy pomocí `from()` +- pracovat s chybami a upozorněními + +
+ +Ukázky navazují na konfiguraci aplikace z [úvodu |@home]. `$processor` je instance `Nette\Schema\Processor`. + + +Pořadí operací +============== + +Hodí se vědět, kdy který krok běží. Nejprve obslužná funkce `before()` upraví surový vstup. Pak se hodnota zvaliduje podle prvku: její typ, rozsahy, regulární výraz a podobně. Jen platná hodnota pokračuje do `assert()`, `transform()` a `castTo()`, které se provedou v pořadí, v jakém jste je deklarovali. Proto `before()` vidí vstup tak, jak přišel, kdežto `transform()` dostane hodnotu s už ověřeným typem. + +Podrobnější pohled na zpracování, včetně slučování více datových sad, najdete na stránce [Vlastní prvky |custom-elements#Jak zpracování probíhá]. + + +Vlastní kontroly: assert() +========================== + +Libovolná další omezení zadáme pomocí `assert(callable $fn)`. Funkce dostane hodnotu a vrátí `true`, když je platná. Dejme tomu, že seznam správců nesmí obsahovat stejný e-mail dvakrát: + +```php +$isUnique = fn(array $list) => count($list) === count(array_unique($list)); + +$schema = Expect::listOf('email') + ->assert($isUnique); // každý e-mail jen jednou + +$processor->process($schema, ['jim@example.com', 'ann@example.com']); // OK +$processor->process($schema, ['jim@example.com', 'jim@example.com']); +// CHYBA: Failed assertion #0 for item with value array. +``` + +Poslouží jakákoliv funkce, i vestavěná: + +```php +Expect::string()->assert('is_dir'); // adresář musí existovat +``` + +Zpráva výše toho moc neřekne. Když omezení dáte popis, stane se součástí chybové zprávy: + +```php +$schema = Expect::listOf('email') + ->assert($isUnique, 'Unique e-mails'); + +$processor->process($schema, ['jim@example.com', 'jim@example.com']); +// CHYBA: Failed assertion 'Unique e-mails' for item with value array. +``` + +Metodu lze volat opakovaně a přidat tak více omezení. Lze ji prokládat s voláním `transform()` a `castTo()`. + + +Transformace: transform() .{data-version:1.2.5} +=============================================== + +Úspěšně zvalidovaná data lze upravovat pomocí vlastní funkce. Dejme tomu, že základní URL aplikace nemá nikdy končit lomítkem: + +```php +Expect::string()->transform(fn(string $url) => rtrim($url, '/')); +``` + +Metodu lze volat opakovaně a přidat tak více transformací. Lze ji prokládat s voláním `assert()` a `castTo()`. Operace se provedou v pořadí, v jakém jsou deklarovány: + +```php +Expect::string() + ->transform(fn(string $s) => strtolower(trim($s))) // z ' Admin ' bude 'admin' + ->assert('ctype_alnum', 'Only letters and digits'); +``` + +Metoda `transform()` může současně transformovat i validovat hodnotu. To je často jednodušší a méně duplicitní než řetězení `transform()` a `assert()`. K tomuto účelu funkce obdrží objekt [Context |api:Nette\Schema\Context] s metodou `addError()`, kterou lze použít k přidání informací o problémech s validací. Převeďme server zapsaný jako `'db.example.com:5432'` na adresu a port: + +```php +Expect::string() + ->transform(function (string $s, Nette\Schema\Context $context) { + if (!preg_match('~^([^:]+):(\d+)$~', $s, $m)) { + $context->addError('The item %path% expects to be host:port.', 'server.format'); + return null; + } + + return ['host' => $m[1], 'port' => (int) $m[2]]; + }); +``` + + +Přetypování: castTo() +===================== + +Úspěšně zvalidovaná data lze přetypovat: + +```php +Expect::scalar()->castTo('string'); +``` + +Kromě nativních PHP typů lze přetypovávat i na třídy. Přitom se rozlišuje, zda jde o jednoduchou třídu bez konstruktoru, nebo třídu s konstruktorem. Pokud třída nemá konstruktor, vytvoří se její instance a všechny prvky struktury se zapíší do properties: + +```php +class DatabaseConfig +{ + public string $host; + public int $port; +} + +Expect::structure([ + 'host' => Expect::string('localhost'), + 'port' => Expect::int(3306), +])->castTo(DatabaseConfig::class); + +// vytvoří '$obj = new DatabaseConfig' a zapíše do $obj->host a $obj->port +``` + +Pokud třída konstruktor má, prvky struktury se předají jako pojmenované parametry konstruktoru: + +```php +class DatabaseConfig +{ + public function __construct( + public string $host, + public int $port, + ) { + } +} + +// vytvoří $obj = new DatabaseConfig(host: ..., port: ...) +``` + +Přetypování v kombinaci se skalárním parametrem vytvoří objekt a hodnotu předá jako jediný parametr konstruktoru: + +```php +Expect::string()->castTo(DateTime::class); +// vytvoří new DateTime(...) +``` + +Z hodnoty `null` se objekt nikdy nevytvoří. Pokud je cílem třída nebo enum, `null` zůstane `null`, takže nevyplněná nepovinná položka zůstane prázdná: .{data-version:1.4.0} + +```php +Expect::string()->nullable()->castTo(DateTime::class); +// z '2026-01-01' bude DateTime, null zůstane null +``` + +U nativních typů přidejte otazník, pokud má `null` projít beze změny: `castTo('?string')` hodnotu `null` zachová, kdežto `castTo('string')` z ní udělá prázdný řetězec. .{data-version:1.4.0} + + +Normalizace: before() +===================== + +Před samotnou validací lze data normalizovat pomocí metody `before()`. Dejme tomu, že seznam správců jde zapsat i jako jeden řetězec s čárkami, `'jim@example.com, ann@example.com'`: + +```php +$explode = fn($v) => is_string($v) ? array_map('trim', explode(',', $v)) : $v; + +$schema = Expect::listOf('email') + ->before($explode); + +$normalized = $processor->process($schema, 'jim@example.com, ann@example.com'); +// OK a vrátí ['jim@example.com', 'ann@example.com'] +``` + +Prvek má jedinou obslužnou funkci, takže druhé volání `before()` tu první nahradí. Celou normalizaci proto umístěte do jedné funkce. + +Druhé volání navíc vyvolá varování `E_USER_DEPRECATED`, protože ve verzi 2.0 se obslužné funkce budou řetězit a každá dostane výsledek té předchozí. .{data-version:1.4.0} + + +Mapování na objekty: from() +=========================== + +Schéma struktury si můžeme nechat vygenerovat z objektu třídy. Sestaví se z typů jejích veřejných vlastností. Příklad: + +```php +class DatabaseConfig +{ + public string $host = 'localhost'; + public int $port = 3306; + public string $user; + public ?string $password = null; + public Mode $mode = Mode::Production; +} + +$schema = Expect::from(new DatabaseConfig); + +$config = $processor->process($schema, [ + 'user' => 'admin', + 'mode' => 'development', +]); +// $config instanceof DatabaseConfig +// $config->mode === Mode::Development +``` + +Vlastnost bez výchozí hodnoty, třeba `$user`, se stane povinnou položkou. Vlastnost typovaná [enumem s hodnotami |types#Výčtové typy: enum()] přijme ze vstupu jeho hodnotu a vrátí vám case. + +Podporovány jsou i anonymní třídy: + +```php +$schema = Expect::from(new class { + public string $host = 'localhost'; + public int $port = 3306; +}); +``` + +Protože informace získané z definice třídy nemusí být dostačující, můžete druhým parametrem doplnit prvkům vlastní schéma: + +```php +$schema = Expect::from(new DatabaseConfig, [ + 'port' => Expect::int(3306)->min(1)->max(65535), +]); +``` + + +Chyby +===== + +Když jsou data neplatná, `process()` vyhodí [api:Nette\Schema\ValidationException] se všemi nalezenými chybami: + +```php +try { + $config = $processor->process($schema, $data); +} catch (Nette\Schema\ValidationException $e) { + echo 'Data nejsou platná: ' . $e->getMessage(); +} +``` + +Metoda `$e->getMessage()` vrací první chybu, `$e->getMessages()` pole všech jako řetězců. Pokud chcete chyby zobrazit po svém, třeba u jednotlivých polí formuláře, `$e->getMessageObjects()` je vrací jako objekty [api:Nette\Schema\Message]. Každý má text v `$message`, cestu k položce v `$path` a kód, který říká, o jaký druh chyby jde, v `$code`: + +```php +foreach ($e->getMessageObjects() as $message) { + echo implode(' › ', $message->path), ': ', $message->code, "\n"; +} +// port: schema.typeMismatch +// user: schema.missingItem +``` + +Kódy jsou konstanty třídy `Message`, třeba `Message::TypeMismatch`, `MissingItem` nebo `UnexpectedItem`. + +Upozornění, třeba na použití [zastaralé položky |types#Zastaralé položky: deprecated()], zpracování nezastaví. Přečtete je po něm pomocí `$processor->getWarnings()`. + +{{maintitle: Nette Schema: vlastní validace, transformace a přetypování}} +{{description: Přidejte do Nette Schema vlastní kontroly, upravte hodnoty před validací i po ní, přetypujte je na třídy, sestavte schéma ze třídy a pracujte s chybami.}} diff --git a/schema/cs/types.texy b/schema/cs/types.texy new file mode 100644 index 0000000000..db19ac8d81 --- /dev/null +++ b/schema/cs/types.texy @@ -0,0 +1,399 @@ +Datové typy +*********** + +
+ +Schéma se skládá z prvků a každý z nich popisuje jednu část dat. Tato stránka je prochází všechny: + +- jednoduché typy, formáty a rozsahy +- výchozí hodnoty, povinné položky a položky připouštějící `null` +- pole, listy, výčty a enumy +- struktury a tuply +- popisy a zastaralé položky + +
+ +Ukázky navazují na konfiguraci aplikace z [úvodu |@home]. `$processor` je instance `Nette\Schema\Processor`. + + +Jednoduché typy: type() +======================= + +Ve schématu lze uvést všechny standardní datové typy PHP: + +```php +Expect::string($default = null); +Expect::int($default = null); +Expect::float($default = null); +Expect::bool($default = null); +Expect::null(); +Expect::array($default = []); +Expect::list($default = []); +``` + +A dále všechny typy, [podporované třídou Validators |utils:validators#Očekávané typy], například `Expect::type('scalar')` nebo zkráceně `Expect::scalar()`. Také názvy tříd či rozhraní, například `Expect::type('AddressEntity')`. + +Lze použít i union zápis: + +```php +Expect::type('bool|string|array') +``` + +Výchozí hodnota je vždy `null` s výjimkou pro `array` a `list`, kde je to prázdné pole. (List je pole indexované podle vzestupné řady numerických klíčů od nuly, tedy neasociativní pole). + +Ve verzi 1.x znamená typ `'?int[]'` pole, jehož položky jsou celá čísla nebo `null`. Verze 2.0 ho čte stejně jako phpDoc, tedy jako pole celých čísel, nebo `null` místo celého pole. Pokud myslíte pole, jehož položky mohou být `null`, napište `Expect::arrayOf(Expect::int()->nullable())`, což znamená totéž v obou verzích. + + +Výchozí, povinné a nullable +=========================== + +Každá položka, která ve vstupu chybí, dostane výchozí hodnotu. U většiny typů je to `null` a jinou nastavíte jako parametr nebo pomocí `default()`: + +```php +Expect::int(3306); +Expect::int()->default(3306); // totéž +``` + +Výchozí hodnota `null` neznamená, že vstup smí obsahovat `null`. `Expect::string()` přijme jen řetězec, takže `'password' => null` ve vstupu je chyba. Pokud chcete `null` povolit, zavolejte `nullable()`: + +```php +$schema = Expect::structure([ + 'user' => Expect::string(), + 'password' => Expect::string()->nullable(), +]); + +$processor->process($schema, ['user' => null]); +// CHYBA: The item 'user' expects to be string, null given. + +$processor->process($schema, ['password' => null]); +// OK, vrací {'password' => null, 'user' => null} +``` + +Položku, která musí být uvedená, označíte pomocí `required()`. Když chybí, zpracování ohlásí chybu, místo aby použilo výchozí hodnotu: + +```php +$schema = Expect::structure([ + 'user' => Expect::string()->required(), +]); + +$processor->process($schema, []); +// CHYBA: The mandatory item 'user' is missing. +``` + + +Rozsahy: min() max() +==================== + +Pomocí `min()` a `max()` lze u polí omezit počet prvků: + +```php +// pole, nejméně 1 položka, maximálně 5 položek +Expect::listOf('email')->min(1)->max(5); +``` + +U řetězců omezit jejich délku: + +```php +// řetězec, nejméně 8 bajtů dlouhý, maximálně 64 bajtů +Expect::string()->min(8)->max(64); +``` + +Délka řetězce se měří v bajtech. Pokud chcete u řetězce v UTF-8 počítat znaky, použijte `Expect::unicode()`. + +U čísel omezit jejich hodnotu: + +```php +// celé číslo, mezi 1 a 65535 včetně +Expect::int()->min(1)->max(65535); +``` + +Samozřejmě je možné uvést pouze `min()`, nebo pouze `max()`: + +```php +// řetězec maximálně 64 bajtů +Expect::string()->max(64); +``` + +U unionu jako `Expect::type('int|string')` není jasné, zda mají `min()` a `max()` omezovat číslo, nebo délku řetězce, proto tam vyvolají varování `E_USER_DEPRECATED`. Omezení místo toho dejte jednotlivým variantám [anyOf() |#Výčet: anyOf()]: .{data-version:1.4.0} + +```php +Expect::anyOf(Expect::int()->min(1), Expect::string()->min(1)); +``` + + +Regulární výrazy: pattern() +=========================== + +Pomocí `pattern()` lze uvést regulární výraz, kterému musí odpovídat **celý** vstupní řetězec (tj. jako by byl obalen znaky `^` a `$`): + +```php +// právě 9 čísel +Expect::string()->pattern('\d{9}'); +``` + +Regulární výraz má smysl jen u řetězce. Proto `Expect::string()` vrací prvek třídy `StringType`, zatímco `Expect::int()` a `Expect::float()` vracejí `NumberType` a `Expect::listOf()` i ostatní schémata polí `ArrayType`, a každý z nich nabízí metody svého druhu. Volání `pattern()` u čísla nebo pole vyvolá varování `E_USER_DEPRECATED` a editor vás na zastaralé volání upozorní hned při psaní. .{data-version:1.4.0} + + +Pole a listy: arrayOf() listOf() +================================ + +Pole představuje příliš obecnou strukturu, užitečnější je určit, jaké prvky přesně může obsahovat. Například pole, jehož prvky mohou být pouze řetězce: + +```php +$schema = Expect::arrayOf('string'); + +$processor->process($schema, ['hello', 'world']); // OK +$processor->process($schema, ['a' => 'hello', 'b' => 'world']); // OK +$processor->process($schema, ['key' => 123]); // CHYBA: 123 není string +``` + +Druhým parametrem lze určit klíče (od verze 1.2): + +```php +$schema = Expect::arrayOf('string', 'int'); + +$processor->process($schema, ['hello', 'world']); // OK +$processor->process($schema, ['a' => 'hello']); // CHYBA: 'a' není int +``` + +List je indexované pole: + +```php +$schema = Expect::listOf('email'); + +$processor->process($schema, ['jim@example.com', 'ann@example.com']); // OK +$processor->process($schema, ['jim@example.com', 'jim']); // CHYBA: 'jim' není e-mail +$processor->process($schema, ['key' => 'jim@example.com']); // CHYBA: není list +``` + +S parametrem `wrap` se přijme i samostatná hodnota a zabalí se do listu o jedné položce. Konfigurace s jediným správcem pak nepotřebuje závorky: .{data-version:1.4.0} + +```php +$schema = Expect::listOf('email', wrap: true); + +$processor->process($schema, 'jim@example.com'); // OK, vrátí ['jim@example.com'] +``` + +Parametrem může být i schéma, můžeme tedy zapsat: + +```php +Expect::arrayOf(Expect::bool()) +``` + +Výchozí hodnota je prázdné pole. Pokud zadáte výchozí hodnotu, bude sloučena s předanými daty. To lze deaktivovat pomocí `mergeDefaults(false)` (od verze 1.1). + + +Výčet: anyOf() +============== + +`anyOf()` představuje výčet hodnot nebo schémat, kterých může hodnota nabývat. Takto zapíšeme pole prvků, které mohou být buď `'a'`, `true` nebo `null`: + +```php +$schema = Expect::listOf( + Expect::anyOf('a', true, null), +); + +$processor->process($schema, ['a', true, null, 'a']); // OK +$processor->process($schema, ['a', false]); // CHYBA: false tam nepatří +``` + +Prvky výčtu mohou být i schémata: + +```php +$schema = Expect::listOf( + Expect::anyOf(Expect::string(), true, null), +); + +$processor->process($schema, ['foo', true, null, 'bar']); // OK +$processor->process($schema, [123]); // CHYBA +``` + +Metoda `anyOf()` přijímá varianty jako jednotlivé parametry, nikoliv pole. Pokud jí chcete předat pole hodnot, použijte unpacking operátor `anyOf(...$variants)`. + +Varianty se zkoušejí v pořadí, v jakém jsou zapsané, a vyhraje první, která vyhoví. Jedinou výjimkou je `null`: pokud ho výčet přijímá, vstup `null` dá vždy `null`, i když by ho dříve uvedená varianta se strukturou nebo polem jinak převedla na prázdnou strukturu či pole. + +Výchozí hodnota je `null`. Metodou `firstIsDefault()` učiníme první prvek výchozí: + +```php +// výchozí je 'hello' +Expect::anyOf(Expect::string('hello'), true, null)->firstIsDefault(); +``` + + +Výčtové typy: enum() .{data-version:1.4.0} +========================================== + +Konfigurační soubor obsahuje jen prostý řetězec jako `'production'`, jenže v kódu byste mnohem raději pracovali s enumem. Metoda `enum()` jedno převede na druhé: předáte jí enum, jehož case mají přiřazené hodnoty (`enum Mode: string`), a ona přijme buď tuto hodnotu, nebo přímo case, a vždy vám vrátí case: + +```php +enum Mode: string +{ + case Development = 'development'; + case Production = 'production'; +} + +$schema = Expect::enum(Mode::class); + +$processor->process($schema, 'production'); // OK, vrátí Mode::Production +$processor->process($schema, Mode::Development); // OK, vrátí Mode::Development +$processor->process($schema, 'test'); // CHYBA: expects to be Mode +``` + +Enumy s celočíselnými hodnotami fungují úplně stejně a platí pro ně vše, co znáte z ostatních prvků, třeba `Expect::enum(Mode::class)->required()` nebo `->default(Mode::Production)`. + +Při [generování schématu ze třídy |normalization#Mapování na objekty: from()] vám vlastnost `public Mode $mode` dá právě tento prvek, takže tam po `enum()` sahat nemusíte. `Expect::type(Mode::class)` je něco jiného: jako u každého názvu třídy přijme jen instanci, tedy samotný case. + + +Struktury +========= + +Struktury jsou objekty s definovanými klíči. Každá z dvojic klíč => hodnota je označována jako "vlastnost". + +Struktury přijímají pole a objekty a vrací objekty `stdClass`. Pokud chcete místo toho pole, doplňte `castTo('array')`. + +Ve výchozím nastavení jsou všechny vlastnosti volitelné a mají výchozí hodnotu `null`. Povinné vlastnosti můžete definovat pomocí `required()`: + +```php +$schema = Expect::structure([ + 'user' => Expect::string()->required(), + 'password' => Expect::string(), // výchozí hodnota je null +]); + +$processor->process($schema, ['password' => 'secret']); +// CHYBA: The mandatory item 'user' is missing. + +$processor->process($schema, ['user' => 'admin']); +// OK, vrací {'user' => 'admin', 'password' => null} +``` + +Samotná struktura je povinná. Pokud je tedy vnořená v jiné struktuře a vstup ji neobsahuje, přesto se vytvoří - a ohlásí chybu ve chvíli, kdy obsahuje povinnou vlastnost. Pomocí `required(false)` učiníte celou vnořenou strukturu volitelnou. Když ve vstupu chybí, na výstupu bude `null`, ale pokud je přítomna, její povinné vlastnosti se vyžadují: + +```php +$schema = Expect::structure([ + 'database' => Expect::structure([ + 'user' => Expect::string()->required(), + ])->required(false), +]); + +$processor->process($schema, []); +// OK, vrací {'database' => null} + +$processor->process($schema, ['database' => []]); +// CHYBA: The mandatory item 'database › user' is missing. +``` + +Pokud nechcete mít na výstupu vlastnosti s výchozí hodnotou, použijte `skipDefaults()`: + +```php +$schema = Expect::structure([ + 'user' => Expect::string()->required(), + 'password' => Expect::string(), +])->skipDefaults(); + +$processor->process($schema, ['user' => 'admin']); +// OK, vrací {'user' => 'admin'} +``` + +Pole všech vlastností struktury vrací metoda `getShape()`. + +Ve výchozím nastavení nemohou být ve vstupních datech žádné položky navíc. Právě tak se odhalí překlep v klíči: + +```php +$schema = Expect::structure([ + 'host' => Expect::string(), +]); + +$processor->process($schema, ['hots' => 'localhost']); +// CHYBA: Unexpected item 'hots', did you mean 'host'? +``` + +Což můžeme změnit pomocí `otherItems()`. Jako parametr uvedeme schéma, podle kterého se budou prvky navíc validovat: + +```php +$schema = Expect::structure([ + 'host' => Expect::string(), +])->otherItems(Expect::int()); + +$processor->process($schema, ['timeout' => 30]); // OK +$processor->process($schema, ['timeout' => true]); // CHYBA +``` + +Novou strukturu můžete vytvořit odvozením od jiné pomocí `extend()`: + +```php +$database = Expect::structure([ + 'host' => Expect::string('localhost'), + 'port' => Expect::int(3306), +]); + +$replica = $database->extend([ + 'readOnly' => Expect::bool(true), +]); +``` + + +Pole .{data-version:1.3.2} +========================== + +Pole s definovanými klíči. Platí pro něj vše, co pro [#struktury]. + +```php +$schema = Expect::array([ + 'user' => Expect::string()->required(), + 'password' => Expect::string(), // výchozí hodnota je null +]); +``` + + +Tuple: tuple() .{data-version:1.4.0} +==================================== + +Tuple je pole pevné velikosti, v němž má každá pozice své vlastní schéma: + +```php +$schema = Expect::tuple([ + Expect::int(), + Expect::string(), + Expect::bool(), +]); + +$processor->process($schema, [1, 'hello', true]); // OK +``` + +Vstupem musí být list, takže pozice zadané klíči nebo v jiném pořadí se odmítnou. Když je vstup kratší, chybějící pozice se chovají jako chybějící položky struktury: dostanou výchozí hodnotu, nebo nahlásí chybu, pokud jsou `required()`. Metoda `otherItems()` dovolí, aby za definovanými pozicemi následovaly další položky, a určí schéma, kterému musí odpovídat, kdežto `extend()` přidá na konec další pozice. + +Když se konfigurace skládají ve vrstvách, pozdější tuple nahradí ten dřívější celý, protože smíchat pozice dvou různých tuplů by dalo jen nesmysl. + +Na rozdíl od struktury nepřijímá tuple `null` jako prázdnou hodnotu; pokud je `null` platnou hodnotou, zavolejte `nullable()`. + + +Zastaralé položky: deprecated() +=============================== + +Když konfigurační volbu přejmenujete nebo zrušíte, ta stará může ještě chvíli fungovat a upozorňovat své uživatele. Označte ji pomocí `deprecated([string $message])`. Upozornění vrací `$processor->getWarnings()`: + +```php +$schema = Expect::structure([ + 'server' => Expect::string()->deprecated('The item %path% is deprecated, use host'), + 'host' => Expect::string(), +]); + +$processor->process($schema, ['server' => 'localhost']); // OK +$processor->getWarnings(); // ["The item 'server' is deprecated, use host"] +``` + + +Popis: description() .{data-version:1.4.0} +========================================== + +Každému prvku můžete přidat lidsky čitelný popis. Na validaci nemá vliv, jenže schéma bývá jediné místo, kde je význam konfigurační volby vůbec zapsaný, a `description()` vám ho dovolí napsat přímo tam. Popis se také propíše do [exportu do JSON Schema |json-schema]: + +```php +$schema = Expect::structure([ + 'host' => Expect::string('localhost')->description('Database server hostname'), + 'port' => Expect::int(3306)->description('Port the server listens on'), +])->description('Database connection'); +``` + +{{maintitle: Datové typy Nette Schema: struktury, listy, enumy, tuply}} +{{description: Všechny prvky Nette Schema: typy, rozsahy, regulární výrazy, pole a listy, enumy, struktury a tuply, s výchozími a povinnými položkami a popisy.}} diff --git a/schema/en/@home.texy b/schema/en/@home.texy index 0cc596b943..296199b29f 100644 --- a/schema/en/@home.texy +++ b/schema/en/@home.texy @@ -1,808 +1,181 @@ Nette Schema ************ -.[perex] -A practical library for validating and normalizing data structures against a given schema with a smart, easy-to-understand API. +
-Installation: +Does your application read a configuration file, or accept data from an API? Before your code touches such data, it should check that the data has the shape you expect. Nette Schema does it for you: -```shell -composer require nette/schema -``` +- You describe the expected data in a few lines of readable PHP code +- It reports every mistake at once, with the path to the item +- It fills in default values, converts values and maps them to your objects +- It merges configuration from several files according to the schema +- It exports the schema to JSON Schema, so editors can offer completion +
-Basic Usage ------------ -In the variable `$schema`, we have a validation schema (we'll explain what this means and how to create one in a moment), and in the variable `$data`, we have the data structure we want to validate and normalize. This could be, for example, data submitted by a user via an API, a configuration file, etc. +Installation +============ -The task is handled by the [api:Nette\Schema\Processor] class, which processes the input and either returns normalized data or throws a [api:Nette\Schema\ValidationException] exception if an error occurs. - -```php -$processor = new Nette\Schema\Processor; +Download and install the package using [Composer|best-practices:composer]: -try { - $normalized = $processor->process($schema, $data); -} catch (Nette\Schema\ValidationException $e) { - echo 'Data is invalid: ' . $e->getMessage(); -} +```shell +composer require nette/schema ``` -The method `$e->getMessages()` returns an array of all messages as strings, and `$e->getMessageObjects()` returns all messages as "Nette\Schema\Message":https://api.nette.org/schema/master/Nette/Schema/Message.html objects. +Your First Schema +================= -Defining the Schema -------------------- - -And now let's create the schema. The class [api:Nette\Schema\Expect] is used to define it; we essentially define expectations for what the data should look like. Let's say the input data must be a structure (e.g., an array) containing elements `processRefund` of type bool and `refundAmount` of type int. - -```php -use Nette\Schema\Expect; - -$schema = Expect::structure([ - 'processRefund' => Expect::bool(), - 'refundAmount' => Expect::int(), -]); -``` - -We believe the schema definition looks understandable, even if you're seeing it for the first time. - -Let's send the following data for validation: +The easiest way to show it is with an example. Let's say your application connects to a database and reads the connection settings from a configuration file. Once loaded, the configuration is an ordinary PHP array, for example: ```php $data = [ - 'processRefund' => true, - 'refundAmount' => 17, + 'user' => 'admin', + 'port' => 5432, ]; - -$normalized = $processor->process($schema, $data); // OK, passes validation ``` -The output, i.e., the value `$normalized`, is a `stdClass` object. If we wanted the output to be an array, we would add casting `->castTo('array')` to the schema. - -All elements of the structure are optional and have a default value of `null`. Example: +Nothing guarantees that the file contains what your code needs. Someone may misspell a key, write the port as text or forget the user name altogether. So we describe what the data should look like. This description is the **schema**, and the class [api:Nette\Schema\Expect] builds it: ```php -$data = [ - 'refundAmount' => 17, -]; - -$normalized = $processor->process($schema, $data); // OK, passes validation -// $normalized = {'processRefund' => null, 'refundAmount' => 17} -``` - -The fact that the default value is `null` does not mean it would accept `'processRefund' => null` in the input data. No, the input must be a boolean, i.e. `true` or `false` only. We would have to explicitly allow `null` using `Expect::bool()->nullable()`. - -An item can be made mandatory using `Expect::bool()->required()`. We can change the default value, for example, to `false` using `Expect::bool()->default(false)` or shorthand `Expect::bool(false)`. - -And what if we wanted to accept `1` and `0` in addition to booleans? Then we list the values that we also want to normalize to boolean: +use Nette\Schema\Expect; -```php $schema = Expect::structure([ - 'processRefund' => Expect::anyOf(true, false, 1, 0)->castTo('bool'), - 'refundAmount' => Expect::int(), + 'host' => Expect::string('localhost'), + 'port' => Expect::int(3306), + 'user' => Expect::string()->required(), + 'password' => Expect::string()->nullable(), ]); - -$normalized = $processor->process($schema, $data); -is_bool($normalized->processRefund); // true -``` - -Now you know the basics of defining a schema and how the structure items behave. We will now show what other elements you can use when defining a schema. - - -Data Types: type() ------------------- - -All standard PHP data types can be specified in the schema: - -```php -Expect::string($default = null) -Expect::int($default = null) -Expect::float($default = null) -Expect::bool($default = null) -Expect::null() -Expect::array($default = []) -Expect::list($default = []) ``` -And also all types [supported by the Validators class |utils:validators#Expected Types], for example `Expect::type('scalar')` or shorthand `Expect::scalar()`. Also class or interface names, e.g., `Expect::type('AddressEntity')`. +It reads almost like a sentence. The data is a structure with four items: `host` is a string, `localhost` when not given; `port` is an integer, 3306 by default; `user` is a string that must be given; and `password` is a string that may also be `null`. -Union syntax can also be used: +Now we let the [api:Nette\Schema\Processor] check the data against the schema: ```php -Expect::type('bool|string|array') -``` - -The default value is always `null` with the exception of `array` and `list`, where it is an empty array. (A list is an array indexed by a sequence of numeric keys starting from zero, i.e. a non-associative array). - -In 1.x, the type `'?int[]'` means an array whose items are integers or `null`. Version 2.0 will read it the way phpDoc does, as an array of integers or `null` in place of the whole array, so using it raises an `E_USER_DEPRECATED` notice. To keep the current meaning, write `Expect::arrayOf(Expect::type('int')->nullable())`. .{data-version:1.4.0} - - -Array of Values: arrayOf() listOf() ------------------------------------ - -An array represents too general a structure; it's more useful to specify precisely which elements it may contain. For example, an array whose elements can only be strings: - -```php -$schema = Expect::arrayOf('string'); - -$processor->process($schema, ['hello', 'world']); // OK -$processor->process($schema, ['a' => 'hello', 'b' => 'world']); // OK -$processor->process($schema, ['key' => 123]); // ERROR: 123 is not a string -``` - -The second parameter can specify keys (since version 1.2): - -```php -$schema = Expect::arrayOf('string', 'int'); +$processor = new Nette\Schema\Processor; +$config = $processor->process($schema, $data); -$processor->process($schema, ['hello', 'world']); // OK -$processor->process($schema, ['a' => 'hello']); // ERROR: 'a' is not an int +echo $config->host; // 'localhost' +echo $config->port; // 5432 ``` -A list is an indexed array: +The result is not the same array. It is a `stdClass` object with all four items: the missing `host` got its default value, and the missing `password` is `null`. Your code can rely on every item being there and having the right type. -```php -$schema = Expect::listOf('string'); -$processor->process($schema, ['a', 'b']); // OK -$processor->process($schema, ['a', 123]); // ERROR: 123 is not a string -$processor->process($schema, ['key' => 'a']); // ERROR: not a list -$processor->process($schema, [1 => 'a', 0 => 'b']); // ERROR: also not a list -``` +When the Data Is Wrong +====================== -With the `wrap` parameter, a single value is also accepted and wrapped into a one-item list: .{data-version:1.4.0} +And what if the configuration contains a mistake? Let's say the port is written as text and the user is missing: ```php -$schema = Expect::listOf('string', wrap: true); - -$processor->process($schema, 'hello'); // OK, gives ['hello'] -$processor->process($schema, ['a', 'b']); // OK -``` - -The parameter can also be a schema, so we can write: +$data = [ + 'port' => 'abc', +]; -```php -Expect::arrayOf(Expect::bool()) +try { + $config = $processor->process($schema, $data); +} catch (Nette\Schema\ValidationException $e) { + echo implode("\n", $e->getMessages()); +} ``` -The default value is an empty array. If you specify a default value, it will be merged with the passed data. This can be disabled using `mergeDefaults(false)` (since version 1.1). - - -Enumeration: anyOf() --------------------- - -`anyOf()` represents a set of values or schemas that a value can take. Here's how to write an array of elements that can be either `'a'`, `true`, or `null`: - -```php -$schema = Expect::listOf( - Expect::anyOf('a', true, null), -); - -$processor->process($schema, ['a', true, null, 'a']); // OK -$processor->process($schema, ['a', false]); // ERROR: false does not belong there ``` - -The elements of the enumeration can also be schemas: - -```php -$schema = Expect::listOf( - Expect::anyOf(Expect::string(), true, null), -); - -$processor->process($schema, ['foo', true, null, 'bar']); // OK -$processor->process($schema, [123]); // ERROR +The item 'port' expects to be int, 'abc' given. +The mandatory item 'user' is missing. ``` -The `anyOf()` method accepts variants as separate parameters, not as an array. To pass it an array of values, use the unpack operator `anyOf(...$variants)`. - -Variants are tried in the order they are written, and the first one that matches wins. The only exception is `null`: when the set accepts it, a `null` input always gives `null`, even if a structure or array variant listed earlier would otherwise turn it into an empty structure or array. - -The default value is `null`. Use the `firstIsDefault()` method to make the first item the default: +Notice that you get all the mistakes at once, not just the first one, and each message says which item it concerns. The user fixes the whole file in one go instead of running the application again and again. -```php -// default is 'hello' -Expect::anyOf(Expect::string('hello'), true, null)->firstIsDefault(); -``` +The method `getMessages()` returns the messages as strings. When you want to show them in your own way, `getMessageObjects()` returns objects that carry the path to the item and a code of the error as well. More on this in [Validation and Normalization |normalization#Errors]. -Enums: enum() .{data-version:1.4.0} ------------------------------------ +Describing the Data +=================== -A configuration file can only hold a plain string such as `'hearts'`, but in your code you would much rather work with an enum. `enum()` converts one into the other: give it a backed enum, i.e. one whose cases have values (`enum Suit: string`), and it accepts either the value or the case itself, and always gives you back the case: +A real configuration has more than four items. Let's put the database connection into a nested structure and add a list of administrators' e-mails, the mode the application runs in, and the date it goes live: ```php -enum Suit: string +enum Mode: string { - case Hearts = 'hearts'; - case Spades = 'spades'; + case Development = 'development'; + case Production = 'production'; } -$schema = Expect::enum(Suit::class); - -$processor->process($schema, 'hearts'); // OK, returns Suit::Hearts -$processor->process($schema, Suit::Spades); // OK, returns Suit::Spades -$processor->process($schema, 'clubs'); // ERROR: expects to be Suit -``` - -Enums backed by integers work exactly the same, and so does everything you know from the other elements, such as `Expect::enum(Suit::class)->required()` or `->default(Suit::Hearts)`. - -When [generating a schema from a class |#mapping-to-objects-from], a `public Suit $suit` property gives you this very element, so you do not have to reach for `enum()` there. `Expect::type(Suit::class)` is a different thing: like any class name, it accepts only an instance, i.e. the case itself. - - -Structures ----------- - -Structures are objects with defined keys. Each key-value pair is referred to as a "property". - -Structures accept arrays and objects and return `stdClass` objects. - -By default, all properties are optional and have a default value of `null`. You can define mandatory properties using `required()`: - -```php -$schema = Expect::structure([ - 'required' => Expect::string()->required(), - 'optional' => Expect::string(), // default value is null -]); - -$processor->process($schema, ['optional' => '']); -// ERROR: the mandatory item 'required' is missing - -$processor->process($schema, ['required' => 'foo']); -// OK, returns {'required' => 'foo', 'optional' => null} -``` - -A structure itself is mandatory. Therefore, if it is nested inside another structure and the input does not contain it, it is created anyway - and it reports an error when it contains a required property. Use `required(false)` to make the entire nested structure optional. If it is missing in the input, `null` appears in the output, but if it is present, its required properties are enforced: - -```php -$schema = Expect::structure([ - 'db' => Expect::structure([ - 'dsn' => Expect::string()->required(), - ])->required(false), -]); - -$processor->process($schema, []); -// OK, returns {'db' => null} - -$processor->process($schema, ['db' => []]); -// ERROR: 'db › dsn' is missing -``` - -If you do not want properties with default values in the output, use `skipDefaults()`: - -```php -$schema = Expect::structure([ - 'required' => Expect::string()->required(), - 'optional' => Expect::string(), -])->skipDefaults(); - -$processor->process($schema, ['required' => 'foo']); -// OK, returns {'required' => 'foo'} -``` - -Although `null` is the default value for the `optional` property, it is not allowed in input data (the value must be a string). Properties accepting `null` are defined using `nullable()`: - -```php -$schema = Expect::structure([ - 'optional' => Expect::string(), - 'nullable' => Expect::string()->nullable(), -]); - -$processor->process($schema, ['optional' => null]); -// ERROR: 'optional' expects to be string, null given. - -$processor->process($schema, ['nullable' => null]); -// OK, returns {'optional' => null, 'nullable' => null} -``` - -The array of all structure properties is returned by the `getShape()` method. - -By default, no additional items can be present in the input data: - -```php -$schema = Expect::structure([ - 'key' => Expect::string(), -]); - -$processor->process($schema, ['additional' => 1]); -// ERROR: Unexpected item 'additional' -``` - -This can be changed using `otherItems()`. As a parameter, pass the schema to validate each extra item: - -```php -$schema = Expect::structure([ - 'key' => Expect::string(), -])->otherItems(Expect::int()); - -$processor->process($schema, ['additional' => 1]); // OK -$processor->process($schema, ['additional' => true]); // ERROR -``` - -You can create a new structure by extending another using `extend()`: - -```php -$dog = Expect::structure([ - 'name' => Expect::string(), - 'age' => Expect::int(), -]); - -$dogWithBreed = $dog->extend([ - 'breed' => Expect::string(), -]); -``` - - -Array .{data-version:1.3.2} ---------------------------- - -An array with defined keys. Everything that applies to [#structures] applies to it. - -```php -$schema = Expect::array([ - 'required' => Expect::string()->required(), - 'optional' => Expect::string(), // default value is null -]); -``` - - -Tuples: tuple() .{data-version:1.4.0} -------------------------------------- - -A tuple is a fixed-size array where each position has its own schema: - -```php -$schema = Expect::tuple([ - Expect::int(), - Expect::string(), - Expect::bool(), -]); - -$processor->process($schema, [1, 'hello', true]); // OK -``` - -The input must be a list, so positions given by keys or in a different order are refused. When the input is shorter, the missing positions behave like missing items of a structure: they get their default value, or report an error when they are `required()`. `otherItems()` lets further items follow the defined positions and sets the schema they must match, while `extend()` adds more positions to the end. - -When configurations are layered, a later tuple replaces the earlier one as a whole, because mixing the positions of two different tuples would only produce nonsense. - -Unlike a structure, a tuple does not accept `null` as an empty value; call `nullable()` when `null` is a valid value. - - -Deprecated Properties ---------------------- - -You can mark a property as deprecated using the `deprecated([string $message])` method. Information about deprecation is returned using `$processor->getWarnings()`: - -```php $schema = Expect::structure([ - 'old' => Expect::int()->deprecated('The item %path% is deprecated'), + 'database' => Expect::structure([ + 'host' => Expect::string('localhost'), + 'port' => Expect::int(3306)->min(1)->max(65535), + 'user' => Expect::string()->required(), + ]), + 'admins' => Expect::listOf('email'), + 'mode' => Expect::enum(Mode::class)->default(Mode::Production), + 'launchDate' => Expect::string()->nullable()->castTo(DateTimeImmutable::class), ]); - -$processor->process($schema, ['old' => 1]); // OK -$processor->getWarnings(); // ["The item 'old' is deprecated"] ``` +Each item says exactly what it accepts. The port must be between 1 and 65535. `admins` is a list in which every item must be a valid e-mail address. `mode` accepts the string `'development'` or `'production'` from the file, and your code gets a case of the enum `Mode`. `launchDate` turns a string like `'2026-03-01'` into a `DateTimeImmutable` object. -Description: description() .{data-version:1.4.0} ------------------------------------------------- - -Any element can carry a human-readable description. It has no effect on validation, but the schema is often the only place where the meaning of a configuration option is written down at all, and `description()` lets you write it right there. The description also travels into the [JSON Schema export |#exporting-to-json-schema]: +All the data types and their options, from numbers and strings to structures and tuples, are described on the page [Data Types |types]. -```php -$schema = Expect::structure([ - 'host' => Expect::string('localhost')->description('Database server hostname'), - 'port' => Expect::int(3306)->description('Port the server listens on'), -])->description('Database connection'); -``` +Converting the Data +=================== -Ranges: min() max() -------------------- - -Use `min()` and `max()` to limit the count for arrays: +Validation is just one half. The other is turning the data into what your code works with best. Instead of a `stdClass`, you will probably want your own class. `Expect::from()` creates the schema straight from it, using the types of its properties: ```php -// array, at least 10 items, maximum 20 items -Expect::array()->min(10)->max(20); -``` - -For strings, they limit the length: - -```php -// string, at least 10 bytes long, maximum 20 bytes -Expect::string()->min(10)->max(20); -``` - -The length of a string is measured in bytes. To count characters of a UTF-8 string, use `Expect::unicode()`. - -For numbers, they limit the value: - -```php -// integer, between 10 and 20 inclusive -Expect::int()->min(10)->max(20); -``` - -Of course, it is possible to specify just `min()` or just `max()`: - -```php -// string, maximum 20 bytes -Expect::string()->max(20); -``` - -On a union such as `Expect::type('int|string')`, it is not clear whether `min()` and `max()` should limit the number or the length of the string, so they raise an `E_USER_DEPRECATED` notice there. Give the limits to each variant of [anyOf() |#enumeration-anyof] instead: .{data-version:1.4.0} - -```php -Expect::anyOf(Expect::int()->min(1), Expect::string()->min(1)); -``` - - -Regular Expressions: pattern() ------------------------------- - -Using `pattern()`, you can specify a regular expression that the **entire** input string must match (i.e. as if it were wrapped in `^` and `$` characters): - -```php -// exactly 9 digits -Expect::string()->pattern('\d{9}'); -``` - -A pattern only makes sense for a string. That is why `Expect::string()` returns a `StringType` element, while `Expect::int()` and `Expect::float()` return a `NumberType` and `Expect::listOf()` and the other array schemas an `ArrayType`, each offering the methods of its kind. Calling `pattern()` on a number or an array raises an `E_USER_DEPRECATED` notice, and your editor flags such a call as deprecated as soon as you write it. .{data-version:1.4.0} - - -Custom Assertions: assert() ---------------------------- - -You can add any other constraints using `assert(callable $fn)`. - -```php -$countIsEven = fn($v) => count($v) % 2 === 0; - -$schema = Expect::arrayOf('string') - ->assert($countIsEven); // the count must be even - -$processor->process($schema, ['a', 'b']); // OK -$processor->process($schema, ['a', 'b', 'c']); // ERROR: 3 is not an even count -``` - -Or - -```php -Expect::string()->assert('is_file'); // file must exist -``` - -You can add a custom description to each assertion. It will be part of the error message. - -```php -$schema = Expect::arrayOf('string') - ->assert($countIsEven, 'Even items in array'); - -$processor->process($schema, ['a', 'b', 'c']); -// Failed assertion "Even items in array" for item with value array. -``` - -The method can be called repeatedly to add multiple constraints. It can be interleaved with calls to `transform()` and `castTo()`. - - -Transformation: transform() .{data-version:1.2.5} -------------------------------------------------- - -Successfully validated data can be modified using a custom function: - -```php -// convert to uppercase: -Expect::string()->transform(fn(string $s) => strtoupper($s)); -``` - -The method can be called repeatedly to add multiple transformations. It can be interleaved with calls to `assert()` and `castTo()`. The operations are performed in the order in which they are declared: - -```php -Expect::type('string|int') - ->castTo('string') - ->assert('ctype_lower', 'All characters must be lowercased') - ->transform(fn(string $s) => strtoupper($s)); // convert to uppercase -``` - -The `transform()` method can simultaneously transform and validate the value. This is often simpler and involves less code duplication than chaining `transform()` and `assert()`. For this purpose, the function receives a [Context |api:Nette\Schema\Context] object with an `addError()` method, which can be used to add information about validation problems: - -```php -Expect::string() - ->transform(function (string $s, Nette\Schema\Context $context) { - if (!ctype_lower($s)) { - $context->addError('All characters must be lowercased', 'my.case.error'); - return null; - } - - return strtoupper($s); - }); -``` - - -Casting: castTo() ------------------ - -Successfully validated data can be cast: - -```php -Expect::scalar()->castTo('string'); -``` - -In addition to native PHP types, you can also cast to classes. It distinguishes between a simple class without a constructor and a class with a constructor. If the class has no constructor, an instance is created, and all structure elements are written to the properties: - -```php -class Info -{ - public bool $processRefund; - public int $refundAmount; -} - -Expect::structure([ - 'processRefund' => Expect::bool(), - 'refundAmount' => Expect::int(), -])->castTo(Info::class); - -// creates '$obj = new Info' and writes to $obj->processRefund and $obj->refundAmount -``` - -If the class has a constructor, the structure elements are passed as named arguments to the constructor: - -```php -class Info -{ - public function __construct( - public bool $processRefund, - public int $refundAmount, - ) { - } -} - -// creates $obj = new Info(processRefund: ..., refundAmount: ...) -``` - -Casting combined with a scalar parameter creates an object and passes the value as the single argument to the constructor: - -```php -Expect::string()->castTo(DateTime::class); -// creates new DateTime(...) -``` - -A `null` is never turned into an object. When the target is a class or an enum, `null` stays `null`, so an optional item that was left empty stays empty: .{data-version:1.4.0} - -```php -Expect::string()->nullable()->castTo(DateTime::class); -// '2026-01-01' becomes a DateTime, null stays null -``` - -With native types, add a question mark when `null` should pass unchanged: `castTo('?string')` keeps `null`, whereas `castTo('string')` turns it into an empty string. .{data-version:1.4.0} - - -Normalization: before() ------------------------ - -Before the validation itself, the data can be normalized using the `before()` method. As an example, let's take an element that must be an array of strings (e.g., `['a', 'b', 'c']`), but accepts input in the form of string `a b c`: - -```php -$explode = fn($v) => explode(' ', $v); - -$schema = Expect::arrayOf('string') - ->before($explode); - -$normalized = $processor->process($schema, 'a b c'); -// OK and returns ['a', 'b', 'c'] -``` - -An element has one handler, so a second call to `before()` replaces the first one. Put all the normalization into one handler instead. - -The second call also raises an `E_USER_DEPRECATED` notice, because in version 2.0 the handlers will be chained, each receiving the result of the previous one. .{data-version:1.4.0} - - -Mapping to Objects: from() --------------------------- - -You can have the structure schema generated from a class. Example: - -```php -class Config +class DatabaseConfig { - public string $name; - public string|null $password = null; - public bool $admin = false; -} - -$schema = Expect::from(new Config); - -$data = [ - 'name' => 'Frank', -]; - -$normalized = $processor->process($schema, $data); -// $normalized instanceof Config -// $normalized = {'name' => 'Frank', 'password' => null, 'admin' => false} -``` - -Anonymous classes are also supported: - -```php -$schema = Expect::from(new class { - public string $name; + public string $host = 'localhost'; + public int $port = 3306; + public string $user; public ?string $password = null; - public bool $admin = false; -}); -``` - -Because the information obtained from the class definition may not be sufficient, you can supplement the elements with your own schema using the second parameter: - -```php -$schema = Expect::from(new Config, [ - 'name' => Expect::string()->pattern('\w:.*'), -]); -``` - - -Merging Multiple Configurations -------------------------------- - -Applications often assemble their configuration in layers: there are built-in default values, and on top of them the user supplies their own settings, which should override only the items they actually specify. That is exactly what `processMultiple()` does - it takes several datasets, merges them in order so that later ones take precedence, and validates the final result as a whole: - -```php -$schema = Expect::structure([ - 'host' => Expect::string(), - 'port' => Expect::int(), - 'logging' => Expect::bool(), -]); - -$defaults = ['host' => 'localhost', 'port' => 3306, 'logging' => false]; -$userConfig = ['port' => 5432, 'logging' => true]; - -$config = $processor->processMultiple($schema, [$defaults, $userConfig]); -// $config = {'host' => 'localhost', 'port' => 5432, 'logging' => true} -``` - -The `host` item keeps its default value because the user did not set it, while `port` and `logging` are overwritten by the later dataset. Values stored under string keys are merged this way; the items of a list (`listOf()`, `arrayOf()`) are appended one after another instead of being overwritten. - -When appending or merging by keys is not what you want, arrays and structures can choose another strategy with `mergeMode()`: .{data-version:1.4.0} - -```php -use Nette\Schema\MergeMode; +} -Expect::arrayOf('string')->mergeMode(MergeMode::Replace); // the later array replaces the earlier one +$schema = Expect::from(new DatabaseConfig); +$config = $processor->process($schema, ['user' => 'admin']); // an instance of DatabaseConfig ``` -`MergeMode::AppendKeys` merges by keys and appends list items, `OverwriteKeys` also merges by keys but overwrites list items by their position, and `Replace` keeps only the later value. Without `mergeMode()`, an array whose items are not described, such as `Expect::array()`, is merged deeply. +Besides that, you can adjust a value before it is validated with `before()`, change it afterwards with `transform()`, cast it to another type with `castTo()` and add your own checks with `assert()`. All of that is on the page [Validation and Normalization |normalization]. -For anything else, `mergeWith()` takes your own function that combines the later value with the earlier one: .{data-version:1.4.0} - -```php -Expect::bool()->mergeWith(fn($value, $base) => $value || $base); // once enabled, stays enabled -``` +Configuration in Layers +======================= -Exporting to JSON Schema .{data-version:1.4.0} ----------------------------------------------- - -Your schema is already a precise description of what the configuration may contain, and that description is useful outside PHP as well. `JsonSchema::export()` turns it into a "JSON Schema":https://json-schema.org document, the format editors read to offer completion and underline mistakes directly in the JSON or YAML file: +Applications often assemble their configuration from several sources: built-in defaults, a shared configuration file and a local file of each developer, where each one overrides only the items it mentions. The method `processMultiple()` merges them in order and validates the result as a whole: ```php -use Nette\Schema\JsonSchema; +$defaults = ['host' => 'localhost', 'port' => 3306]; +$local = ['user' => 'admin', 'port' => 5432]; -$schema = Expect::structure([ - 'host' => Expect::string('localhost')->description('Database server hostname'), - 'port' => Expect::int(3306)->min(1)->max(65535), - 'user' => Expect::string()->required(), -]); - -echo json_encode(JsonSchema::export($schema), JSON_PRETTY_PRINT); -``` - -```json -{ - "type": "object", - "properties": { - "host": {"type": "string", "description": "Database server hostname"}, - "port": {"type": "integer", "minimum": 1, "maximum": 65535}, - "user": {"type": "string"} - }, - "required": ["user"], - "additionalProperties": false -} +$config = $processor->processMultiple($schema, [$defaults, $local]); ``` -The export describes the **shape** of the data: types, ranges, patterns, required items, enum values and the texts you added with `description()`. Default values, `castTo()` and `transform()` are deliberately left out, because they describe what happens to the data after validation, and JSON Schema has no way to say that. - -A type that exists only in PHP, such as a class (`Expect::type(Address::class)`), a callable or a resource, cannot be exported at all. Instead of producing a document that would quietly describe something else, the export throws `Nette\NotSupportedException`. - -Two differences remain between the export and the validation. JSON Schema counts the length of a string in characters, while `Expect::string()` counts bytes, so use `Expect::unicode()` for text that is not plain ASCII. And a `pattern()` is exported as it is, but a JSON Schema validator reads it as an ECMAScript regular expression, so constructions specific to PCRE may be understood differently there. - +The schema decides how the layers are combined, for example the items of a list are appended one after another. How that works is described in [Merging Configurations |merging]. -Under the Hood: normalize, merge, complete ------------------------------------------- -Every schema element - whether built-in or one you write yourself - implements four methods that together define how it handles data. Three of them form the processing pipeline: +JSON Schema for Your Editor +=========================== -1. **normalize()** - prepares the raw input. This is where `before()` hooks run and where, for example, an object is turned into an array. It runs first, separately on each dataset. -2. **merge()** - combines two already normalized datasets, with the later one taking priority. This step is used only by `processMultiple()`; `process()` skips it, because it has just a single dataset. -3. **complete()** - performs the actual validation, fills in default values for missing items, and applies `assert()`, `transform()` and `castTo()`. It runs last, on the merged result. +Your schema is already a precise description of what the configuration may contain. `Nette\Schema\JsonSchema::export()` turns it into a JSON Schema document, which editors read to offer completion and underline mistakes right in the configuration file. See [Exporting to JSON Schema |json-schema]. -The fourth method, **completeDefault()**, is called by the parent element for an item entirely missing from the input - it either supplies the default value or reports that a `required()` item is missing. -So `process()` runs *normalize → complete*, while `processMultiple()` runs *normalize (each dataset) → merge → complete*. This order is why `before()` sees the raw input, whereas `transform()` sees the already validated value. +Nette Schema in Nette Applications +================================== +You use the library even when you don't call it yourself: every extension of the [DI container |dependency-injection:] describes its configuration section with a schema in the method [getConfigSchema() |dependency-injection:extensions#getConfigSchema]. That is why a typo in the configuration of your application is reported with a clear message. -Custom Schema Elements ----------------------- -You can get a long way with `assert()`, `transform()` and `before()`, so you rarely need to build anything from scratch. But when you want a reusable, self-contained element with its own validation and merging logic, you can create one by implementing the [api:Nette\Schema\Schema] interface. It has exactly the four methods described above: - -```php -interface Schema -{ - function normalize(mixed $value, Context $context); - function merge(mixed $value, mixed $base); - function complete(mixed $value, Context $context); - function completeDefault(Context $context); -} -``` - -Errors are not thrown; instead you report them through the [Context |api:Nette\Schema\Context] object using `$context->addError()` and return `null`. The `Processor` gathers all errors and throws them together at the end. - -As an example, let's build a reusable element for sizes written the way people like to write them in configuration files, such as `'512kB'` or `'2 MB'`. It validates them and returns the number of bytes: - -```php -use Nette\Schema\Context; -use Nette\Schema\Schema; - -class ByteSizeSchema implements Schema -{ - private const Units = ['b' => 1, 'kb' => 1024, 'mb' => 1024 ** 2, 'gb' => 1024 ** 3]; - - public function normalize(mixed $value, Context $context): mixed - { - return is_int($value) ? "$value B" : $value; // unify both notations - } - - public function merge(mixed $value, mixed $base): mixed - { - return $value ?? $base; // the later value wins - } - - public function complete(mixed $value, Context $context): mixed - { - if (!is_string($value) || !preg_match('~^(\d+)\s*([a-zA-Z]+)$~', $value, $m)) { - $context->addError("The item %path% expects to be a size like '512kB'.", 'size.format'); - return null; - } - - $unit = self::Units[strtolower($m[2])] ?? null; - if ($unit === null) { - $context->addError("The item %path% uses an unknown unit '$m[2]'.", 'size.unit'); - return null; - } - - return (int) $m[1] * $unit; - } - - public function completeDefault(Context $context): mixed - { - return null; // value used when the item is missing from the input - } -} -``` - -You can use it anywhere a built-in element is expected - on its own or as part of a larger structure: - -```php -$schema = Expect::structure([ - 'maxUpload' => new ByteSizeSchema, - 'diskQuota' => new ByteSizeSchema, -]); - -$processor->process($schema, ['maxUpload' => '2 MB', 'diskQuota' => 512]); -// OK, returns {'maxUpload' => 2097152, 'diskQuota' => 512} - -$processor->process($schema, ['maxUpload' => '5 TB']); -// ERROR: The item 'maxUpload' uses an unknown unit 'TB'. -``` +What's Next +=========== -Because the element implements the whole interface, it also works automatically inside `processMultiple()` - the `Processor` calls its `merge()` method just like for any other element. Only `JsonSchema::export()` cannot know what such an element accepts, so it throws `Nette\NotSupportedException`. +- [Data Types |types] - every element of a schema and its options +- [Validation and Normalization |normalization] - custom checks, transformations, casting and mapping to objects +- [Merging Configurations |merging] - combining configuration layers +- [Exporting to JSON Schema |json-schema] - completion and checking of configuration in editors +- [Custom Elements |custom-elements] - how processing works and how to write your own element {{maintitle: Nette Schema: Validate and Normalize Data Structures in PHP}} {{description: A practical PHP library for validating and normalizing data against a schema with a smart, easy-to-understand API. Great for configuration and API inputs.}} diff --git a/schema/en/@left-menu.texy b/schema/en/@left-menu.texy index 8cbad6d4d5..5c81ccd39e 100644 --- a/schema/en/@left-menu.texy +++ b/schema/en/@left-menu.texy @@ -1,6 +1,11 @@ Nette Schema ************ - [Overview |@home] +- [Data Types |types] +- [Validation and Normalization |normalization] +- [Merging Configurations |merging] +- [Exporting to JSON Schema |json-schema] +- [Custom Elements |custom-elements] Further Reading diff --git a/schema/en/custom-elements.texy b/schema/en/custom-elements.texy new file mode 100644 index 0000000000..be600c7dad --- /dev/null +++ b/schema/en/custom-elements.texy @@ -0,0 +1,111 @@ +Custom Elements +*************** + +
+ +You can get a long way with `assert()`, `transform()` and `before()`, so you rarely need to build anything from scratch. But when you want a reusable, self-contained element with its own validation and merging logic, you can write one. This page explains: + +- how the processor handles data, step by step +- the interface every element implements +- how to write and use your own element + +
+ + +How Processing Works +==================== + +Every schema element - whether built-in or one you write yourself - implements four methods that together define how it handles data. Three of them form the processing pipeline: + +1. **normalize()** - prepares the raw input. This is where `before()` hooks run and where, for example, an object is turned into an array. It runs first, separately on each dataset. +2. **merge()** - combines two already normalized datasets, with the later one taking priority. This step is used only by `processMultiple()`; `process()` skips it, because it has just a single dataset. +3. **complete()** - performs the actual validation, fills in default values for missing items, and applies `assert()`, `transform()` and `castTo()`. It runs last, on the merged result. + +The fourth method, **completeDefault()**, is called by the parent element for an item entirely missing from the input - it either supplies the default value or reports that a `required()` item is missing. + +So `process()` runs *normalize → complete*, while `processMultiple()` runs *normalize (each dataset) → merge → complete*. This order is why `before()` sees the raw input, whereas `transform()` sees the already validated value. + + +The Schema Interface +==================== + +To create your own element, implement the [api:Nette\Schema\Schema] interface. It has exactly the four methods described above: + +```php +interface Schema +{ + function normalize(mixed $value, Context $context); + function merge(mixed $value, mixed $base); + function complete(mixed $value, Context $context); + function completeDefault(Context $context); +} +``` + +Errors are not thrown; instead you report them through the [Context |api:Nette\Schema\Context] object using `$context->addError()` and return `null`. The `Processor` gathers all errors and throws them together at the end. + + +Example: Sizes in Bytes +======================= + +As an example, let's build a reusable element for sizes written the way people like to write them in configuration files, such as `'512kB'` or `'2 MB'`. It validates them and returns the number of bytes: + +```php +use Nette\Schema\Context; +use Nette\Schema\Schema; + +class ByteSizeSchema implements Schema +{ + private const Units = ['b' => 1, 'kb' => 1024, 'mb' => 1024 ** 2, 'gb' => 1024 ** 3]; + + public function normalize(mixed $value, Context $context): mixed + { + return is_int($value) ? "$value B" : $value; // unify both notations + } + + public function merge(mixed $value, mixed $base): mixed + { + return $value ?? $base; // the later value wins + } + + public function complete(mixed $value, Context $context): mixed + { + if (!is_string($value) || !preg_match('~^(\d+)\s*([a-zA-Z]+)$~', $value, $m)) { + $context->addError("The item %path% expects to be a size like '512kB'.", 'size.format'); + return null; + } + + $unit = self::Units[strtolower($m[2])] ?? null; + if ($unit === null) { + $context->addError("The item %path% uses an unknown unit '$m[2]'.", 'size.unit'); + return null; + } + + return (int) $m[1] * $unit; + } + + public function completeDefault(Context $context): mixed + { + return null; // value used when the item is missing from the input + } +} +``` + +You can use it anywhere a built-in element is expected - on its own or as part of a larger structure: + +```php +$schema = Expect::structure([ + 'maxUpload' => new ByteSizeSchema, + 'diskQuota' => new ByteSizeSchema, +]); + +$processor->process($schema, ['maxUpload' => '2 MB', 'diskQuota' => 512]); +// OK, returns {'maxUpload' => 2097152, 'diskQuota' => 512} + +$processor->process($schema, ['maxUpload' => '5 TB']); +// ERROR: The item 'maxUpload' uses an unknown unit 'TB'. +``` + +Because the element implements the whole interface, it also works automatically inside `processMultiple()` - the `Processor` calls its `merge()` method just like for any other element. Only [JsonSchema::export() |json-schema] cannot know what such an element accepts, so it throws `Nette\NotSupportedException`. + +{{maintitle: Nette Schema: How Processing Works and Custom Elements}} +{{description: See how Nette Schema normalizes, merges and completes data, and write a reusable custom element with its own validation and merging logic.}} diff --git a/schema/en/json-schema.texy b/schema/en/json-schema.texy new file mode 100644 index 0000000000..79479ac28c --- /dev/null +++ b/schema/en/json-schema.texy @@ -0,0 +1,65 @@ +Exporting to JSON Schema +************************ + +
+ +Your schema is already a precise description of what the configuration may contain, and that description is useful outside PHP as well. Exported to JSON Schema, it lets editors: + +- offer completion of keys and values right in the configuration file +- underline mistakes before the application even runs +- show the descriptions of the options as hints + +
+ + +Export .{data-version:1.4.0} +============================ + +`JsonSchema::export()` turns your schema into a "JSON Schema":https://json-schema.org document, the format editors read to offer completion and underline mistakes directly in the JSON or YAML file: + +```php +use Nette\Schema\Expect; +use Nette\Schema\JsonSchema; + +$schema = Expect::structure([ + 'host' => Expect::string('localhost')->description('Database server hostname'), + 'port' => Expect::int(3306)->min(1)->max(65535), + 'user' => Expect::string()->required(), +]); + +echo json_encode(JsonSchema::export($schema), JSON_PRETTY_PRINT); +``` + +```json +{ + "type": "object", + "properties": { + "host": {"type": "string", "description": "Database server hostname"}, + "port": {"type": "integer", "minimum": 1, "maximum": 65535}, + "user": {"type": "string"} + }, + "required": ["user"], + "additionalProperties": false +} +``` + +Save the result into a file and point your editor to it; how exactly depends on the editor and the format of the configuration file. + + +What the Export Contains +======================== + +The export describes the **shape** of the data: types, ranges, patterns, required items, enum values and the texts you added with [description() |types#Description: description()]. + +Default values, `castTo()` and `transform()` are deliberately left out, because they describe what happens to the data after validation, and JSON Schema has no way to say that. + +A type that exists only in PHP, such as a class (`Expect::type(Address::class)`), a callable or a resource, cannot be exported at all. Instead of producing a document that would quietly describe something else, the export throws `Nette\NotSupportedException`. The same goes for a [custom element |custom-elements], whose rules the export cannot know. + + +Differences from Validation +=========================== + +Two differences remain between the export and the validation. JSON Schema counts the length of a string in characters, while `Expect::string()` counts bytes, so use `Expect::unicode()` for text that is not plain ASCII. And a `pattern()` is exported as it is, but a JSON Schema validator reads it as an ECMAScript regular expression, so constructions specific to PCRE may be understood differently there. + +{{maintitle: Nette Schema: Export to JSON Schema for Editor Completion}} +{{description: Export a Nette Schema to JSON Schema, so editors offer completion and underline mistakes in configuration files. What the export contains and where it differs.}} diff --git a/schema/en/merging.texy b/schema/en/merging.texy new file mode 100644 index 0000000000..30fff7d4c4 --- /dev/null +++ b/schema/en/merging.texy @@ -0,0 +1,117 @@ +Merging Configurations +********************** + +
+ +Applications often assemble their configuration from several layers: built-in defaults, a configuration file shared by the team and a local file of each developer. Each layer overrides only the items it mentions. This page shows: + +- how `processMultiple()` merges the layers and validates the result +- how structures, arrays and lists are combined +- how to choose another strategy with `mergeMode()` or your own function +- how arrays without described items are merged + +
+ +The examples continue the configuration of an application from the [overview |@home]. `$processor` is an instance of `Nette\Schema\Processor`. + + +Merging Layers: processMultiple() +================================= + +The method `processMultiple()` takes several datasets, merges them in order so that later ones take precedence, and validates the final result as a whole: + +```php +$schema = Expect::structure([ + 'host' => Expect::string(), + 'port' => Expect::int(), + 'logging' => Expect::bool(), +]); + +$defaults = ['host' => 'localhost', 'port' => 3306, 'logging' => false]; +$local = ['port' => 5432, 'logging' => true]; + +$config = $processor->processMultiple($schema, [$defaults, $local]); +// $config = {'host' => 'localhost', 'port' => 5432, 'logging' => true} +``` + +The `host` item keeps its default value because the local file did not set it, while `port` and `logging` are overwritten by the later dataset. + +Notice that the result is validated only once, after merging. A layer on its own may be incomplete, for example the defaults usually lack the password, and only the merged configuration must contain everything that is required. + + +How Values Are Combined +======================= + +The schema decides how two layers are combined: + +- a simple value, such as a string or a number, is replaced by the later one +- a structure and an array with string keys are merged by keys, recursively according to the schemas of their items +- the items of a list (`listOf()`, or `arrayOf()` with numeric keys) are appended one after another +- a [tuple |types#Tuples: tuple()] is replaced as a whole, because mixing the positions of two tuples would only produce nonsense + +So with `'admins' => Expect::listOf('email')`, the administrators from the local file are added to those from the shared one: + +```php +$schema = Expect::structure([ + 'admins' => Expect::listOf('email'), +]); + +$config = $processor->processMultiple($schema, [ + ['admins' => ['jim@example.com']], + ['admins' => ['ann@example.com']], +]); +// $config->admins = ['jim@example.com', 'ann@example.com'] +``` + +The default value of an array is merged with the layers as well: its items stay unless a layer overrides them, and the items of the layers are appended to a list. To turn this off, call [mergeDefaults(false) |types#Arrays and Lists: arrayOf() listOf()]. + + +Choosing a Strategy: mergeMode() .{data-version:1.4.0} +====================================================== + +When appending or merging by keys is not what you want, arrays and structures can choose another strategy with `mergeMode()`. Let's say the local file should replace the list of administrators instead of adding to it: + +```php +use Nette\Schema\MergeMode; + +Expect::listOf('email')->mergeMode(MergeMode::Replace); // the later list replaces the earlier one +``` + +`MergeMode::AppendKeys` merges by keys and appends list items, `OverwriteKeys` also merges by keys but overwrites list items by their position, and `Replace` keeps only the later value. + +In a NEON configuration file of a Nette application, an exclamation mark after a key, `admins!:`, prevents the merging of that one item, see [configuration of the DI container |dependency-injection:configuration#Merging]. + + +Arrays Without Described Items +============================== + +An array whose items are not described, such as `Expect::array()`, is merged deeply, key by key at every level: + +```php +$schema = Expect::structure([ + 'options' => Expect::array(), +]); + +$processor->processMultiple($schema, [ + ['options' => ['cache' => ['ttl' => 60]]], + ['options' => ['cache' => ['ttl' => 3600]]], +]); +// OK, returns {'options' => ['cache' => ['ttl' => 3600]]} +``` + +Keep in mind that the schema then cannot check what the arrays contain. To let the later layer replace the array as a whole, choose `mergeMode(MergeMode::Replace)`. + + +Your Own Function: mergeWith() .{data-version:1.4.0} +==================================================== + +For anything else, `mergeWith()` takes your own function that combines the later value with the earlier one. Let's say logging should stay on once any layer turns it on: + +```php +Expect::bool()->mergeWith(fn($value, $base) => $value || $base); // once enabled, stays enabled +``` + +The function only combines layers; to adjust the shape of a single layer, use [before() |normalization#Normalization: before()]. + +{{maintitle: Nette Schema: Merging Configuration Files in PHP}} +{{description: Merge configuration from defaults, shared and local files with Nette Schema. See how structures, arrays and lists are combined and how to choose a strategy.}} diff --git a/schema/en/normalization.texy b/schema/en/normalization.texy new file mode 100644 index 0000000000..c17b182423 --- /dev/null +++ b/schema/en/normalization.texy @@ -0,0 +1,245 @@ +Validation and Normalization +**************************** + +
+ +Checking types is often not enough. Data from a configuration file or an API needs further checks and adjustments before your code can use it. This page shows how to: + +- add your own checks with `assert()` +- adjust a value before validation with `before()` and after it with `transform()` +- cast a value to another type or a class with `castTo()` +- build a schema from a class with `from()` +- work with errors and warnings + +
+ +The examples continue the configuration of an application from the [overview |@home]. `$processor` is an instance of `Nette\Schema\Processor`. + + +Order of Operations +=================== + +It helps to know when each step runs. First, the handler of `before()` adjusts the raw input. Then the value is validated against the element: its type, ranges, pattern and so on. Only a valid value continues to `assert()`, `transform()` and `castTo()`, which run in the order in which you declared them. That is why `before()` sees the input as it came, while `transform()` gets a value whose type is already checked. + +A more detailed look at the processing, including merging of several datasets, is on the page [Custom Elements |custom-elements#How Processing Works]. + + +Custom Checks: assert() +======================= + +You can add any other constraints using `assert(callable $fn)`. The function gets the value and returns `true` when it is valid. Let's say the list of administrators must not contain the same e-mail twice: + +```php +$isUnique = fn(array $list) => count($list) === count(array_unique($list)); + +$schema = Expect::listOf('email') + ->assert($isUnique); // each e-mail only once + +$processor->process($schema, ['jim@example.com', 'ann@example.com']); // OK +$processor->process($schema, ['jim@example.com', 'jim@example.com']); +// ERROR: Failed assertion #0 for item with value array. +``` + +Any function will do, including a built-in one: + +```php +Expect::string()->assert('is_dir'); // the directory must exist +``` + +The message above does not say much. Give the assertion a description and it becomes part of the error message: + +```php +$schema = Expect::listOf('email') + ->assert($isUnique, 'Unique e-mails'); + +$processor->process($schema, ['jim@example.com', 'jim@example.com']); +// ERROR: Failed assertion 'Unique e-mails' for item with value array. +``` + +The method can be called repeatedly to add multiple constraints. It can be interleaved with calls to `transform()` and `castTo()`. + + +Transformation: transform() .{data-version:1.2.5} +================================================= + +Successfully validated data can be modified using a custom function. Let's say the base URL of the application should never end with a slash: + +```php +Expect::string()->transform(fn(string $url) => rtrim($url, '/')); +``` + +The method can be called repeatedly to add multiple transformations. It can be interleaved with calls to `assert()` and `castTo()`. The operations are performed in the order in which they are declared: + +```php +Expect::string() + ->transform(fn(string $s) => strtolower(trim($s))) // ' Admin ' becomes 'admin' + ->assert('ctype_alnum', 'Only letters and digits'); +``` + +The `transform()` method can simultaneously transform and validate the value. This is often simpler and involves less code duplication than chaining `transform()` and `assert()`. For this purpose, the function receives a [Context |api:Nette\Schema\Context] object with an `addError()` method, which can be used to add information about validation problems. Let's turn a server written as `'db.example.com:5432'` into a host and a port: + +```php +Expect::string() + ->transform(function (string $s, Nette\Schema\Context $context) { + if (!preg_match('~^([^:]+):(\d+)$~', $s, $m)) { + $context->addError('The item %path% expects to be host:port.', 'server.format'); + return null; + } + + return ['host' => $m[1], 'port' => (int) $m[2]]; + }); +``` + + +Casting: castTo() +================= + +Successfully validated data can be cast: + +```php +Expect::scalar()->castTo('string'); +``` + +In addition to native PHP types, you can also cast to classes. It distinguishes between a simple class without a constructor and a class with a constructor. If the class has no constructor, an instance is created, and all structure elements are written to the properties: + +```php +class DatabaseConfig +{ + public string $host; + public int $port; +} + +Expect::structure([ + 'host' => Expect::string('localhost'), + 'port' => Expect::int(3306), +])->castTo(DatabaseConfig::class); + +// creates '$obj = new DatabaseConfig' and writes to $obj->host and $obj->port +``` + +If the class has a constructor, the structure elements are passed as named arguments to the constructor: + +```php +class DatabaseConfig +{ + public function __construct( + public string $host, + public int $port, + ) { + } +} + +// creates $obj = new DatabaseConfig(host: ..., port: ...) +``` + +Casting combined with a scalar parameter creates an object and passes the value as the single argument to the constructor: + +```php +Expect::string()->castTo(DateTime::class); +// creates new DateTime(...) +``` + +A `null` is never turned into an object. When the target is a class or an enum, `null` stays `null`, so an optional item that was left empty stays empty: .{data-version:1.4.0} + +```php +Expect::string()->nullable()->castTo(DateTime::class); +// '2026-01-01' becomes a DateTime, null stays null +``` + +With native types, add a question mark when `null` should pass unchanged: `castTo('?string')` keeps `null`, whereas `castTo('string')` turns it into an empty string. .{data-version:1.4.0} + + +Normalization: before() +======================= + +Before the validation itself, the data can be normalized using the `before()` method. Let's say the list of administrators can also be written as a single string with commas, `'jim@example.com, ann@example.com'`: + +```php +$explode = fn($v) => is_string($v) ? array_map('trim', explode(',', $v)) : $v; + +$schema = Expect::listOf('email') + ->before($explode); + +$normalized = $processor->process($schema, 'jim@example.com, ann@example.com'); +// OK and returns ['jim@example.com', 'ann@example.com'] +``` + +An element has one handler, so a second call to `before()` replaces the first one. Put all the normalization into one handler instead. + +The second call also raises an `E_USER_DEPRECATED` notice, because in version 2.0 the handlers will be chained, each receiving the result of the previous one. .{data-version:1.4.0} + + +Mapping to Objects: from() +========================== + +You can have the structure schema generated from an object of a class. It is built from the types of its public properties. Example: + +```php +class DatabaseConfig +{ + public string $host = 'localhost'; + public int $port = 3306; + public string $user; + public ?string $password = null; + public Mode $mode = Mode::Production; +} + +$schema = Expect::from(new DatabaseConfig); + +$config = $processor->process($schema, [ + 'user' => 'admin', + 'mode' => 'development', +]); +// $config instanceof DatabaseConfig +// $config->mode === Mode::Development +``` + +A property without a default value, such as `$user`, becomes a required item. A property with a [backed enum |types#Enums: enum()] accepts its value from the input and gives you the case. + +Anonymous classes are also supported: + +```php +$schema = Expect::from(new class { + public string $host = 'localhost'; + public int $port = 3306; +}); +``` + +Because the information obtained from the class definition may not be sufficient, you can supplement the elements with your own schema using the second parameter: + +```php +$schema = Expect::from(new DatabaseConfig, [ + 'port' => Expect::int(3306)->min(1)->max(65535), +]); +``` + + +Errors +====== + +When the data is invalid, `process()` throws [api:Nette\Schema\ValidationException] with all the errors found: + +```php +try { + $config = $processor->process($schema, $data); +} catch (Nette\Schema\ValidationException $e) { + echo 'Data is invalid: ' . $e->getMessage(); +} +``` + +The method `$e->getMessage()` returns the first error, `$e->getMessages()` an array of all of them as strings. When you want to show the errors in your own way, for example next to each field of a form, `$e->getMessageObjects()` returns them as [api:Nette\Schema\Message] objects. Each has the text in `$message`, the path to the item in `$path` and a code saying what kind of error it is in `$code`: + +```php +foreach ($e->getMessageObjects() as $message) { + echo implode(' › ', $message->path), ': ', $message->code, "\n"; +} +// port: schema.typeMismatch +// user: schema.missingItem +``` + +The codes are constants of the class `Message`, such as `Message::TypeMismatch`, `MissingItem` or `UnexpectedItem`. + +Warnings, such as the use of a [deprecated item |types#Deprecated Items: deprecated()], do not stop the processing. You read them after it with `$processor->getWarnings()`. + +{{maintitle: Nette Schema: Custom Validation, Transformation and Casting}} +{{description: Add custom checks to a Nette Schema, adjust values before and after validation, cast them to classes, build a schema from a class and work with errors.}} diff --git a/schema/en/types.texy b/schema/en/types.texy new file mode 100644 index 0000000000..edac1b3a4a --- /dev/null +++ b/schema/en/types.texy @@ -0,0 +1,399 @@ +Data Types +********** + +
+ +A schema is made of elements, each describing one piece of the data. This page goes through all of them: + +- simple types, formats and ranges +- default values, required and nullable items +- arrays, lists, enumerations and enums +- structures and tuples +- descriptions and deprecated items + +
+ +The examples continue the configuration of an application from the [overview |@home]. `$processor` is an instance of `Nette\Schema\Processor`. + + +Simple Types: type() +==================== + +All standard PHP data types can be specified in the schema: + +```php +Expect::string($default = null); +Expect::int($default = null); +Expect::float($default = null); +Expect::bool($default = null); +Expect::null(); +Expect::array($default = []); +Expect::list($default = []); +``` + +And also all types [supported by the Validators class |utils:validators#Expected Types], for example `Expect::type('scalar')` or shorthand `Expect::scalar()`. Also class or interface names, e.g., `Expect::type('AddressEntity')`. + +Union syntax can also be used: + +```php +Expect::type('bool|string|array') +``` + +The default value is always `null` with the exception of `array` and `list`, where it is an empty array. (A list is an array indexed by a sequence of numeric keys starting from zero, i.e. a non-associative array). + +In version 1.x, the type `'?int[]'` means an array whose items are integers or `null`. Version 2.0 reads it the way phpDoc does, as an array of integers, or `null` in place of the whole array. If you mean an array whose items may be `null`, write `Expect::arrayOf(Expect::int()->nullable())`, which means the same in both versions. + + +Default, Required and Nullable +============================== + +Every item that is missing in the input gets its default value. For most types it is `null`, and you set another one as the parameter or with `default()`: + +```php +Expect::int(3306); +Expect::int()->default(3306); // the same +``` + +A default value of `null` does not mean that the input may contain `null`. `Expect::string()` accepts only a string, so `'password' => null` in the input is an error. To allow `null`, call `nullable()`: + +```php +$schema = Expect::structure([ + 'user' => Expect::string(), + 'password' => Expect::string()->nullable(), +]); + +$processor->process($schema, ['user' => null]); +// ERROR: The item 'user' expects to be string, null given. + +$processor->process($schema, ['password' => null]); +// OK, returns {'password' => null, 'user' => null} +``` + +An item that must be given is marked with `required()`. When it is missing, the processing reports an error instead of using the default value: + +```php +$schema = Expect::structure([ + 'user' => Expect::string()->required(), +]); + +$processor->process($schema, []); +// ERROR: The mandatory item 'user' is missing. +``` + + +Ranges: min() max() +=================== + +Use `min()` and `max()` to limit the count for arrays: + +```php +// array, at least 1 item, maximum 5 items +Expect::listOf('email')->min(1)->max(5); +``` + +For strings, they limit the length: + +```php +// string, at least 8 bytes long, maximum 64 bytes +Expect::string()->min(8)->max(64); +``` + +The length of a string is measured in bytes. To count characters of a UTF-8 string, use `Expect::unicode()`. + +For numbers, they limit the value: + +```php +// integer, between 1 and 65535 inclusive +Expect::int()->min(1)->max(65535); +``` + +Of course, it is possible to specify just `min()` or just `max()`: + +```php +// string, maximum 64 bytes +Expect::string()->max(64); +``` + +On a union such as `Expect::type('int|string')`, it is not clear whether `min()` and `max()` should limit the number or the length of the string, so they raise an `E_USER_DEPRECATED` notice there. Give the limits to each variant of [anyOf() |#Enumeration: anyOf()] instead: .{data-version:1.4.0} + +```php +Expect::anyOf(Expect::int()->min(1), Expect::string()->min(1)); +``` + + +Regular Expressions: pattern() +============================== + +Using `pattern()`, you can specify a regular expression that the **entire** input string must match (i.e. as if it were wrapped in `^` and `$` characters): + +```php +// exactly 9 digits +Expect::string()->pattern('\d{9}'); +``` + +A pattern only makes sense for a string. That is why `Expect::string()` returns a `StringType` element, while `Expect::int()` and `Expect::float()` return a `NumberType` and `Expect::listOf()` and the other array schemas an `ArrayType`, each offering the methods of its kind. Calling `pattern()` on a number or an array raises an `E_USER_DEPRECATED` notice, and your editor flags such a call as deprecated as soon as you write it. .{data-version:1.4.0} + + +Arrays and Lists: arrayOf() listOf() +==================================== + +An array represents too general a structure; it's more useful to specify precisely which elements it may contain. For example, an array whose elements can only be strings: + +```php +$schema = Expect::arrayOf('string'); + +$processor->process($schema, ['hello', 'world']); // OK +$processor->process($schema, ['a' => 'hello', 'b' => 'world']); // OK +$processor->process($schema, ['key' => 123]); // ERROR: 123 is not a string +``` + +The second parameter can specify keys (since version 1.2): + +```php +$schema = Expect::arrayOf('string', 'int'); + +$processor->process($schema, ['hello', 'world']); // OK +$processor->process($schema, ['a' => 'hello']); // ERROR: 'a' is not an int +``` + +A list is an indexed array: + +```php +$schema = Expect::listOf('email'); + +$processor->process($schema, ['jim@example.com', 'ann@example.com']); // OK +$processor->process($schema, ['jim@example.com', 'jim']); // ERROR: 'jim' is not an e-mail +$processor->process($schema, ['key' => 'jim@example.com']); // ERROR: not a list +``` + +With the `wrap` parameter, a single value is also accepted and wrapped into a one-item list. A configuration with a single administrator then does not need the brackets: .{data-version:1.4.0} + +```php +$schema = Expect::listOf('email', wrap: true); + +$processor->process($schema, 'jim@example.com'); // OK, gives ['jim@example.com'] +``` + +The parameter can also be a schema, so we can write: + +```php +Expect::arrayOf(Expect::bool()) +``` + +The default value is an empty array. If you specify a default value, it will be merged with the passed data. This can be disabled using `mergeDefaults(false)` (since version 1.1). + + +Enumeration: anyOf() +==================== + +`anyOf()` represents a set of values or schemas that a value can take. Here's how to write an array of elements that can be either `'a'`, `true`, or `null`: + +```php +$schema = Expect::listOf( + Expect::anyOf('a', true, null), +); + +$processor->process($schema, ['a', true, null, 'a']); // OK +$processor->process($schema, ['a', false]); // ERROR: false does not belong there +``` + +The elements of the enumeration can also be schemas: + +```php +$schema = Expect::listOf( + Expect::anyOf(Expect::string(), true, null), +); + +$processor->process($schema, ['foo', true, null, 'bar']); // OK +$processor->process($schema, [123]); // ERROR +``` + +The `anyOf()` method accepts variants as separate parameters, not as an array. To pass it an array of values, use the unpack operator `anyOf(...$variants)`. + +Variants are tried in the order they are written, and the first one that matches wins. The only exception is `null`: when the set accepts it, a `null` input always gives `null`, even if a structure or array variant listed earlier would otherwise turn it into an empty structure or array. + +The default value is `null`. Use the `firstIsDefault()` method to make the first item the default: + +```php +// default is 'hello' +Expect::anyOf(Expect::string('hello'), true, null)->firstIsDefault(); +``` + + +Enums: enum() .{data-version:1.4.0} +=================================== + +A configuration file can only hold a plain string such as `'production'`, but in your code you would much rather work with an enum. `enum()` converts one into the other: give it a backed enum, i.e. one whose cases have values (`enum Mode: string`), and it accepts either the value or the case itself, and always gives you back the case: + +```php +enum Mode: string +{ + case Development = 'development'; + case Production = 'production'; +} + +$schema = Expect::enum(Mode::class); + +$processor->process($schema, 'production'); // OK, returns Mode::Production +$processor->process($schema, Mode::Development); // OK, returns Mode::Development +$processor->process($schema, 'test'); // ERROR: expects to be Mode +``` + +Enums backed by integers work exactly the same, and so does everything you know from the other elements, such as `Expect::enum(Mode::class)->required()` or `->default(Mode::Production)`. + +When [generating a schema from a class |normalization#Mapping to Objects: from()], a `public Mode $mode` property gives you this very element, so you do not have to reach for `enum()` there. `Expect::type(Mode::class)` is a different thing: like any class name, it accepts only an instance, i.e. the case itself. + + +Structures +========== + +Structures are objects with defined keys. Each key-value pair is referred to as a "property". + +Structures accept arrays and objects and return `stdClass` objects. To get an array instead, add `castTo('array')`. + +By default, all properties are optional and have a default value of `null`. You can define mandatory properties using `required()`: + +```php +$schema = Expect::structure([ + 'user' => Expect::string()->required(), + 'password' => Expect::string(), // default value is null +]); + +$processor->process($schema, ['password' => 'secret']); +// ERROR: The mandatory item 'user' is missing. + +$processor->process($schema, ['user' => 'admin']); +// OK, returns {'user' => 'admin', 'password' => null} +``` + +A structure itself is mandatory. Therefore, if it is nested inside another structure and the input does not contain it, it is created anyway - and it reports an error when it contains a required property. Use `required(false)` to make the entire nested structure optional. If it is missing in the input, `null` appears in the output, but if it is present, its required properties are enforced: + +```php +$schema = Expect::structure([ + 'database' => Expect::structure([ + 'user' => Expect::string()->required(), + ])->required(false), +]); + +$processor->process($schema, []); +// OK, returns {'database' => null} + +$processor->process($schema, ['database' => []]); +// ERROR: The mandatory item 'database › user' is missing. +``` + +If you do not want properties with default values in the output, use `skipDefaults()`: + +```php +$schema = Expect::structure([ + 'user' => Expect::string()->required(), + 'password' => Expect::string(), +])->skipDefaults(); + +$processor->process($schema, ['user' => 'admin']); +// OK, returns {'user' => 'admin'} +``` + +The array of all structure properties is returned by the `getShape()` method. + +By default, no additional items can be present in the input data. That is how a misspelled key is caught: + +```php +$schema = Expect::structure([ + 'host' => Expect::string(), +]); + +$processor->process($schema, ['hots' => 'localhost']); +// ERROR: Unexpected item 'hots', did you mean 'host'? +``` + +This can be changed using `otherItems()`. As a parameter, pass the schema to validate each extra item: + +```php +$schema = Expect::structure([ + 'host' => Expect::string(), +])->otherItems(Expect::int()); + +$processor->process($schema, ['timeout' => 30]); // OK +$processor->process($schema, ['timeout' => true]); // ERROR +``` + +You can create a new structure by extending another using `extend()`: + +```php +$database = Expect::structure([ + 'host' => Expect::string('localhost'), + 'port' => Expect::int(3306), +]); + +$replica = $database->extend([ + 'readOnly' => Expect::bool(true), +]); +``` + + +Array .{data-version:1.3.2} +=========================== + +An array with defined keys. Everything that applies to [#structures] applies to it. + +```php +$schema = Expect::array([ + 'user' => Expect::string()->required(), + 'password' => Expect::string(), // default value is null +]); +``` + + +Tuples: tuple() .{data-version:1.4.0} +===================================== + +A tuple is a fixed-size array where each position has its own schema: + +```php +$schema = Expect::tuple([ + Expect::int(), + Expect::string(), + Expect::bool(), +]); + +$processor->process($schema, [1, 'hello', true]); // OK +``` + +The input must be a list, so positions given by keys or in a different order are refused. When the input is shorter, the missing positions behave like missing items of a structure: they get their default value, or report an error when they are `required()`. `otherItems()` lets further items follow the defined positions and sets the schema they must match, while `extend()` adds more positions to the end. + +When configurations are layered, a later tuple replaces the earlier one as a whole, because mixing the positions of two different tuples would only produce nonsense. + +Unlike a structure, a tuple does not accept `null` as an empty value; call `nullable()` when `null` is a valid value. + + +Deprecated Items: deprecated() +============================== + +When you rename or drop a configuration option, the old one can keep working for a while and warn its users. Mark it with `deprecated([string $message])`. The warnings are returned by `$processor->getWarnings()`: + +```php +$schema = Expect::structure([ + 'server' => Expect::string()->deprecated('The item %path% is deprecated, use host'), + 'host' => Expect::string(), +]); + +$processor->process($schema, ['server' => 'localhost']); // OK +$processor->getWarnings(); // ["The item 'server' is deprecated, use host"] +``` + + +Description: description() .{data-version:1.4.0} +================================================ + +Any element can carry a human-readable description. It has no effect on validation, but the schema is often the only place where the meaning of a configuration option is written down at all, and `description()` lets you write it right there. The description also travels into the [JSON Schema export |json-schema]: + +```php +$schema = Expect::structure([ + 'host' => Expect::string('localhost')->description('Database server hostname'), + 'port' => Expect::int(3306)->description('Port the server listens on'), +])->description('Database connection'); +``` + +{{maintitle: Nette Schema Data Types: Structures, Lists, Enums, Tuples}} +{{description: Every element of a Nette Schema: types, ranges, patterns, arrays and lists, enums, structures and tuples, with default and required items and descriptions.}} From d240b0baaa96bf56d2dfc63de5d86b80cff81092 Mon Sep 17 00:00:00 2001 From: David Grudl Date: Thu, 24 Sep 2026 00:22:50 +0200 Subject: [PATCH 6/7] WIP --- nette/cs/@home.texy | 2 +- nette/de/@home.texy | 2 +- nette/en/@home.texy | 2 +- nette/es/@home.texy | 2 +- nette/fr/@home.texy | 2 +- nette/it/@home.texy | 2 +- nette/ja/@home.texy | 2 +- nette/pl/@home.texy | 2 +- nette/ru/@home.texy | 2 +- nette/tr/@home.texy | 2 +- tools/cs/@home.texy | 4 ++-- tools/de/@home.texy | 4 ++-- tools/en/@home.texy | 4 ++-- tools/es/@home.texy | 4 ++-- tools/fr/@home.texy | 4 ++-- tools/it/@home.texy | 4 ++-- tools/ja/@home.texy | 4 ++-- tools/pl/@home.texy | 4 ++-- tools/ru/@home.texy | 4 ++-- tools/tr/@home.texy | 4 ++-- tracy/cs/guide.texy | 2 +- tracy/de/guide.texy | 2 +- tracy/en/guide.texy | 2 +- tracy/es/guide.texy | 2 +- tracy/fr/guide.texy | 2 +- tracy/it/guide.texy | 2 +- tracy/ja/guide.texy | 2 +- tracy/pl/guide.texy | 2 +- tracy/ru/guide.texy | 2 +- tracy/tr/guide.texy | 2 +- 30 files changed, 40 insertions(+), 40 deletions(-) diff --git a/nette/cs/@home.texy b/nette/cs/@home.texy index bcea128f79..cb4c432b59 100644 --- a/nette/cs/@home.texy +++ b/nette/cs/@home.texy @@ -48,7 +48,7 @@ Aplikace v Nette - 🎓 [Návody a postupy |best-practices:] - 🧰 [Nástroje |tools:] -- ✨ [Nette AI |ai:] +- ✨ [Nette AI |https://ai.nette.org] diff --git a/nette/de/@home.texy b/nette/de/@home.texy index 9eac7d62dd..56b1809a93 100644 --- a/nette/de/@home.texy +++ b/nette/de/@home.texy @@ -48,7 +48,7 @@ Nette Application - 🎓 [Anleitungen und Best Practices |best-practices:] - 🧰 [Werkzeuge |tools:] -- ✨ [Nette AI |ai:] +- ✨ [Nette AI |https://ai.nette.org] diff --git a/nette/en/@home.texy b/nette/en/@home.texy index 447b679901..9c24e11985 100644 --- a/nette/en/@home.texy +++ b/nette/en/@home.texy @@ -48,7 +48,7 @@ Nette Application - 🎓 [Tutorials and Best Practices |best-practices:] - 🧰 [Tools |tools:] -- ✨ [Nette AI |ai:] +- ✨ [Nette AI |https://ai.nette.org] diff --git a/nette/es/@home.texy b/nette/es/@home.texy index 1aeb9b8db5..c8e45d6d58 100644 --- a/nette/es/@home.texy +++ b/nette/es/@home.texy @@ -48,7 +48,7 @@ Nette Application - 🎓 [Tutoriales y buenas prácticas |best-practices:] - 🧰 [Herramientas |tools:] -- ✨ [Nette AI |ai:] +- ✨ [Nette AI |https://ai.nette.org] diff --git a/nette/fr/@home.texy b/nette/fr/@home.texy index 4a8a18b31a..202f51c56f 100644 --- a/nette/fr/@home.texy +++ b/nette/fr/@home.texy @@ -48,7 +48,7 @@ Nette Application - 🎓 [Tutoriels et bonnes pratiques |best-practices:] - 🧰 [Outils |tools:] -- ✨ [Nette AI |ai:] +- ✨ [Nette AI |https://ai.nette.org] diff --git a/nette/it/@home.texy b/nette/it/@home.texy index 9b8e6eda55..51f8ea549a 100644 --- a/nette/it/@home.texy +++ b/nette/it/@home.texy @@ -48,7 +48,7 @@ Nette Application - 🎓 [Tutorial e best practice |best-practices:] - 🧰 [Strumenti |tools:] -- ✨ [Nette AI |ai:] +- ✨ [Nette AI |https://ai.nette.org] diff --git a/nette/ja/@home.texy b/nette/ja/@home.texy index dcced55cd3..5bd8997797 100644 --- a/nette/ja/@home.texy +++ b/nette/ja/@home.texy @@ -48,7 +48,7 @@ Nette Application - 🎓 [チュートリアルとベストプラクティス |best-practices:] - 🧰 [ツール |tools:] -- ✨ [Nette AI |ai:] +- ✨ [Nette AI |https://ai.nette.org] diff --git a/nette/pl/@home.texy b/nette/pl/@home.texy index 4c0e0e69ac..6205fd5f89 100644 --- a/nette/pl/@home.texy +++ b/nette/pl/@home.texy @@ -48,7 +48,7 @@ Nette Application - 🎓 [Poradniki i dobre praktyki |best-practices:] - 🧰 [Narzędzia |tools:] -- ✨ [Nette AI |ai:] +- ✨ [Nette AI |https://ai.nette.org] diff --git a/nette/ru/@home.texy b/nette/ru/@home.texy index 05738cef6f..113e3c18d0 100644 --- a/nette/ru/@home.texy +++ b/nette/ru/@home.texy @@ -48,7 +48,7 @@ Nette Application - 🎓 [Руководства и лучшие практики |best-practices:] - 🧰 [Инструменты |tools:] -- ✨ [Nette AI |ai:] +- ✨ [Nette AI |https://ai.nette.org] diff --git a/nette/tr/@home.texy b/nette/tr/@home.texy index 03a56df36a..32f3a4ccd5 100644 --- a/nette/tr/@home.texy +++ b/nette/tr/@home.texy @@ -48,7 +48,7 @@ Nette Application - 🎓 [Öğreticiler ve en iyi uygulamalar |best-practices:] - 🧰 [Araçlar |tools:] -- ✨ [Nette AI |ai:] +- ✨ [Nette AI |https://ai.nette.org] diff --git a/tools/cs/@home.texy b/tools/cs/@home.texy index bb3d5526d6..4711931625 100644 --- a/tools/cs/@home.texy +++ b/tools/cs/@home.texy @@ -21,8 +21,8 @@ Kvalita kódu Umělá inteligence ----------------- -- [Pluginy pro Claude Code a Codex |ai:en:agent-plugins] naučí AI agenty konvence Nette: skills, automatická validace Latte/NEON/JS a integrace MCP. -- [MCP Inspector |ai:en:mcp-inspector] zpřístupní AI reálný stav aplikace: DI služby, schéma databáze, routy i Tracy logy. +- [Pluginy pro Claude Code a Codex |https://ai.nette.org/en/agent-plugins] naučí AI agenty konvence Nette: skills, automatická validace Latte/NEON/JS a integrace MCP. +- [MCP Inspector |https://ai.nette.org/en/mcp-inspector] zpřístupní AI reálný stav aplikace: DI služby, schéma databáze, routy i Tracy logy. Frontend diff --git a/tools/de/@home.texy b/tools/de/@home.texy index b894165198..780fe51098 100644 --- a/tools/de/@home.texy +++ b/tools/de/@home.texy @@ -21,8 +21,8 @@ Codequalität Künstliche Intelligenz ---------------------- -- [Claude-Code-Plugin |ai:en:agent-plugins] bringt Claude Code die Konventionen von Nette bei: Skills, automatische Validierung von Latte/NEON/JS und MCP-Integration. -- [MCP Inspector |ai:en:mcp-inspector] gibt der KI den echten Zustand Ihrer Anwendung: DI-Services, Datenbankschema, Routen und Tracy-Logs. +- [Claude-Code-Plugin |https://ai.nette.org/en/agent-plugins] bringt Claude Code die Konventionen von Nette bei: Skills, automatische Validierung von Latte/NEON/JS und MCP-Integration. +- [MCP Inspector |https://ai.nette.org/en/mcp-inspector] gibt der KI den echten Zustand Ihrer Anwendung: DI-Services, Datenbankschema, Routen und Tracy-Logs. Frontend diff --git a/tools/en/@home.texy b/tools/en/@home.texy index 20c248467a..b1f2bbe5c3 100644 --- a/tools/en/@home.texy +++ b/tools/en/@home.texy @@ -21,8 +21,8 @@ Code Quality Artificial Intelligence ----------------------- -- [Plugins for Claude Code and Codex |ai:en:agent-plugins] teach AI agents the Nette conventions: skills, automatic validation of Latte/NEON/JS, and MCP integration. -- [MCP Inspector |ai:en:mcp-inspector] gives AI the real state of your application: DI services, database schema, routes and Tracy logs. +- [Plugins for Claude Code and Codex |https://ai.nette.org/en/agent-plugins] teach AI agents the Nette conventions: skills, automatic validation of Latte/NEON/JS, and MCP integration. +- [MCP Inspector |https://ai.nette.org/en/mcp-inspector] gives AI the real state of your application: DI services, database schema, routes and Tracy logs. Frontend diff --git a/tools/es/@home.texy b/tools/es/@home.texy index 69c342613c..e58c701f3c 100644 --- a/tools/es/@home.texy +++ b/tools/es/@home.texy @@ -21,8 +21,8 @@ Calidad del código Inteligencia artificial ----------------------- -- [Claude Code plugin |ai:en:agent-plugins] enseña a Claude Code las convenciones de Nette: skills, validación automática de Latte/NEON/JS e integración con MCP. -- [MCP Inspector |ai:en:mcp-inspector] da a la IA el estado real de su aplicación: servicios de DI, esquema de la base de datos, rutas y registros de Tracy. +- [Claude Code plugin |https://ai.nette.org/en/agent-plugins] enseña a Claude Code las convenciones de Nette: skills, validación automática de Latte/NEON/JS e integración con MCP. +- [MCP Inspector |https://ai.nette.org/en/mcp-inspector] da a la IA el estado real de su aplicación: servicios de DI, esquema de la base de datos, rutas y registros de Tracy. Frontend diff --git a/tools/fr/@home.texy b/tools/fr/@home.texy index a1a8c37a89..6b54793847 100644 --- a/tools/fr/@home.texy +++ b/tools/fr/@home.texy @@ -21,8 +21,8 @@ Qualité du code Intelligence artificielle ------------------------- -- [Plugin Claude Code |ai:en:agent-plugins] apprend à Claude Code les conventions de Nette : skills, validation automatique de Latte/NEON/JS et intégration MCP. -- [MCP Inspector |ai:en:mcp-inspector] donne à l'IA l'état réel de votre application : services DI, schéma de la base de données, routes et journaux de Tracy. +- [Plugin Claude Code |https://ai.nette.org/en/agent-plugins] apprend à Claude Code les conventions de Nette : skills, validation automatique de Latte/NEON/JS et intégration MCP. +- [MCP Inspector |https://ai.nette.org/en/mcp-inspector] donne à l'IA l'état réel de votre application : services DI, schéma de la base de données, routes et journaux de Tracy. Frontend diff --git a/tools/it/@home.texy b/tools/it/@home.texy index e277b52ce0..dedb17ba4a 100644 --- a/tools/it/@home.texy +++ b/tools/it/@home.texy @@ -21,8 +21,8 @@ Qualità del codice Intelligenza artificiale ------------------------ -- [Plugin per Claude Code |ai:en:agent-plugins] insegna a Claude Code le convenzioni di Nette: skill, validazione automatica di Latte/NEON/JS e integrazione MCP. -- [MCP Inspector |ai:en:mcp-inspector] dà all'AI lo stato reale della vostra applicazione: servizi DI, schema del database, rotte e log di Tracy. +- [Plugin per Claude Code |https://ai.nette.org/en/agent-plugins] insegna a Claude Code le convenzioni di Nette: skill, validazione automatica di Latte/NEON/JS e integrazione MCP. +- [MCP Inspector |https://ai.nette.org/en/mcp-inspector] dà all'AI lo stato reale della vostra applicazione: servizi DI, schema del database, rotte e log di Tracy. Frontend diff --git a/tools/ja/@home.texy b/tools/ja/@home.texy index 0eafb39768..b050890519 100644 --- a/tools/ja/@home.texy +++ b/tools/ja/@home.texy @@ -21,8 +21,8 @@ Nette での開発を楽にしてくれる助っ人の道具です。 人工知能 ---- -- [Claude Code のプラグイン |ai:en:agent-plugins] Claude Code に Nette の流儀を教えます。スキル、Latte・NEON・JS の自動の検証、そして MCP との統合。 -- [MCP Inspector |ai:en:mcp-inspector] AI にあなたのアプリケーションの実際の状態を与えます。DI のサービス、データベースのスキーマ、ルート、Tracy のログです。 +- [Claude Code のプラグイン |https://ai.nette.org/en/agent-plugins] Claude Code に Nette の流儀を教えます。スキル、Latte・NEON・JS の自動の検証、そして MCP との統合。 +- [MCP Inspector |https://ai.nette.org/en/mcp-inspector] AI にあなたのアプリケーションの実際の状態を与えます。DI のサービス、データベースのスキーマ、ルート、Tracy のログです。 フロントエンド diff --git a/tools/pl/@home.texy b/tools/pl/@home.texy index fc1efa9cec..d30fe1ed00 100644 --- a/tools/pl/@home.texy +++ b/tools/pl/@home.texy @@ -21,8 +21,8 @@ Jakość kodu Sztuczna inteligencja --------------------- -- [Plugin Claude Code |ai:en:agent-plugins] uczy Claude Code konwencji Nette: skille, automatyczna walidacja Latte/NEON/JS i integracja MCP. -- [MCP Inspector |ai:en:mcp-inspector] daje AI rzeczywisty stan Twojej aplikacji: usługi DI, schemat bazy danych, trasy i logi Tracy. +- [Plugin Claude Code |https://ai.nette.org/en/agent-plugins] uczy Claude Code konwencji Nette: skille, automatyczna walidacja Latte/NEON/JS i integracja MCP. +- [MCP Inspector |https://ai.nette.org/en/mcp-inspector] daje AI rzeczywisty stan Twojej aplikacji: usługi DI, schemat bazy danych, trasy i logi Tracy. Frontend diff --git a/tools/ru/@home.texy b/tools/ru/@home.texy index 842ec3e8cb..61222a9a6d 100644 --- a/tools/ru/@home.texy +++ b/tools/ru/@home.texy @@ -21,8 +21,8 @@ Искусственный интеллект ----------------------- -- [Плагин для Claude Code |ai:en:agent-plugins] учит Claude Code соглашениям Nette: навыки, автоматическая проверка Latte/NEON/JS и интеграция с MCP. -- [MCP Inspector |ai:en:mcp-inspector] даёт ИИ реальное состояние вашего приложения: сервисы DI, схему базы данных, маршруты и логи Tracy. +- [Плагин для Claude Code |https://ai.nette.org/en/agent-plugins] учит Claude Code соглашениям Nette: навыки, автоматическая проверка Latte/NEON/JS и интеграция с MCP. +- [MCP Inspector |https://ai.nette.org/en/mcp-inspector] даёт ИИ реальное состояние вашего приложения: сервисы DI, схему базы данных, маршруты и логи Tracy. Фронтенд diff --git a/tools/tr/@home.texy b/tools/tr/@home.texy index 7a68145498..98263d8303 100644 --- a/tools/tr/@home.texy +++ b/tools/tr/@home.texy @@ -21,8 +21,8 @@ Kod Kalitesi Yapay Zekâ ---------- -- [Claude Code eklentisi |ai:en:agent-plugins] Claude Code'a Nette kurallarını öğretir: beceriler, Latte/NEON/JS'in otomatik doğrulanması ve MCP entegrasyonu. -- [MCP Inspector |ai:en:mcp-inspector] yapay zekâya uygulamanızın gerçek durumunu verir: DI servisleri, veritabanı şeması, rotalar ve Tracy günlükleri. +- [Claude Code eklentisi |https://ai.nette.org/en/agent-plugins] Claude Code'a Nette kurallarını öğretir: beceriler, Latte/NEON/JS'in otomatik doğrulanması ve MCP entegrasyonu. +- [MCP Inspector |https://ai.nette.org/en/mcp-inspector] yapay zekâya uygulamanızın gerçek durumunu verir: DI servisleri, veritabanı şeması, rotalar ve Tracy günlükleri. Frontend diff --git a/tracy/cs/guide.texy b/tracy/cs/guide.texy index 42b286978e..c90e217aeb 100644 --- a/tracy/cs/guide.texy +++ b/tracy/cs/guide.texy @@ -202,7 +202,7 @@ Když vaši aplikaci ovládá AI agent přes prohlížeč (Chrome DevTools MCP, Detekce nastaví cookie `tracy-webdriver=1`; pokud chcete markdown výstup vidět z normálního prohlížeče, cookie si nastavte ručně v DevTools. Aktivace agenta neovlivňuje `.md` sourozence, kteří se zapisují vedle každého `log/exception-*.html` bez podmínek - ti jsou vstupem pro dávkové zpracování produkčních logů. -Vlastní panely Tracy Baru mohou nabídnout svůj markdown výstup implementací [`getAgentInfo()` |extensions#Podpora AI agentů]. Pro uživatele Claude Code a Codexu obsahuje [Nette plugin |ai:agent-plugins] skill `tracy-debugging`, který agentovi vysvětluje, jak číst Tracy výstup z `list_console_messages()`. +Vlastní panely Tracy Baru mohou nabídnout svůj markdown výstup implementací [`getAgentInfo()` |extensions#Podpora AI agentů]. Pro uživatele Claude Code a Codexu obsahuje [Nette plugin |https://ai.nette.org/en/agent-plugins] skill `tracy-debugging`, který agentovi vysvětluje, jak číst Tracy výstup z `list_console_messages()`. Otevírání v editoru diff --git a/tracy/de/guide.texy b/tracy/de/guide.texy index 6f9471b4e1..649e2de53d 100644 --- a/tracy/de/guide.texy +++ b/tracy/de/guide.texy @@ -202,7 +202,7 @@ Wenn ein KI-Agent Ihre Anwendung über einen Browser steuert (Chrome DevTools MC Die Erkennung setzt das Cookie `tracy-webdriver=1`; Sie können es in den DevTools von Hand setzen, um die Markdown-Ausgabe auch aus einem gewöhnlichen Browser zu aktivieren. Die Aktivierung des Agenten beeinflusst die `.md`-Geschwisterchen neben jeder `log/exception-*.html` nicht - die entstehen bedingungslos und bilden die Grundlage für die Stapelverarbeitung von Produktionslogs. -Eigene Panels der Tracy Bar können ihr eigenes Markdown liefern, indem sie [`getAgentInfo()` |extensions#Unterstützung für KI-Agenten] implementieren. Für Nutzer von Claude Code enthält das [Nette-Plugin |ai:agent-plugins] den Skill `tracy-debugging`, der dem Agenten beibringt, die Ausgabe von Tracy aus `list_console_messages()` zu lesen. +Eigene Panels der Tracy Bar können ihr eigenes Markdown liefern, indem sie [`getAgentInfo()` |extensions#Unterstützung für KI-Agenten] implementieren. Für Nutzer von Claude Code enthält das [Nette-Plugin |https://ai.nette.org/en/agent-plugins] den Skill `tracy-debugging`, der dem Agenten beibringt, die Ausgabe von Tracy aus `list_console_messages()` zu lesen. Dateien im Editor öffnen diff --git a/tracy/en/guide.texy b/tracy/en/guide.texy index 69d7e42dc5..b8aabe7e12 100644 --- a/tracy/en/guide.texy +++ b/tracy/en/guide.texy @@ -202,7 +202,7 @@ When an AI agent drives your application through a browser (Chrome DevTools MCP, Detection sets the cookie `tracy-webdriver=1`; you can set it manually in DevTools to enable the markdown output from a regular browser. Agent activation does not affect the `.md` siblings written next to every `log/exception-*.html` - those are produced unconditionally and form the basis for batch processing of production logs. -Custom Tracy Bar panels can supply their own markdown by implementing [`getAgentInfo()` |extensions#AI Agent Support]. For Claude Code and Codex users, the [Nette plugin |ai:agent-plugins] includes the `tracy-debugging` skill that teaches the agent how to read Tracy's output from `list_console_messages()`. +Custom Tracy Bar panels can supply their own markdown by implementing [`getAgentInfo()` |extensions#AI Agent Support]. For Claude Code and Codex users, the [Nette plugin |https://ai.nette.org/en/agent-plugins] includes the `tracy-debugging` skill that teaches the agent how to read Tracy's output from `list_console_messages()`. Opening Files in the Editor diff --git a/tracy/es/guide.texy b/tracy/es/guide.texy index a0266a8ea2..d479384eb3 100644 --- a/tracy/es/guide.texy +++ b/tracy/es/guide.texy @@ -202,7 +202,7 @@ Cuando un agente de IA maneja su aplicación mediante un navegador (Chrome DevTo La detección establece la cookie `tracy-webdriver=1`; puede ponerla a mano en las DevTools para activar la salida en markdown desde un navegador normal. La activación del agente no afecta a los archivos hermanos `.md` que se escriben junto a cada `log/exception-*.html`: esos se producen incondicionalmente y son la base del procesamiento por lotes de los registros de producción. -Los paneles propios de la Tracy Bar pueden aportar su propio markdown implementando [`getAgentInfo()` |extensions#Soporte para agentes de IA]. Para quien use Claude Code, el [plugin de Nette |ai:agent-plugins] incluye la skill `tracy-debugging`, que enseña al agente a leer la salida de Tracy desde `list_console_messages()`. +Los paneles propios de la Tracy Bar pueden aportar su propio markdown implementando [`getAgentInfo()` |extensions#Soporte para agentes de IA]. Para quien use Claude Code, el [plugin de Nette |https://ai.nette.org/en/agent-plugins] incluye la skill `tracy-debugging`, que enseña al agente a leer la salida de Tracy desde `list_console_messages()`. Abrir archivos en el editor diff --git a/tracy/fr/guide.texy b/tracy/fr/guide.texy index 78e0ef5ee4..0bd28f849a 100644 --- a/tracy/fr/guide.texy +++ b/tracy/fr/guide.texy @@ -202,7 +202,7 @@ Lorsqu'un agent IA pilote votre application dans un navigateur (Chrome DevTools La détection pose le cookie `tracy-webdriver=1` ; vous pouvez le définir manuellement dans les DevTools pour activer la sortie markdown depuis un navigateur ordinaire. L'activation de l'agent n'a aucune incidence sur les fichiers `.md` écrits à côté de chaque `log/exception-*.html` : ceux-là sont produits sans condition et forment la base du traitement en masse des journaux de production. -Les panneaux personnalisés de la Tracy Bar peuvent fournir leur propre markdown en implémentant [`getAgentInfo()` |extensions#Prise en charge des agents IA]. Pour les utilisateurs de Claude Code, le [plugin Nette |ai:agent-plugins] contient la skill `tracy-debugging`, qui apprend à l'agent à lire la sortie de Tracy depuis `list_console_messages()`. +Les panneaux personnalisés de la Tracy Bar peuvent fournir leur propre markdown en implémentant [`getAgentInfo()` |extensions#Prise en charge des agents IA]. Pour les utilisateurs de Claude Code, le [plugin Nette |https://ai.nette.org/en/agent-plugins] contient la skill `tracy-debugging`, qui apprend à l'agent à lire la sortie de Tracy depuis `list_console_messages()`. Ouvrir les fichiers dans l'éditeur diff --git a/tracy/it/guide.texy b/tracy/it/guide.texy index 15e340d6cd..fe4de33523 100644 --- a/tracy/it/guide.texy +++ b/tracy/it/guide.texy @@ -202,7 +202,7 @@ Quando un agente AI comanda la vostra applicazione tramite un browser (Chrome De Il rilevamento imposta il cookie `tracy-webdriver=1`; potete impostarlo a mano nei DevTools per attivare l'output markdown da un browser normale. L'attivazione dell'agente non influisce sui file gemelli `.md` scritti accanto a ogni `log/exception-*.html`: quelli vengono prodotti sempre e sono la base per l'elaborazione in blocco dei log di produzione. -I pannelli personalizzati della Tracy Bar possono fornire il proprio markdown implementando [`getAgentInfo()` |extensions#Supporto per gli agenti AI]. Per chi usa Claude Code, il [plugin Nette |ai:agent-plugins] comprende la skill `tracy-debugging`, che insegna all'agente come leggere l'output di Tracy da `list_console_messages()`. +I pannelli personalizzati della Tracy Bar possono fornire il proprio markdown implementando [`getAgentInfo()` |extensions#Supporto per gli agenti AI]. Per chi usa Claude Code, il [plugin Nette |https://ai.nette.org/en/agent-plugins] comprende la skill `tracy-debugging`, che insegna all'agente come leggere l'output di Tracy da `list_console_messages()`. Aprire i file nell'editor diff --git a/tracy/ja/guide.texy b/tracy/ja/guide.texy index 7b4f03dd5c..12bfc27c9d 100644 --- a/tracy/ja/guide.texy +++ b/tracy/ja/guide.texy @@ -202,7 +202,7 @@ AI エージェントがブラウザ越しにあなたのアプリケーショ 見分けがつくと `tracy-webdriver=1` のクッキーが設定されます。DevTools で手で設定すれば、ふつうのブラウザからでも markdown の出力を有効にできます。エージェントが認識されたかどうかは、`log/exception-*.html` の隣に書かれる `.md` の兄弟ファイルには影響しません。あれはいつでも作られ、本番のログをまとめて処理するための土台になります。 -Tracy Bar の独自のパネルは、[`getAgentInfo()` |extensions#AI エージェントへの対応]を実装すれば自分の markdown を出せます。Claude Code の利用者向けには、[Nette のプラグイン |ai:agent-plugins]に `tracy-debugging` のスキルが入っていて、`list_console_messages()` から Tracy の出力を読む方法をエージェントに教えます。 +Tracy Bar の独自のパネルは、[`getAgentInfo()` |extensions#AI エージェントへの対応]を実装すれば自分の markdown を出せます。Claude Code の利用者向けには、[Nette のプラグイン |https://ai.nette.org/en/agent-plugins]に `tracy-debugging` のスキルが入っていて、`list_console_messages()` から Tracy の出力を読む方法をエージェントに教えます。 エディタでファイルを開く diff --git a/tracy/pl/guide.texy b/tracy/pl/guide.texy index b67cb73a72..f2929aabfe 100644 --- a/tracy/pl/guide.texy +++ b/tracy/pl/guide.texy @@ -202,7 +202,7 @@ Gdy agent AI steruje Twoją aplikacją przez przeglądarkę (Chrome DevTools MCP Wykrycie ustawia cookie `tracy-webdriver=1`; możesz ustawić je ręcznie w DevTools, żeby włączyć wyjście markdownowe ze zwykłej przeglądarki. Aktywacja agenta nie wpływa na bliźniacze pliki `.md` zapisywane obok każdego `log/exception-*.html` - te powstają bezwarunkowo i stanowią podstawę wsadowego przetwarzania logów produkcyjnych. -Własne panele Tracy Bara mogą dostarczyć swój markdown, implementując [`getAgentInfo()` |extensions#Wsparcie dla agentów AI]. Dla użytkowników Claude Code [plugin Nette |ai:agent-plugins] zawiera skill `tracy-debugging`, który uczy agenta, jak czytać wyjście Tracy z `list_console_messages()`. +Własne panele Tracy Bara mogą dostarczyć swój markdown, implementując [`getAgentInfo()` |extensions#Wsparcie dla agentów AI]. Dla użytkowników Claude Code [plugin Nette |https://ai.nette.org/en/agent-plugins] zawiera skill `tracy-debugging`, który uczy agenta, jak czytać wyjście Tracy z `list_console_messages()`. Otwieranie plików w edytorze diff --git a/tracy/ru/guide.texy b/tracy/ru/guide.texy index e3c1068829..0091f51486 100644 --- a/tracy/ru/guide.texy +++ b/tracy/ru/guide.texy @@ -202,7 +202,7 @@ Debugger::$email = 'admin@example.com'; Распознавание устанавливает cookie `tracy-webdriver=1`; вы можете задать её вручную в DevTools и включить markdown-вывод из обычного браузера. Включение режима агента не влияет на файлы `.md`, записываемые рядом с каждым `log/exception-*.html`: они создаются всегда и служат основой для пакетной обработки продакшн-логов. -Собственные панели Tracy Bar могут предоставить свой markdown, реализовав [`getAgentInfo()` |extensions#Поддержка AI-агентов]. Для пользователей Claude Code [плагин Nette |ai:agent-plugins] содержит навык `tracy-debugging`, который учит агента читать вывод Tracy из `list_console_messages()`. +Собственные панели Tracy Bar могут предоставить свой markdown, реализовав [`getAgentInfo()` |extensions#Поддержка AI-агентов]. Для пользователей Claude Code [плагин Nette |https://ai.nette.org/en/agent-plugins] содержит навык `tracy-debugging`, который учит агента читать вывод Tracy из `list_console_messages()`. Открытие файлов в редакторе diff --git a/tracy/tr/guide.texy b/tracy/tr/guide.texy index b0206477fe..ca3019bf93 100644 --- a/tracy/tr/guide.texy +++ b/tracy/tr/guide.texy @@ -202,7 +202,7 @@ Bir yapay zekâ ajanı uygulamanızı bir tarayıcı üzerinden sürdüğünde ( Saptama, `tracy-webdriver=1` çerezini ayarlar; markdown çıktısını sıradan bir tarayıcıdan etkinleştirmek için onu DevTools'ta elle de ayarlayabilirsiniz. Ajan etkinleştirmesi, her `log/exception-*.html` dosyasının yanına yazılan `.md` kardeşlerini etkilemez; onlar koşulsuz üretilir ve üretim günlüklerinin toplu işlenmesinin temelini oluşturur. -Özel Tracy Bar panelleri, [`getAgentInfo()` |extensions#Yapay Zekâ Ajanı Desteği] metodunu uygulayarak kendi markdown çıktılarını sağlayabilir. Claude Code kullanıcıları için [Nette eklentisi |ai:agent-plugins], ajana Tracy'nin çıktısını `list_console_messages()` içinden nasıl okuyacağını öğreten `tracy-debugging` becerisini içerir. +Özel Tracy Bar panelleri, [`getAgentInfo()` |extensions#Yapay Zekâ Ajanı Desteği] metodunu uygulayarak kendi markdown çıktılarını sağlayabilir. Claude Code kullanıcıları için [Nette eklentisi |https://ai.nette.org/en/agent-plugins], ajana Tracy'nin çıktısını `list_console_messages()` içinden nasıl okuyacağını öğreten `tracy-debugging` becerisini içerir. Dosyaları Düzenleyicide Açma From 064a481eb91bfb8f2621e836bae0c67d2552adbf Mon Sep 17 00:00:00 2001 From: Vladislav Korchagin Date: Sun, 8 Nov 2026 23:31:07 +0300 Subject: [PATCH 7/7] Fixed the order of security-relevant information to avoid early assumptions Added links and notes to relevant considerations --- latte/en/guide.texy | 4 ++- latte/en/safety-first.texy | 30 ++++++++++++++------- latte/en/sandbox.texy | 53 +++++++++++++++++++++----------------- 3 files changed, 53 insertions(+), 34 deletions(-) diff --git a/latte/en/guide.texy b/latte/en/guide.texy index a3f44e77c7..47384c350e 100644 --- a/latte/en/guide.texy +++ b/latte/en/guide.texy @@ -5,7 +5,9 @@ Getting Started with Latte Templates improve code organization, separate application logic from presentation, and enhance security. They offer far better features and expressive means for generating HTML than PHP itself. -Latte is the safest templating system for PHP. You will love its intuitive syntax. A wide range of useful features will significantly simplify your work. It provides top-notch protection against [critical vulnerabilities|safety-first] and allows you to focus on creating high-quality applications without worrying about their security. +When used with trusted templates, Latte is the safest templating system for PHP. You will love its intuitive syntax. A wide range of useful features will significantly simplify your work. It provides top-notch protection against [critical XSS vulnerabilities|safety-first] and allows you to focus on creating high-quality applications without worrying about their security. + +To allow templates from untrusted sources, you can enable a built-in [sandbox|sandbox], that prohibits everything that is not explicitly allowed by the policy. This will protect your server from running arbitrary PHP code inside the template. How to write templates using Latte? diff --git a/latte/en/safety-first.texy b/latte/en/safety-first.texy index 62c6fb7291..db8cf279b7 100644 --- a/latte/en/safety-first.texy +++ b/latte/en/safety-first.texy @@ -3,7 +3,11 @@ Latte is Synonymous with Safety
-Latte is the only PHP templating system with effective protection against the critical Cross-site Scripting (XSS) vulnerability. This is thanks to context-aware escaping. We will discuss: +When using a template engine, you should consider two potential security-critical scenarios: rendering untrusted templates and embedding untrusted user input. + +When working with untrusted templates, use a built-in [sandbox|sandbox] to avoid running unwanted PHP code on the server. Still, templates by design can contain unsafe client-side JavaScript, so you also need to add protections against Cross-site Scripting (XSS). + +As for the second scenario, Latte is the only PHP templating system with effective protection against the critical Cross-site Scripting (XSS) vulnerability exploited through embedding unsafe data. This is thanks to context-aware escaping. We will discuss: - the principle of the XSS vulnerability and why it is so dangerous - what makes Latte so effective in defending against XSS @@ -22,6 +26,21 @@ What can such a script do? For example, it can send any content from the comprom This is why XSS consistently ranks among the most dangerous vulnerabilities. If a vulnerability appears on a website, it must be removed as soon as possible to prevent exploitation. +Limits of Latte +=============== + +Latte is not a complete XSS protection for the entire application. We would be unhappy if you stopped thinking about security when using Latte. Latte's goal is to ensure that an attacker cannot alter the page structure or forge HTML elements or attributes. But it does not check the content correctness of the printed data. Nor the correctness of JavaScript behavior. That goes beyond the competence of the templating system. Verifying the correctness of data, especially data entered by the user and therefore untrusted, is an important task for the programmer. + +Latte guards your website against XSS in the untrusted data embedded into the template. Here are the examples of what Latte does not prevent: + +- XSS outside the templates: It is up to you to protect the rest of your website +- XSS in the template itself: Templates can contain arbitrary JavaScript by design +- DOM-based XSS: Your own JavaScript code can add untrusted data to the page on the client side + +.[tip] +Do you want to test your knowledge of escaping in individual contexts? Try the [XSS vulnerability quiz |https://blog.nette.org/en/quiz-can-you-defend-against-xss-vulnerability]. + + How Does the Vulnerability Arise? --------------------------------- @@ -400,14 +419,5 @@ Outputs: The protection works automatically and requires no configuration. - -Limits of Latte -=============== - -Latte is not a complete XSS protection for the entire application. We would be unhappy if you stopped thinking about security when using Latte. Latte's goal is to ensure that an attacker cannot alter the page structure or forge HTML elements or attributes. But it does not check the content correctness of the printed data. Nor the correctness of JavaScript behavior. That goes beyond the competence of the templating system. Verifying the correctness of data, especially data entered by the user and therefore untrusted, is an important task for the programmer. - -.[tip] -Do you want to test your knowledge of escaping in individual contexts? Try the [XSS vulnerability quiz |https://blog.nette.org/en/quiz-can-you-defend-against-xss-vulnerability]. - {{maintitle: PHP XSS Protection: Context-Aware Escaping in Latte}} {{description: Why XSS is so dangerous and how Latte stops it: it knows where each value is printed and escapes it accordingly, which naive template systems cannot do.}} diff --git a/latte/en/sandbox.texy b/latte/en/sandbox.texy index bbcd581ce1..ed2df500b9 100644 --- a/latte/en/sandbox.texy +++ b/latte/en/sandbox.texy @@ -2,9 +2,11 @@ Sandbox ******* .[perex] -Sandbox provides a security layer that gives you control over which tags, PHP functions, methods, etc., can be used in templates. Thanks to the sandbox mode, you can safely collaborate with a client or external coder on template creation without worrying about compromising the application or performing unwanted operations. +Sandbox provides a security layer that gives you control over which tags, PHP functions, methods, etc., can be used in templates. Thanks to the sandbox mode, you can safely collaborate with a client or external coder on template creation without worrying about compromising the application or performing unwanted server-side operations. -How does it work? We simply define what we want to allow in the template. Initially, everything is forbidden and we gradually grant permissions. The following code allows the template author to use the `{block}`, `{if}`, `{else}` and `{=}` tags (the latter is a tag for [printing a variable or expression |tags#Printing]) and all filters: +While Sandbox can protect against server-side attacks and Latte already prevents [Cross-site Scripting (XSS)|safety-first] in the user input, templates by design can contain unsafe HTML with client-side JavaScript. Consider this limitation when using third-party templates. + +How does the sandbox work? We simply define what we want to allow in the template. Initially, everything is forbidden and we gradually grant permissions. The following code allows the template author to use the `{block}`, `{if}`, `{else}` and `{=}` tags (the latter is a tag for [printing a variable or expression |tags#Printing]) and all filters: ```php $policy = new Latte\Sandbox\SecurityPolicy; @@ -12,11 +14,36 @@ $policy->allowTags(['block', 'if', 'else', '=']); $policy->allowFilters($policy::All); $latte->setPolicy($policy); +$latte->setSandboxMode(); ``` -We can also allow access to individual global functions, methods, or properties of objects: +Activating the Sandbox +====================== + +In the example above, the last line is used to enable sandbox mode directly for all templates: + +```php +$latte->setSandboxMode(); +``` + +You can remove it and apply the policy using the [`{sandbox}` |tags#Including Templates] tag. This is somewhat analogous to `{include}`, but it enables sandbox mode and, like `{include}`, does not automatically pass the surrounding variables. You can, however, pass them explicitly, for example `{sandbox 'untrusted.latte', a: 1, b: 2}`: + +```latte +{sandbox 'untrusted.latte'} +``` + +Thus, the layout and individual pages can freely use all tags and variables; restrictions will only be applied to the `untrusted.latte` template. + +Some violations, like using a forbidden tag or filter, are detected at compile time. Others, like calling disallowed methods of an object, are detected at runtime. The template can also contain any other errors. To prevent an exception from the sandboxed template from disrupting the entire rendering process, you can define your [own exception handler |develop#Exception Handler], which might, for example, just log it. + +Configuring the policy +====================== + +In our sandbox policy, we can allow access to individual tags, filters, global functions, methods, or properties of objects: ```php +$policy->allowTags(['block', 'if', 'else', '=']); +$policy->allowFilters($policy::All); $policy->allowFunctions(['trim', 'strlen']); $policy->allowMethods(Nette\Security\User::class, ['isLoggedIn', 'isAllowed']); $policy->allowProperties(Nette\Database\Row::class, $policy::All); @@ -64,26 +91,6 @@ class MyPolicy implements Latte\Policy If the method is missing, Latte warns you with a deprecation notice. -Activating the Sandbox -====================== - -The rules apply to the template that we insert with the [`{sandbox}` |tags#Including Templates] tag. This is somewhat analogous to `{include}`: it enables sandbox mode and, like `{include}`, does not automatically pass the surrounding variables. You can, however, pass them explicitly, for example `{sandbox 'untrusted.latte', a: 1, b: 2}`: - -```latte -{sandbox 'untrusted.latte'} -``` - -Thus, the layout and individual pages can freely use all tags and variables; restrictions will only be applied to the `untrusted.latte` template. - -Some violations, like using a forbidden tag or filter, are detected at compile time. Others, like calling disallowed methods of an object, are detected at runtime. The template can also contain any other errors. To prevent an exception from the sandboxed template from disrupting the entire rendering process, you can define your [own exception handler |develop#Exception Handler], which might, for example, just log it. - -If we wanted to enable sandbox mode directly for all templates, it's easy: - -```php -$latte->setSandboxMode(); -``` - - Checking the Generated Code ===========================