Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
Nette Framework Documentation
https://github.com/nette/docs
Admin
Comprehensive documentation for Nette, a PHP web application framework.
Tokens:
1,023,249
Snippets:
7,961
Trust Score:
9.4
Update:
2 weeks ago
Context
Chat
Benchmark
74.05
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Install Tracy via Composer Source: https://github.com/nette/docs/blob/master/tracy/en/guide.texy Use Composer to install the Tracy library. This is the recommended installation method. ```shell composer require tracy/tracy ``` -------------------------------- ### Navigate to Project Directory Source: https://github.com/nette/docs/blob/master/ai/en/getting-started.texy Navigate to your project directory. The example shows paths for both Windows (WSL) and macOS/Linux. ```shell # Windows (WSL) cd /mnt/c/Users/Jan/Projects/my-app # macOS/Linux cd ~/projects/my-app ``` -------------------------------- ### Launch Ubuntu in WSL Source: https://github.com/nette/docs/blob/master/ai/en/getting-started.texy Launch the Ubuntu terminal after WSL installation. The first launch will ask for a username and password, needed for sudo later. ```shell ubuntu ``` -------------------------------- ### tester --setup tests/runner-setup.php tests with setup script Source: https://github.com/nette/docs/blob/master/tester/en/running-tests.texy Loads a PHP script at startup. The variable Tester\Runner\Runner $runner is available within the script. The example shows a setup file and the command to run it. ```php $runner->outputHandlers[] = new MyOutputHandler; ``` ```terminal tester --setup tests/runner-setup.php tests ``` -------------------------------- ### Install Nette Plugin Source: https://github.com/nette/docs/blob/master/ai/en/getting-started.texy Install the Nette plugin. It includes 11 specialized skills that activate based on your work context. ```shell /plugin install nette@nette ``` -------------------------------- ### Define setup methods for a service Source: https://github.com/nette/docs/blob/master/dependency-injection/en/services.texy Defines methods to be invoked upon service creation using the `setup` section. The example calls `setAttribute` on a `PDO` instance. ```neon services: database: create: PDO(%dsn%, %user%, %password%) setup: - setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION) ``` -------------------------------- ### Create a new Nette project with composer create-project Source: https://github.com/nette/docs/blob/master/quickstart/en/@home.texy Run this command in your terminal to create a new Nette web project in the `nette-blog` directory. Requires PHP 8.1 or later and prior installation of Nette tooling. ```shell composer create-project nette/web-project nette-blog ``` -------------------------------- ### Install WSL on Windows Source: https://github.com/nette/docs/blob/master/ai/en/getting-started.texy Install Windows Subsystem for Linux (WSL) to provide a Unix environment required by Claude Code. Restart your computer after installation. ```shell wsl --install ``` -------------------------------- ### Run Nette Tester without arguments Source: https://github.com/nette/docs/blob/master/tester/en/guide.texy Running vendor/bin/tester without arguments prints help information. ```terminal vendor/bin/tester ``` -------------------------------- ### Environment::setupFunctions: define test functions Source: https://github.com/nette/docs/blob/master/tester/en/helpers.texy Creates global functions test(), testException(), testNoError(), setUp(), and tearDown() for structuring tests. The example shows a test() call with assertions. ```php test('test description', function () { Assert::same(123, foo()); Assert::false(bar()); // ... }); ``` -------------------------------- ### Supplement setup of an altered service in NEON Source: https://github.com/nette/docs/blob/master/dependency-injection/en/services.texy Adds a setup item to the modified 'application.application' service, assigning an array to '$onStartup[]' using the '@resource' reference. This is a continuation of the previous alteration example. ```neon services: application.application: create: MyApplication alteration: true setup: - '$onStartup[]' = [@resource, init] ``` -------------------------------- ### setUp() and tearDown() hooks Source: https://github.com/nette/docs/blob/master/tester/de/writing-tests.texy Registers code to run before and after each test() block. The setUp function is called before each test, and tearDown after each test. ```php setUp(function () { // Initialisierungscode, der vor jedem test() läuft }); ``` -------------------------------- ### Install nette/utils package with Composer Source: https://github.com/nette/docs/blob/master/nette/en/installation.texy Run this command in the root directory of your project to install the nette/utils package, which provides the Finder class for file system navigation. Requires Composer to be set up. ```shell composer require nette/utils ``` -------------------------------- ### Nette Application setup in Bootstrap.php Source: https://github.com/nette/docs/blob/master/robot-loader/en/@home.texy Simplified RobotLoader setup using Configurator's createRobotLoader() method. ```php $configurator = new Nette\Bootstrap\Configurator; // ... $configurator->setTempDirectory(__DIR__ . '/../temp'); $configurator->createRobotLoader() ->addDirectory(__DIR__) ->addDirectory(__DIR__ . '/../libs') ->register(); ``` -------------------------------- ### setUp and tearDown functions Source: https://github.com/nette/docs/blob/master/tester/en/writing-tests.texy Pass initialization or cleanup code to setUp() or tearDown() to run before or after each test() call. ```php setUp(function () { // initialization code that runs before each test() }); ``` -------------------------------- ### Install latte/tools via Composer Source: https://github.com/nette/docs/blob/master/latte/en/cookbook/migration-from-php.texy Install the migration tool using Composer. Run this command in your project directory. ```shell composer create-project latte/tools ``` -------------------------------- ### Access the welcome page at localhost URL Source: https://github.com/nette/docs/blob/master/quickstart/en/@home.texy Open this URL in your browser to view the welcome page of the newly created Nette project. The document root should point to the `www/` directory. ```text http://localhost/nette-blog/www/ ``` -------------------------------- ### Install Claude Code on macOS/Linux Source: https://github.com/nette/docs/blob/master/ai/en/getting-started.texy Install Claude Code using the official installer script. On macOS, Homebrew is an alternative installation method. ```shell curl -fsSL https://claude.ai/install.sh | bash ``` ```shell brew install --cask claude-code ``` -------------------------------- ### Insert sample posts (SQL) Source: https://github.com/nette/docs/blob/master/quickstart/en/home-page.texy Inserts three sample blog posts into the `posts` table. Use this to have data to display before implementing post creation in the application. ```sql INSERT INTO `posts` (`id`, `title`, `content`, `created_at`) VALUES (1, 'Article One', 'Lorem ipsum dolor one', CURRENT_TIMESTAMP), (2, 'Article Two', 'Lorem ipsum dolor two', CURRENT_TIMESTAMP), (3, 'Article Three', 'Lorem ipsum dolor three', CURRENT_TIMESTAMP); ``` -------------------------------- ### Environment::setup() Source: https://github.com/nette/docs/blob/master/tester/en/helpers.texy Improves error dump readability, enables assertion checking, starts coverage collection, and prints status at the end of the script. ```APIDOC ## Environment::setup() ### Description Improves error dump readability, enables assertion checking, starts coverage collection, and prints status at the end of the script. ### Method setup ### Effects - Improves readability of error dumps (including coloring) - Enables checking that assertions were called in the test - Automatically starts collecting information about executed code (when --coverage is used) - Prints the status OK or FAILURE at the end of the script ``` -------------------------------- ### Service setup with static method and service call Source: https://github.com/nette/docs/blob/master/dependency-injection/en/services.texy Defines a service 'foo' with a setup section that calls a static method and a method on another service. The generated factory method shows how the setup calls are applied after instantiation. ```neon services: foo: create: Foo setup: - My\Helpers::initializeFoo(@self) - @anotherService::setFoo(@self) ``` ```php public function createServiceFoo(): Foo { $service = new Foo; My\Helpers::initializeFoo($service); $this->getService('anotherService')->setFoo($service); return $service; } ``` -------------------------------- ### Install Nette Tester via Composer Source: https://github.com/nette/docs/blob/master/tester/en/guide.texy Installs Nette Tester as a dev dependency using Composer. Requires PHP 8.1 or higher. ```terminal composer require --dev nette/tester ``` -------------------------------- ### Install Nette Mail via Composer Source: https://github.com/nette/docs/blob/master/mail/tr/@home.texy Run this command to install the nette/mail package using Composer. ```shell composer require nette/mail ``` -------------------------------- ### Install Claude Code in WSL Source: https://github.com/nette/docs/blob/master/ai/en/getting-started.texy Install Claude Code inside the Ubuntu terminal within WSL. Windows drives are mounted under /mnt/. ```shell curl -fsSL https://claude.ai/install.sh | bash ``` -------------------------------- ### Handle login callback in SignPresenter Source: https://github.com/nette/docs/blob/master/quickstart/en/authentication.texy Callback method that logs in the user with the submitted credentials. On failure, catches AuthenticationException and adds a form error. ```php private function signInFormSucceeded(Form $form, \stdClass $data): void { try { $this->getUser()->login($data->username, $data->password); $this->redirect('Home:'); } catch (Nette\Security\AuthenticationException $e) { $form->addError('Incorrect username or password.'); } } ``` -------------------------------- ### Environment::setupFunctions() Source: https://github.com/nette/docs/blob/master/tester/en/helpers.texy Creates global functions test(), testException(), testNoError(), setUp(), and tearDown() for structuring tests. ```APIDOC ## Environment::setupFunctions() ### Description Creates global functions test(), testException(), testNoError(), setUp(), and tearDown() for structuring tests. ### Method setupFunctions ### Request Example ```php test('test description', function () { Assert::same(123, foo()); Assert::false(bar()); // ... }); ``` ``` -------------------------------- ### Example help output for convert command Source: https://github.com/nette/docs/blob/master/command-line/en/arguments.texy Shows the generated help output for a convert script with options like --format, --quality, --backup, --exclude, --[no-]metadata, and --dry-run. Demonstrates optional values, repeated values, opposite flags, and default values. ```text Usage: convert [options] <files>... Converts images to another format Arguments: <files>... Images to convert Options: -f, --format <jpg|png|webp> Target format (default: webp) -q, --quality <value> Quality from 1 to 100 --backup[=dir] Keep the originals, optionally in the given directory --exclude <mask>... Skip files matching the mask --[no-]metadata Keep EXIF metadata -n, --dry-run Only show what would be done ``` -------------------------------- ### Start Claude Code Source: https://github.com/nette/docs/blob/master/ai/en/getting-started.texy Start Claude Code. The first run will ask for authentication via a browser window; after success you'll see the claude> prompt. ```shell claude ``` -------------------------------- ### Environment::setupFunctions: Define test functions Source: https://github.com/nette/docs/blob/master/tester/de/helpers.texy Creates global functions test(), testException(), testNoError(), setUp(), and tearDown() for structuring tests. ```php test('Beschreibung des Tests', function () { Assert::same(123, foo()); Assert::false(bar()); // ... }); ``` -------------------------------- ### index.php bootstrapping and application run Source: https://github.com/nette/docs/blob/master/application/en/bootstrapping.texy Initializes the environment, creates the DI container, retrieves the Application service, and runs it. The application emits events like onStartup, onRequest, onPresenter, onResponse, onShutdown, and onError. ```php $bootstrap = new App\Bootstrap; // Initialize the environment + create a DI container $container = $bootstrap->bootWebApplication(); // DI container creates a Nette\Application\Application object $application = $container->getByType(Nette\Application\Application::class); // Start the Nette application and process the incoming request $application->run(); ``` -------------------------------- ### SimpleRouter URL example Source: https://github.com/nette/docs/blob/master/application/ru/routing.texy Example of a URL generated by SimpleRouter when no custom URL format is required. ```text http://example.com/?presenter=Product&action=detail&id=123 ``` -------------------------------- ### PHP: Handle output printer selection and code coverage setup Source: https://github.com/nette/docs/blob/master/tester/files/coverage.html This snippet is part of a PHP script that configures the Tester runner's output handlers based on a format option. It handles cases for 'junit', 'log', and 'none' formats, throwing a LogicException for undefined printers. It also includes a setup closure that requires a file specified by the '--setup' option, and a method to prepare code coverage engines, throwing an exception if no engines are available. ```php case 'junit': $runner->outputHandlers[] = new Output\JUnitPrinter($file); break; case 'log': $runner->outputHandlers[] = new Output\Logger($runner, $file); break; case 'none': break; default: throw new \LogicException("Undefined output printer '$format'."); } } if ($this->options['--setup']) { (function () use ($runner): void { require func_get_arg(0); })($this->options['--setup']); } return $runner; } private function prepareCodeCoverage(Runner $runner): string { $engines = $this->interpreter->getCodeCoverageEngines(); if (count($engines) < 1) { throw new \Exception( ``` -------------------------------- ### X-Ray CLI output example Source: https://github.com/nette/docs/blob/master/tools/en/xray.texy Example output after scanning PHP, NEON, and Latte files, showing where reports are saved. ```text Nette X-Ray =========== Scanning PHP files ... 142/142 done Scanning NEON files ... 4/4 done Scanning Latte files ... 87/87 done Reports saved to: xray-report.json xray-report.html ``` -------------------------------- ### Retrieve services from container Source: https://github.com/nette/docs/blob/master/bootstrap/es/@home.texy Get services from the container using getByType() or getByName(). Examples show retrieving database connections and explorer. ```php $db = $container->getByType(Nette\Database\Connection::class); // o $explorer = $container->getByType(Nette\Database\Explorer::class); // o, al crear varias conexiones $db = $container->getByName('database.main.connection'); ``` -------------------------------- ### Start Vite Development Server Source: https://github.com/nette/docs/blob/master/assets/es/vite.texy Run the development server with npm run dev. The output shows the local URL and a hint to expose the server on the network. ```shell npm run dev ``` -------------------------------- ### Handle --help and --version flags with HelpRenderer Source: https://github.com/nette/docs/blob/master/command-line/en/arguments.texy Sets up standalone --help and --version flags, parses arguments, renders help or version, and runs the command. Catches UsageException to render an error and exit with code 2. ```php use Nette\CommandLine\HelpRenderer; use Nette\CommandLine\UsageException; $program->addFlag('--help', 'Print this help', alias: '-h', standalone: true); $program->addFlag('--version', 'Print the version', standalone: true); $parser = new Parser; $renderer = new HelpRenderer; try { $args = $parser->parse($program); if ($args->get('--help')) { $renderer->render($args->command); exit(0); } elseif ($args->get('--version')) { echo "Images 1.0\n"; exit(0); } exit($args->run()); } catch (UsageException $e) { $renderer->renderError($e); exit(2); } ``` -------------------------------- ### Create posts table (SQL) Source: https://github.com/nette/docs/blob/master/quickstart/en/home-page.texy SQL to create the `posts` table with columns id, title, content, and created_at. Uses the InnoDB storage engine, which is important for later functionality. ```sql CREATE TABLE `posts` ( `id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, `title` varchar(255) NOT NULL, `content` text NOT NULL, `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB CHARSET=utf8; ``` -------------------------------- ### Add Nette Plugin Marketplace Source: https://github.com/nette/docs/blob/master/ai/en/getting-started.texy Add the Nette marketplace and enable auto-updating for the Nette plugin. ```shell /plugin marketplace add nette/agent-plugins ``` -------------------------------- ### Tracy mit verzögerter Session-Initialisierung und dispatch() Source: https://github.com/nette/docs/blob/master/tracy/de/recipes.texy Startet Tracy sofort, initialisiert die Session danach und teilt Tracy mit dispatch() mit, dass die Session bereit ist. ```php Debugger::setSessionStorage(new Tracy\NativeSession); Debugger::enable(); // danach folgt die Initialisierung der Session // und der Start der Session session_start(); Debugger::dispatch(); ``` -------------------------------- ### Hide the Tracy Bar Source: https://github.com/nette/docs/blob/master/tracy/en/guide.texy Set Debugger::$showBar to false to prevent the Tracy Bar from being displayed in the bottom right corner. ```php Debugger::$showBar = false; ``` -------------------------------- ### PHP composition with Engine and Car classes Source: https://github.com/nette/docs/blob/master/nette/en/introduction-to-object-oriented-programming.texy Shows composition: the Car class contains an Engine instance instead of inheriting from it. The Car's start() method delegates to the Engine's start() method and then adds its own output. The example creates a Car and calls start(), which prints 'Engine is running.' followed by 'The car is ready to drive!'. ```php class Engine { function start() { echo 'Engine is running.'; } } class Car { private $engine; function __construct() { $this->engine = new Engine; } function start() { $this->engine->start(); echo 'The car is ready to drive!'; } } $car = new Car; $car->start(); ``` -------------------------------- ### fetchField() shortcut Source: https://github.com/nette/docs/blob/master/database/en/sql-way.texy Use fetchField() to get the value of the first column in the first row. This example shows counting rows. ```php // fetchField() - returns the value of the first cell $count = $database->query('SELECT COUNT(*) FROM articles') ->fetchField(); ``` -------------------------------- ### Run the command with Parser and Command::from Source: https://github.com/nette/docs/blob/master/command-line/en/@home.texy Sets up the command from the convert method, parses the command line, and runs it. The method's return value becomes the script's exit code. ```php require __DIR__ . '/vendor/autoload.php'; $converter = new ImageConverter; $program = Command::from($converter->convert(...)); $parser = new Parser; $args = $parser->parse($program); exit($args->run()); ``` -------------------------------- ### Install a development version of nette/utils Source: https://github.com/nette/docs/blob/master/best-practices/en/composer.texy Installs the 4.0.x-dev development version of nette/utils. Use this to test unreleased versions. ```shell composer require nette/utils:4.0.x-dev ``` -------------------------------- ### Example of match method return array Source: https://github.com/nette/docs/blob/master/application/ja/routing.texy Example of the array returned by the match method, containing the presenter name and action. The action is optional and defaults to 'default'. ```php [ 'presenter' => 'Front:Home', 'action' => 'default', ] ``` -------------------------------- ### Example configuration data array Source: https://github.com/nette/docs/blob/master/schema/en/@home.texy An example PHP array representing database connection settings loaded from a configuration file. ```php $data = [ 'user' => 'admin', 'port' => 5432, ]; ``` -------------------------------- ### Test MCP Inspector Prompt Source: https://github.com/nette/docs/blob/master/ai/en/getting-started.texy Prompt to test MCP Inspector. Claude should list services registered in your DI container. ```text What services do I have registered in my DI container? ``` -------------------------------- ### Assign property values and add array elements in setup Source: https://github.com/nette/docs/blob/master/dependency-injection/en/services.texy Shows how to assign values to properties and add elements to arrays in the `setup` section. Array access must be enclosed in quotes to avoid NEON syntax conflicts. ```neon services: foo: create: Foo setup: - $value = 123 - '$onClick[]' = [@bar, clickHandler] ``` -------------------------------- ### Install a specific release candidate of nette/utils Source: https://github.com/nette/docs/blob/master/best-practices/en/composer.texy Installs the 4.0.0-RC2 release candidate of nette/utils. Use this to test a specific pre-release version. ```shell composer require nette/utils:4.0.0-RC2 ``` -------------------------------- ### Run convert.php with arguments and options Source: https://github.com/nette/docs/blob/master/command-line/en/@home.texy Example invocations of the convert.php script. The first converts photo.jpg to logo.png with format png; the second uses --dry-run to only show what would be done. ```shell php convert.php photo.jpg logo.png --format png php convert.php photo.jpg --dry-run ``` -------------------------------- ### Prompt: Generate ArticlePresenter Source: https://github.com/nette/docs/blob/master/ai/en/getting-started.texy Use this prompt to generate a complete ArticlePresenter with list and detail actions, including templates and route suggestions. ```text I need a simple ArticlePresenter with list and detail actions. Generate the presenter, templates, and tell me what routes I need. ``` -------------------------------- ### Get column types with getColumnTypes() Source: https://github.com/nette/docs/blob/master/database/en/sql-way.texy ResultSet provides information about column types. The example iterates over the types and prints each column name and its type. ```php $result = $database->query('SELECT * FROM articles'); $types = $result->getColumnTypes(); foreach ($types as $column => $type) { echo "$column is of type $type"; // e.g., 'id is of type int' } ``` -------------------------------- ### Create sign-in form in SignPresenter Source: https://github.com/nette/docs/blob/master/quickstart/en/authentication.texy Defines a login form with username and password fields, and a submit button. The form's onSuccess callback is set to signInFormSucceeded. ```php <?php namespace App\Presentation\Sign; use Nette; use Nette\Application\UI\Form; final class SignPresenter extends Nette\Application\UI\Presenter { protected function createComponentSignInForm(): Form { $form = new Form; $form->addText('username', 'Username:') ->setRequired('Please enter your username.'); $form->addPassword('password', 'Password:') ->setRequired('Please enter your password.'); $form->addSubmit('send', 'Sign in'); $form->onSuccess[] = $this->signInFormSucceeded(...); return $form; } } ``` -------------------------------- ### Install symfony/thanks globally Source: https://github.com/nette/docs/blob/master/best-practices/en/composer.texy Installs the symfony/thanks package globally to enable thanking open source authors via GitHub stars. ```shell composer global require symfony/thanks ``` -------------------------------- ### aggregation() with simple aggregate function Source: https://github.com/nette/docs/blob/master/database/en/explorer.texy Performs any aggregate function. Example shows AVG(price) and GROUP_CONCAT(tag.name) with fetch() to get the result. ```php // average price of products in a category $avgPrice = $products->where('category_id', 1) ->aggregation('AVG(price)'); // joins product tags into a single string $tags = $products->where('id', 1) ->aggregation('GROUP_CONCAT(tag.name) AS tags') ->fetch() ->tags; ``` -------------------------------- ### Route with detailed parameter configuration Source: https://github.com/nette/docs/blob/master/application/ja/routing.texy Extends the previous example with validation patterns and default values using Route::Value and Route::Pattern constants. ```php use Nette\Routing\Route; $router->addRoute('<presenter>/<action>[/<id>]', [ 'presenter' => [ Route::Value => 'Home', ], 'action' => [ Route::Value => 'default', 'id' => [ Route::Pattern => '\d+', ], ], ]); ``` -------------------------------- ### Redirect unauthenticated users in EditPresenter Source: https://github.com/nette/docs/blob/master/quickstart/en/authentication.texy In the startup method, redirects users who are not logged in to the sign-in page. Prevents access to the edit form for guests. ```php public function startup(): void { parent::startup(); if (!$this->getUser()->isLoggedIn()) { $this->redirect('Sign:in'); } } ``` -------------------------------- ### Running ArrayTest.php - successful output Source: https://github.com/nette/docs/blob/master/tester/en/guide.texy Command to run the test file and its expected output when all assertions pass. The output shows 'OK' with a green background. ```terminal $ php ArrayTest.php OK ``` -------------------------------- ### Prompt: Generate ArticleRow Entity Source: https://github.com/nette/docs/blob/master/ai/en/getting-started.texy Use this prompt to generate an ArticleRow entity with proper type hints based on the article table in your database. ```text Look at my article table and generate an ArticleRow entity with proper type hints. ``` -------------------------------- ### CliTester class with run() method and option handling Source: https://github.com/nette/docs/blob/master/tester/files/coverage.html This snippet shows the start of the CliTester class from the Nette Tester project, including its properties and the beginning of the run() method. It handles the '--colors' option to set Environment::$useColors and checks for 'tap' or 'junit' output formats. The code is truncated in the source, so only the visible portion is included. ```php class CliTester { /** @var array */ private $options; /** @var PhpInterpreter */ private $interpreter; /** @var bool */ private $debugMode = true; /** @var string|null */ private $stdoutFormat; public function run(): ?int { Environment::setupColors(); $this->setupErrors(); ob_start(); $cmd = $this->loadOptions(); if (isset($this->options['--colors'])) { Environment::$useColors = (bool) $this->options['--colors']; } elseif (in_array($this->stdoutFormat, ['tap', 'junit'], true)) { Environment::$useColors = false; } if ($cmd […] ``` -------------------------------- ### Log PHP errors with detailed HTML report Source: https://github.com/nette/docs/blob/master/tracy/en/guide.texy Set `Debugger::$logSeverity` to log PHP errors like `E_NOTICE` or `E_WARNING` with detailed information (HTML report). ```php Debugger::$logSeverity = E_NOTICE | E_WARNING; ``` -------------------------------- ### Render with indentation using render() Source: https://github.com/nette/docs/blob/master/utils/pl/html-elements.texy Use render(?int $indent = null) to output nicely formatted, indented HTML. The example shows calling render(0) to get indented HTML. ```php echo $el->render(0); // zwraca wcięty HTML ``` -------------------------------- ### Display blog posts with foreach loop Source: https://github.com/nette/docs/blob/master/quickstart/en/home-page.texy Modifies Home/default.latte to display blog posts. Uses {foreach $posts as $post} to iterate over posts, with filters |date and |truncate for formatting. The list is not styled yet. ```latte {block content} <h1>My Blog</h1> {foreach $posts as $post} <div class="post"> <div class="date">{$post->created_at|date:'F j, Y'}</div> <h2>{$post->title}</h2> <div>{$post->content|truncate:256}</div> </div> {/foreach} {/block} ``` -------------------------------- ### Test help output with HelpRenderer and Assert::matchFile Source: https://github.com/nette/docs/blob/master/command-line/en/arguments.texy Render help with a fixed width of 80 to avoid terminal-dependent output, then compare it to a stored file. Create help.txt initially by saving the renderToString() result. ```php $renderer = new HelpRenderer(width: 80); Assert::matchFile(__DIR__ . '/help.txt', $renderer->renderToString($program)); ``` -------------------------------- ### Get request origin and host Source: https://github.com/nette/docs/blob/master/http/en/request.texy Returns the origin (scheme, host, port) as UrlImmutable or null if header missing or 'null'. The example shows how to access the origin and its host. ```php $origin = $httpRequest->getOrigin(); echo $origin; // https://example.com:8080 echo $origin?->getHost(); // example.com ``` -------------------------------- ### Set log directory for Tracy Source: https://github.com/nette/docs/blob/master/tracy/en/guide.texy Set the absolute path to the log directory via `$logDirectory` or pass it as the second parameter to `enable()`. Required for error logging in production mode. ```php Debugger::$logDirectory = __DIR__ . '/log'; ``` -------------------------------- ### Multiple commands usage examples Source: https://github.com/nette/docs/blob/master/command-line/en/@home.texy Shows example invocations of a script with multiple commands: convert, resize, and a global --quiet flag. Demonstrates how commands are used in the terminal. ```shell php images.php convert photo.jpg --format png php images.php resize photo.jpg --width 800 php images.php --quiet convert photo.jpg ``` -------------------------------- ### Enable development mode with IP and cookie token Source: https://github.com/nette/docs/blob/master/tracy/en/guide.texy Combine an IP address with a secret token stored in the `tracy-debug` cookie to activate development mode only for developers from that IP who have the token. ```php Debugger::enable('secret1234@23.75.345.200'); ``` -------------------------------- ### slice(string|iterable $value, int $start, ?int $length=null, bool $preserveKeys=false): string|array|\Generator Source: https://github.com/nette/docs/blob/master/latte/en/functions.texy Extracts a slice of an array, a string, or an iterator. This function is used in templates to get a subset of data. ```APIDOC ## Function: slice ### Description Extracts a slice of an array, a string, or an iterator. ### Signature `slice(string|iterable $value, int $start, ?int $length=null, bool $preserveKeys=false): string|array|\Generator` ### Parameters - `$value` (string|iterable) - Required - The input to slice. - `$start` (int) - Required - The starting offset. If negative, starts that far from the end. - `$length` (?int) - Optional - The length of the slice. Defaults to null. - `$preserveKeys` (bool) - Optional - Whether to preserve keys. Defaults to false. ### Return Value - (string|array|\Generator) - The sliced portion. ### Request Example ```latte {=slice('hello', 1, 2)} {* outputs 'el' *} {=slice(['a', 'b', 'c'], 1, 2)} {* outputs ['b', 'c'] *} ``` ``` -------------------------------- ### Añadir código de inicialización con addBody Source: https://github.com/nette/docs/blob/master/dependency-injection/es/extensions.texy En loadConfiguration, se puede añadir código que se ejecute en tiempo de ejecución justo después de crear el contenedor. El ejemplo crea servicios con la etiqueta 'run'. ```php public function loadConfiguration(): void { // los servicios con la etiqueta 'run' deben crearse justo después de arrancar el contenedor $builder = $this->getContainerBuilder(); foreach ($builder->findByTag('run') as $name => $attrs) { $this->initialization->addBody('$this->getService(?);', [$name]); } } ``` -------------------------------- ### Setup functions in bootstrap.php Source: https://github.com/nette/docs/blob/master/tester/en/writing-tests.texy Call Tester\Environment::setup() and setupFunctions() in bootstrap.php to enable the global test() function. This avoids collisions with user-defined functions of the same name. ```php Tester\Environment::setup(); Tester\Environment::setupFunctions(); ``` -------------------------------- ### Get reflection object from database connection Source: https://github.com/nette/docs/blob/master/database/en/reflection.texy Obtain the Nette Database reflection object from a database connection instance. This is the starting point for all structure introspection. ```php $reflection = $database->getReflection(); ``` -------------------------------- ### Printing variables and expressions with {=...} Source: https://github.com/nette/docs/blob/master/latte/en/tags.texy In Latte, the `{=...}` tag prints any expression. The equals sign can be omitted if the expression starts with a variable or function call. The example shows printing variables and a PHP expression. ```latte Name: {$name} {$surname}<br> Age: {date('Y') - $birth}<br> ``` ```latte {='0' . ($num ?? $num * 3) . ', ' . \PHP_VERSION} ``` -------------------------------- ### Log custom messages and exceptions Source: https://github.com/nette/docs/blob/master/tracy/en/guide.texy Use `Debugger::log()` to log text messages or caught exceptions. Passing `Debugger::ERROR` as the second parameter also sends an email notification. ```php Debugger::log('Unexpected error'); // text message try { criticalOperation(); } catch (Exception $e) { Debugger::log($e); // log exception // or Debugger::log($e, Debugger::ERROR); // also sends an email notification } ``` -------------------------------- ### Enable development mode for specific IP address Source: https://github.com/nette/docs/blob/master/tracy/en/guide.texy Use the `enable()` method with an IP address parameter to activate development mode for that IP. You can also provide an array of IP addresses. ```php Debugger::enable('23.75.345.200'); // you can also provide an array of IP addresses ``` -------------------------------- ### Example entry point assets/app.js Source: https://github.com/nette/docs/blob/master/assets/en/vite.texy Main entry point that imports styles and JavaScript modules, then initializes netteForms and naja. ```js // Import styles import './style.css' // Import JavaScript modules import netteForms from 'nette-forms'; import naja from 'naja'; // Initialize your application netteForms.initOnLoad(); naja.initialize(); ``` -------------------------------- ### Manual var_dump check in PHP Source: https://github.com/nette/docs/blob/master/tester/en/guide.texy Shows the typical manual debugging pattern of printing a function result with var_dump to visually verify it. The text contrasts this with writing a self-checking test. ```php $obj = new MyClass; $result = $obj->process($input); var_dump($result); ``` -------------------------------- ### Cursor MCP Configuration (.cursor/mcp.json) Source: https://github.com/nette/docs/blob/master/ai/en/getting-started.texy Configuration file for using MCP Inspector with Cursor. Create this file if your project doesn't have a .cursor directory; otherwise, init writes it for you. ```json { "mcpServers": { "nette-inspector": { "command": "php", "args": ["vendor/bin/mcp-inspector"] } } } ``` -------------------------------- ### Sign-out action in SignPresenter Source: https://github.com/nette/docs/blob/master/quickstart/en/authentication.texy Logs out the user, shows a confirmation message, and redirects to the home page. No template is needed because the user is redirected immediately. ```php public function actionOut(): void { $this->getUser()->logout(); $this->flashMessage('You have been signed out.'); $this->redirect('Home:'); } ``` -------------------------------- ### Prompt: Test Database Introspection Source: https://github.com/nette/docs/blob/master/ai/en/getting-started.texy Use this prompt to test database introspection with MCP Inspector. It asks the AI to list tables and show columns in the user table. ```text What tables do I have? Show me the columns in the user table. ``` -------------------------------- ### Get Property Declaring Class with Reflection::getPropertyDeclaringClass Source: https://github.com/nette/docs/blob/master/utils/en/reflection.texy Returns the reflection of the class or trait that declares the property. The example shows how a property from a trait resolves to the trait's reflection. ```php trait DemoTrait { public $foo; } class DemoClass { use DemoTrait; } $prop = new ReflectionProperty(DemoClass::class, 'foo'); Reflection::getPropertyDeclaringClass($prop); // ReflectionClass('DemoTrait') ``` -------------------------------- ### Installer nette-forms via npm Source: https://github.com/nette/docs/blob/master/forms/fr/validation.texy Installe le paquet nette-forms via npm pour l'utiliser dans un projet JavaScript. ```shell npm install nette-forms ``` -------------------------------- ### Minimal composer.json with nette/database dependency Source: https://github.com/nette/docs/blob/master/best-practices/en/composer.texy Defines a project dependency on nette/database with the ^3.0 version constraint, meaning the latest version 3.x will be installed. This is the simplest composer.json to start using Composer in a project. ```js { "require": { "nette/database": "^3.0" } } ``` -------------------------------- ### Implementar Tracy\IBarPanel con getTab() y getPanel() Source: https://github.com/nette/docs/blob/master/tracy/es/extensions.texy Define un panel básico para la Tracy Bar. Los métodos getTab() y getPanel() deben devolver HTML. Si getPanel() no devuelve nada, solo se muestra la pestaña; si getTab() no devuelve nada, no se muestra nada y getPanel() no se llama. ```php class ExamplePanel implements Tracy\IBarPanel { public function getTab() { return /* ... */; } public function getPanel() { return /* ... */; } } ``` -------------------------------- ### Set email for error notifications Source: https://github.com/nette/docs/blob/master/tracy/en/guide.texy Set `Debugger::$email` to receive email notifications for new log entries. Tracy sends only one message and creates a file `email-sent` to prevent flooding. ```php Debugger::$email = 'admin@example.com'; ``` -------------------------------- ### Test Plugin Knowledge Prompt Source: https://github.com/nette/docs/blob/master/ai/en/getting-started.texy Prompt to test the Nette plugin's knowledge. Claude should respond with detailed information about presenters, models, templates, and configuration from the nette-architecture skill. ```text What's the recommended directory structure for a Nette application? ``` -------------------------------- ### PHP coverage renderer class with highlight setup Source: https://github.com/nette/docs/blob/master/tester/files/coverage.html This PHP snippet shows a class constructor that initializes syntax highlighting via ini_set calls and includes a template file. It also includes a method that checks if files exist before proceeding. The code is from a coverage report renderer, likely part of the Nette framework. ```php public function __construct($file, array $sources = [], string $title = null) { parent::__construct($file, $sources); $this->title = $title; protected function renderSelf(): void { $this->setupHighlight(); $this->parse(); $title = $this->title; $classes = self::CLASSES; $files = $this->files; $coveredPercent = $this->getCoveredPercent(); include __DIR__ . '/template.phtml'; } private function setupHighlight(): void { ini_set('highlight.comment', 'hc'); ini_set('highlight.default', 'hd'); ini_set('highlight.html', 'hh'); ini_set('highlight.keyword', 'hk'); ini_set('highlight.string', 'hs'); } // ... (rest of the method) } ``` -------------------------------- ### Basic Debugger::timer() usage Source: https://github.com/nette/docs/blob/master/tracy/en/stopwatch.texy Starts the timer and returns elapsed time in seconds when called again. The example shows a sleep(2) call resulting in $elapsed = 2. ```php Debugger::timer(); // sweet dreams my cherrie sleep(2); $elapsed = Debugger::timer(); // $elapsed = 2 ``` -------------------------------- ### get() method to fetch row by primary key Source: https://github.com/nette/docs/blob/master/database/en/explorer.texy Executes the SQL query and returns the row by primary key, or null if it doesn't exist. Example checks existence before echoing title. ```php $book = $explorer->table('book')->get(123); // returns ActiveRow with ID 123 or null if ($book) { echo $book->title; } ``` -------------------------------- ### Add Multiple Configuration Files Source: https://github.com/nette/docs/blob/master/application/en/bootstrapping.texy Calls `addConfig()` multiple times to load additional configuration files. The example includes a PHP configuration file for CLI. Later files have higher priority and overwrite or merge items with the same keys. ```php $configDir = $this->rootDir . '/config'; $this->configurator->addConfig($configDir . '/common.neon'); $this->configurator->addConfig($configDir . '/services.neon'); if (PHP_SAPI === 'cli') { $this->configurator->addConfig($configDir . '/cli.php'); } ``` -------------------------------- ### Run Nette Tester on current directory Source: https://github.com/nette/docs/blob/master/tester/en/guide.texy Runs the test runner on the current directory. It searches for files matching *.phpt and *Test.php, runs each test in a separate PHP process, and runs them in parallel. ```terminal vendor/bin/tester . ``` -------------------------------- ### Get Parameter Default Value with Reflection::getParameterDefaultValue Source: https://github.com/nette/docs/blob/master/utils/en/reflection.texy Returns the default value of a parameter, correctly resolving constants and class constants. Throws \ReflectionException if the constant cannot be resolved. The example outputs 123. ```php class DemoClass { const DefaultValue = 123; } function demo($param = DemoClass::DefaultValue) { } $param = new ReflectionParameter('demo', 'param'); echo Reflection::getParameterDefaultValue($param); // 123 ``` -------------------------------- ### Mapeo a objetos con Expect::from(new Config) Source: https://github.com/nette/docs/blob/master/schema/es/@home.texy Expect::from() genera un esquema de estructura a partir de una clase, usando sus propiedades como elementos y respetando los valores predeterminados. ```php class Config { 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} ``` -------------------------------- ### Example output structure after build Source: https://github.com/nette/docs/blob/master/assets/en/vite.texy Shows the output directory structure after running the build command. Hashed filenames ensure browsers always load the latest version. ```text www/assets/ ├── app-4f3a2b1c.js # Your main JavaScript (minified) ├── app-7d8e9f2a.css # Extracted CSS (minified) ├── vendor-8c4b5e6d.js # Shared dependencies └── .vite/ └── manifest.json # Mapping for Nette Assets ``` -------------------------------- ### NEON sequence block notation Source: https://github.com/nette/docs/blob/master/neon/en/format.texy Basic sequence example in NEON block notation. Lines start with a hyphen `-` followed by a space. The value can be a string, number, boolean, null, sequence, or another mapping. ```neon - Cat - Dog - Goldfish ``` -------------------------------- ### Create Nette WebProject with Composer Source: https://github.com/nette/docs/blob/master/application/en/how-it-works.texy Use this command to download the WebProject skeleton, including Nette, via Composer. After creation, set write permissions for the log/ and temp/ directories on Linux or macOS. ```shell composer create-project nette/web-project ``` -------------------------------- ### Class documentation block with @property and @method annotations Source: https://github.com/nette/docs/blob/master/contributing/en/coding-standard.texy Example of a class-level phpDoc block: starts with a description, then an empty line, then @property and @method annotations. @author is omitted; @internal or @deprecated may be used. ```php /** * MIME message part. * * @property string $encoding * @property-read array $headers * @method string getSomething(string $name) * @method static bool isEnabled() */ ``` -------------------------------- ### Disable debug mode in app/Bootstrap.php Source: https://github.com/nette/docs/blob/master/quickstart/en/@home.texy Uncomment the `setDebugMode` line and change the parameter to `false` to disable Tracy in production mode. After refreshing, errors are logged to `log/exception.log` and an HTML error page is saved instead of showing the red screen. ```php // ... $this->configurator->setDebugMode(false); ``` -------------------------------- ### Use vendor/autoload.php to load Nette Database Source: https://github.com/nette/docs/blob/master/best-practices/en/composer.texy Includes the generated vendor/autoload.php to start using library classes without extra work. The example creates a Nette Database connection to an in-memory SQLite database. ```php require __DIR__ . '/vendor/autoload.php'; $db = new Nette\Database\Connection('sqlite::memory:'); ``` -------------------------------- ### AdminPresenter startup: store request and redirect to sign-in Source: https://github.com/nette/docs/blob/master/best-practices/en/restore-request.texy In the startup() method, if the user is not logged in, redirect to Sign:in with a backlink parameter containing the key from storeRequest(). This saves the current request (including form data) to the session before redirecting. ```php class AdminPresenter extends Nette\Application\UI\Presenter { protected function startup() { parent::startup(); if (!$this->user->isLoggedIn()) { $this->redirect('Sign:in', ['backlink' => $this->storeRequest()]); } } } ``` -------------------------------- ### ProductPresenter with renderShow action Source: https://github.com/nette/docs/blob/master/application/en/how-it-works.texy Example presenter class that handles the 'show' action. It injects a ProductRepository via constructor and passes product data to the template. The renderShow method receives the id parameter from the URL. ```php class ProductPresenter extends Nette\Application\UI\Presenter { public function __construct( private ProductRepository $repository, ) { } public function renderShow(int $id): void { // obtain data from the model and pass it to the template $this->template->product = $this->repository->getProduct($id); } } ``` -------------------------------- ### Set strict mode for error display Source: https://github.com/nette/docs/blob/master/tracy/en/guide.texy Configure Debugger::$strictMode to display all errors or all errors except deprecated notices. Tracy changes the error reporting level to E_ALL when activated; adjust it after calling enable(). ```php Debugger::$strictMode = true; // display all errors Debugger::$strictMode = E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED; // all errors except deprecated notices ``` -------------------------------- ### Initialisation différée de la session avec dispatch() Source: https://github.com/nette/docs/blob/master/tracy/fr/recipes.texy Démarre Tracy immédiatement, puis initialise la session et informe Tracy avec dispatch(). setSessionStorage() existe depuis la version 2.9. ```php Debugger::setSessionStorage(new Tracy\NativeSession); Debugger::enable(); // suivi de l'initialisation de la session // et du démarrage de la session session_start(); Debugger::dispatch(); ``` -------------------------------- ### Running ArrayTest.php - failing assertion output Source: https://github.com/nette/docs/blob/master/tester/en/guide.texy Command to run the test file after changing an assertion to a false one, and the resulting failure output. Shows the failed assertion details and 'FAILURE' with a red background. ```terminal $ php ArrayTest.php Failed: ['foo'] should contain 'XXX' in ArrayTest.php(17) Assert::contains('XXX', $stack); FAILURE ``` -------------------------------- ### SimpleRouter instantiation Source: https://github.com/nette/docs/blob/master/application/ru/routing.texy Creates a SimpleRouter with default presenter and action. The default presenter is 'Home' and action is 'default'. ```php // презентером по умолчанию будет 'Home', а действием 'default' $router = new Nette\Application\Routers\SimpleRouter('Home:default'); ``` -------------------------------- ### ArrayTest.php - basic assertions with Nette Tester Source: https://github.com/nette/docs/blob/master/tester/en/guide.texy A complete test file using Tester\Assert to verify array operations. Requires Composer autoloader and Tester\Environment::setup(). Running it prints 'OK' if all assertions pass. ```php <?php use Tester\Assert; require __DIR__ . '/vendor/autoload.php'; # load Composer autoloader Tester\Environment::setup(); # initialize Nette Tester $stack = []; Assert::same(0, count($stack)); # we expect count() to return zero $stack[] = 'foo'; Assert::same(1, count($stack)); # we expect count() to return one Assert::contains('foo', $stack); # verify that $stack contains the item 'foo' ``` -------------------------------- ### Get Use Statements with Reflection::getUseStatements Source: https://github.com/nette/docs/blob/master/utils/en/reflection.texy Returns an array of use statements (aliases) from the file where the class is defined. Requires the tokenizer PHP extension. The example shows the output for the given namespace and imports. ```php namespace Foo; use Nette\Utils\Strings; use Nette\Utils\Arrays as Arr; class DemoClass { } $class = new ReflectionClass(Foo\DemoClass::class); Reflection::getUseStatements($class); // ['Strings' => 'Nette\Utils\Strings', 'Arr' => 'Nette\Utils\Arrays'] ``` -------------------------------- ### Enable Tracy with Debugger::enable() Source: https://github.com/nette/docs/blob/master/tracy/en/guide.texy Activate Tracy at the beginning of the program, before any output is sent. Requires the autoloader or tracy.phar. Tracy is only visible on localhost by default; use Debugger::enable(Debugger::Development) to force development mode. ```php use Tracy\Debugger; require 'vendor/autoload.php'; // alternatively tracy.phar Debugger::enable(); ```