Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

More clear description of sendJSON() method #1061

Open
wants to merge 119 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
119 commits
Select commit Hold shift + click to select a range
69965ae
added best-practices/microsites
dg Sep 6, 2023
7d347b4
latte 3.0.9
dg Sep 8, 2023
3362e5d
filesystem: link to Finder
dg Sep 12, 2023
5ab9698
own page for StaticClass
dg Sep 12, 2023
bdeca62
improved smartobject
dg Sep 12, 2023
8a961eb
nette/utils 4.0.1
dg Jan 17, 2024
93ff78a
nette/utils 4.0.2
dg Sep 19, 2023
4fcabd8
latte: info about Latte\Runtime\Html
dg Sep 19, 2023
bafbffb
Tracy: added mappings
dg Sep 22, 2023
bd38bde
robot-loader: info about standalone usage
dg Sep 26, 2023
95f937e
typo
dg Sep 27, 2023
cde7d29
neon: improved syntax description
dg Sep 27, 2023
9646248
di: neon syntax improvements
dg Sep 27, 2023
85b137c
turning cache off
dg Oct 2, 2023
b34a7ca
typo [closes #1022]
dg Oct 5, 2023
40e17f5
nette/di v3.1.8 [Closes #1031]
dg Oct 2, 2023
a8ece7a
nette/schema 1.2.5
dg Oct 4, 2023
43d6215
nette/application v3.1.14
dg Oct 4, 2023
6a5ebe1
improvements
dg Oct 5, 2023
35101fb
nette/forms 3.1.12
dg Oct 10, 2023
ef84794
latte 3.0.10
dg Oct 11, 2023
12e2d54
services: improved text
dg Oct 13, 2023
71f5cfb
form validation: improved
dg Oct 15, 2023
58166cb
forms: used unpkg.com for netteForms
dg Oct 15, 2023
fc920eb
ajax: improved
dg Oct 15, 2023
8427ee1
forms: improved in about disabled fields
dg Oct 20, 2023
2b7b21a
intro to oop
dg Oct 24, 2023
470c613
links to oop
dg Oct 25, 2023
32a6f53
fixed link
dg Oct 25, 2023
bd232a8
Typo (#1034)
pat0s Oct 29, 2023
8e3a29f
nette/forms 3.1.14
dg Oct 29, 2023
e3a4ac4
nette/utils 4.0.2
dg Oct 29, 2023
36171f6
php-generator: improved perex etc
dg Nov 1, 2023
0be2e7e
robot-loader: improved translation
dg Nov 1, 2023
a5a9583
php-generator: improved EN translation
dg Nov 1, 2023
fb2b197
latte 3.0.12
dg Nov 9, 2023
d18a54b
updated PHP requirements
dg Nov 13, 2023
97064a4
composer: ignore upper boundary
dg Nov 21, 2023
c62f118
forms 3.1.15
dg Nov 11, 2023
baebce6
nette/database v3.2
dg Dec 14, 2023
1956b1c
Arrays::associate
dg Nov 25, 2023
8dc3152
typo (#1036)
Jonezzyboy Dec 26, 2023
461b6fa
troubleshooting: fixed info
dg Dec 26, 2023
bdca558
neon: added missing parameter (#1037)
sallyx Dec 26, 2023
b698ccb
typo
dg Dec 31, 2023
56bde14
nette/utils 4.0.4
dg Jan 17, 2024
a99d512
tester: option -l replaced with -o
smuuf Jan 21, 2024
b447533
nette/tester 2.5.2
dg Jan 21, 2024
63f10b1
nette/http 3.2.4
dg Jan 30, 2024
fdecd47
nette/application 3.2
dg Feb 8, 2024
d38b3cf
nette/component-model 3.1.0
dg Feb 8, 2024
a55e9c7
nette/di 3.2
dg Feb 12, 2024
62cf754
added utils/upgrading
dg Mar 2, 2024
160b668
typo
nextMJ Feb 17, 2024
f932041
updated web-project
dg Feb 18, 2024
1f65728
migrations updated
dg Mar 2, 2024
4fcc406
migration guide for Nette 3.2 [WIP]
dg Feb 10, 2023
fd6b154
oop: improvements
dg Mar 10, 2024
f33c95a
nette/application 3.2.1
dg Mar 11, 2024
0195403
floats: note about precision
dg Mar 12, 2024
2cf34aa
typo (#1046)
mildabre Mar 18, 2024
5c685c2
Fixed PhpStorm typo (#1045)
hermajan Mar 18, 2024
ee998de
application: better wording [Closes nette/application#323]
dg Mar 19, 2024
1eeb8c8
Grammar corrected in documentation (#1044)
rastographics Mar 19, 2024
385ef56
Typo. (#1042)
radekdostal Mar 19, 2024
746be14
latte: vscode plugin
dg Apr 3, 2024
49541dc
typo
dg Apr 4, 2024
43a3990
typo
dg Apr 18, 2024
905c5a4
uses GitHub Actions
dg Apr 4, 2024
b4acaf8
latte: simplified "{..}"
dg Apr 6, 2024
c6737e3
typo
dg Apr 15, 2024
67d0eab
nette/application 3.2.3
dg Apr 18, 2024
8974872
nette/application 3.2.3: new directory structure
dg Apr 18, 2024
5a8ec70
new directory structure throughout documentation
dg Apr 18, 2024
ca2c925
best practices: attribute Requires
dg Apr 18, 2024
dd924c1
nette/bootstrap 3.2.3
dg Apr 19, 2024
70575af
forms: info about hidden field security
dg Apr 22, 2024
edf99fc
typo
dg Apr 25, 2024
9fdffea
tracy: AJAX debugging
dg May 2, 2024
b8cc3a3
tester 2.5.3
dg May 3, 2024
a8ea090
forms: missing information added
dg May 5, 2024
2c8bafb
forms: slightly improved HTML attributes
dg May 5, 2024
83db98b
nette/database 3.2.1
dg May 7, 2024
f23722f
iteratewhile -> grouping
dg May 14, 2024
cb8fb99
latte 3.0.16
dg May 14, 2024
e0f541e
latte: adding |group to the grouping
dg May 14, 2024
c35880e
latte: pictograms
dg May 16, 2024
d870d6a
http: missing fragment warning
dg May 17, 2024
7de788c
latte: added passing-variables
dg May 20, 2024
c44211b
typo
dg May 24, 2024
aae4351
routing: better wording
dg May 28, 2024
a3d5712
bootstrap: $appDir -> $rootDir
dg Aug 3, 2024
feb8491
nette/forms 3.2.4
dg Aug 5, 2024
b64eace
latte 3.0.18
dg Aug 6, 2024
f1bd69f
typo (#1052)
buffus Aug 6, 2024
975a88c
nette/caching 3.3.1
dg Aug 7, 2024
846221e
nette/utils 4.0.5
dg Aug 7, 2024
13d4470
nette/database 3.2.4
dg Aug 9, 2024
ea66fe8
typo
dg Sep 4, 2024
aeb7097
php-generator 4.1.6
dg Sep 10, 2024
16181a4
nette/application 3.2.6
dg Jun 9, 2024
d8f3f80
new translation wip
dg Sep 1, 2024
b0de7ec
latte improved
dg Sep 4, 2024
b7f1ba6
Typos (#1057)
mezotv Oct 4, 2024
bdde973
typo [Closes #1050]
dg Oct 4, 2024
a33ad75
nette/schema 1.3.2
dg Oct 5, 2024
a6271a5
typo
dg Oct 23, 2024
5028b64
Forms: added missing parameters
dg Oct 23, 2024
88e5c68
fixed type hints
dg Oct 23, 2024
ba24c4e
[filter] has same signature as [method]
dg Oct 23, 2024
0f2188a
typo
jvitasek Oct 23, 2024
932c8db
ajax: Naja initialization info [Closes #1053]
dg Oct 23, 2024
48401ac
upgrading: added exception class change info (finder) [Closes #1051]
Rixafy Jul 1, 2024
9831113
typo [Closes #1049]
diegosardina Jun 9, 2024
f99ff6f
better wording [Closes #1038][Closes #1040][Closes #1026][Closes #10…
mildabre Jan 24, 2024
2381d0d
typo [Closes #1024]
mabar Jun 25, 2023
a75ee13
components: added info about redirect after signal [Closes #1017]
dg May 30, 2023
6c64b1f
new Bootstrap API
dg Oct 24, 2024
d96b10a
More clear description of sendJSON() method
mildabre Nov 2, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
17 changes: 17 additions & 0 deletions .github/workflows/coding-style.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
name: Coding Style

on: [push, pull_request]

jobs:
nette_cc:
name: Nette Code Checker
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: shivammathur/setup-php@v2
with:
php-version: 8.3
coverage: none

- run: composer create-project nette/code-checker temp/code-checker ^3 --no-progress
- run: php temp/code-checker/code-checker --no-progress
13 changes: 0 additions & 13 deletions .travis.yml

This file was deleted.

5 changes: 3 additions & 2 deletions application/bg/@home.texy
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,9 @@ composer require nette/application

| версия на пакета | съвместима версия на PHP
|-----------------------|-----------------------
| Nette Application 4.0 | PHP 8.0 - 8.1
| Nette Application 3.1 | PHP 7.2 - 8.1
| Nette Application 4.0 | PHP 8.1 – 8.3
| Nette Application 3.2 | PHP 8.1 – 8.3
| Nette Application 3.1 | PHP 7.2 – 8.3
| Nette Application 3.0 | PHP 7.1 - 8.0
| Nette Application 2.4 | PHP 5.6 - 8.0

Expand Down
268 changes: 116 additions & 152 deletions application/bg/ajax.texy

Large diffs are not rendered by default.

107 changes: 71 additions & 36 deletions application/bg/bootstrap.texy
Original file line number Diff line number Diff line change
Expand Up @@ -20,18 +20,44 @@ use Nette\Bootstrap\Configurator;

class Bootstrap
{
public static function boot(): Configurator
private Configurator $configurator;
private string $rootDir;

public function __construct()
{
$this->rootDir = dirname(__DIR__);
// Конфигураторът отговаря за настройката на средата на приложението и услугите.
$this->configurator = new Configurator;
// Задайте директорията за временни файлове, генерирани от Nette (напр. компилирани шаблони)
$this->configurator->setTempDirectory($this->rootDir . '/temp');
}

public function bootWebApplication(): Nette\DI\Container
{
$appDir = dirname(__DIR__);
$configurator = new Configurator;
//$configurator->setDebugMode('[email protected]');
$configurator->enableTracy($appDir . '/log');
$configurator->setTempDirectory($appDir . '/temp');
$configurator->createRobotLoader()
$this->initializeEnvironment();
$this->setupContainer();
return $this->configurator->createContainer();
}

private function initializeEnvironment(): void
{
// Nette е интелигентен и режимът за разработка се включва автоматично,
// или можете да го включите за определен IP адрес, като разкоментирате следния ред:
// $this->configurator->setDebugMode('[email protected]');

// Активира Tracy: най-добрият инструмент за отстраняване на грешки "швейцарско ножче".
$this->configurator->enableTracy($this->rootDir . '/log');

// RobotLoader: автоматично зарежда всички класове в дадената директория
$this->configurator->createRobotLoader()
->addDirectory(__DIR__)
->register();
$configurator->addConfig($appDir . '/config/common.neon');
return $configurator;
}

private function setupContainer(): void
{
// Зареждане на конфигурационни файлове
$this->configurator->addConfig($this->rootDir . '/config/common.neon');
}
}
```
Expand All @@ -40,16 +66,15 @@ class Bootstrap
index.php .[#toc-index-php]
===========================

В случая на уеб приложения началният файл е `index.php`, който се намира в публичната директория `www/`. Той позволява на класа `Bootstrap` да инициализира средата и връща `$configurator`, който създава контейнера DI. След това тя извлича услугата `Application`, която стартира уеб приложението:
Началният файл за уеб приложенията е `index.php`, разположен в публичната директория `www/`. Той използва класа `Bootstrap` за инициализиране на средата и създаване на контейнер DI. След това получава услугата `Application` от контейнера, която стартира уеб приложението:

```php
// инициализиране на средата + получаване на обект Configurator
$configurator = App\Bootstrap::boot();
// създаване на DI-контейнер
$container = $configurator->createContainer();
// DI-контейнерът ще създаде обект Nette\Application\Application
$bootstrap = new App\Bootstrap;
// Иницииране на средата + създаване на контейнер DI
$container = $bootstrap->bootWebApplication();
// Контейнерът DI създава обект Nette\Application\Application
$application = $container->getByType(Nette\Application\Application::class);
//стартиране на приложението Nette
// Стартирайте приложението Nette и обработете входящата заявка
$application->run();
```

Expand All @@ -66,19 +91,19 @@ Nette прави разграничение между два основни р
Ако искате да активирате режима за разработка в други случаи, например за програмисти, които имат достъп от определен IP адрес, можете да използвате `setDebugMode()`:

```php
$configurator->setDebugMode('23.75.345.200'); // един или повече IP адреси
$this->configurator->setDebugMode('23.75.345.200'); // един или повече IP адреси
```

Определено препоръчваме да комбинирате IP адреса с "бисквитка". Ще съхраним тайния токен в "бисквитката" `nette-debug', например, `secret1234`, а режимът за разработка ще бъде активиран за програмистите с тази комбинация от IP и "бисквитка".

```php
$configurator->setDebugMode('[email protected]');
$this->configurator->setDebugMode('[email protected]');
```

Можете да деактивирате напълно режима за разработчици, дори за localhost:

```php
$configurator->setDebugMode(false);
$this->configurator->setDebugMode(false);
```

Обърнете внимание, че стойността `true` активира плътно режима за разработчици, което никога не трябва да се случва на производствен сървър.
Expand All @@ -90,7 +115,7 @@ $configurator->setDebugMode(false);
За да улесним дебъгването, ще включим чудесния инструмент [Tracy |tracy:]. В режим за разработчици той визуализира грешките, а в производствен режим записва грешките в определена директория:

```php
$configurator->enableTracy($appDir . '/log');
$this->configurator->enableTracy($this->rootDir . '/log');
```


Expand All @@ -100,7 +125,7 @@ $configurator->enableTracy($appDir . '/log');
Nette използва кеш за DI-контейнер, RobotLoader, шаблони и др. Затова е необходимо да се зададе пътят до директорията, в която се съхранява кешът:

```php
$configurator->setTempDirectory($appDir . '/temp');
$this->configurator->setTempDirectory($this->rootDir . '/temp');
```

В Linux или macOS задайте [разрешения за запис |nette:troubleshooting#Setting-Directory-Permissions] за директориите `log/` и `temp/`.
Expand All @@ -112,7 +137,7 @@ RobotLoader .[#toc-robotloader]
Обикновено искаме да заредим класовете автоматично с помощта на [RobotLoader |robot-loader:], така че трябва да го стартираме и да му позволим да зареди класовете от директорията, в която се намира `Bootstrap.php` (т.е. `__DIR__`) и всички негови поддиректории:

```php
$configurator->createRobotLoader()
$this->configurator->createRobotLoader()
->addDirectory(__DIR__)
->register();
```
Expand All @@ -126,7 +151,7 @@ $configurator->createRobotLoader()
Конфигураторът ви позволява да зададете часовата зона за вашето приложение.

```php
$configurator->setTimeZone('Europe/Prague');
$this->configurator->setTimeZone('Europe/Prague');
```


Expand All @@ -143,16 +168,17 @@ $configurator->setTimeZone('Europe/Prague');
Файловете за конфигурация се зареждат с помощта на `addConfig()`:

```php
$configurator->addConfig($appDir . '/config/common.neon');
$this->configurator->addConfig($this->rootDir . '/config/common.neon');
```

Методът `addConfig()` може да се извика няколко пъти, за да се добавят няколко файла.

```php
$configurator->addConfig($appDir . '/config/common.neon');
$configurator->addConfig($appDir . '/config/local.neon');
$configDir = $this->rootDir . '/config';
$this->configurator->addConfig($configDir . '/common.neon');
$this->configurator->addConfig($configDir . '/services.neon');
if (PHP_SAPI === 'cli') {
$configurator->addConfig($appDir . '/config/cli.php');
$this->configurator->addConfig($configDir . '/cli.php');
}
```

Expand All @@ -169,7 +195,7 @@ if (PHP_SAPI === 'cli') {
Параметрите, използвани в конфигурационните файлове, могат да бъдат дефинирани [в раздела `parameters` |dependency-injection:configuration#parameters] и да бъдат взети (или презаписани) от метода `addStaticParameters()` (той има псевдоним `addParameters()`). Важно е, че различните стойности на параметрите водят до генериране на допълнителни DI-контейнери, т.е. допълнителни класове.

```php
$configurator->addStaticParameters([
$this->configurator->addStaticParameters([
'projectId' => 23,
]);
```
Expand All @@ -183,15 +209,15 @@ $configurator->addStaticParameters([
Възможно е също така да се добавят динамични параметри към контейнер. Различните им стойности, за разлика от статичните параметри, не генерират нови контейнери DI.

```php
$configurator->addDynamicParameters([
$this->configurator->addDynamicParameters([
'remoteIp' => $_SERVER['REMOTE_ADDR'],
]);
```

Достъпът до променливите на средата е лесен с помощта на динамични параметри. Достъпът до тях се осъществява чрез `%env.variable%` в конфигурационните файлове.

```php
$configurator->addDynamicParameters([
$this->configurator->addDynamicParameters([
'env' => getenv(),
]);
```
Expand All @@ -206,6 +232,7 @@ $configurator->addDynamicParameters([
- `%wwwDir%` е абсолютният път до директорията, съдържаща входния файл `index.php`
- `%tempDir%` е абсолютният път до директорията за временни файлове
- `%vendorDir%` е абсолютният път до директорията, в която Composer инсталира библиотеки
- `%rootDir%` е абсолютният път до главната директория на проекта
- `%debugMode%` показва дали приложението е в режим на отстраняване на грешки
- `%consoleMode%` показва дали заявката е постъпила от командния ред

Expand All @@ -225,7 +252,7 @@ services:
Създайте нов екземпляр и го вмъкнете в Bootstrap:

```php
$configurator->addServices([
$this->configurator->addServices([
'myservice' => new App\Model\MyCustomService('foobar'),
]);
```
Expand All @@ -234,13 +261,21 @@ $configurator->addServices([
Различни среди .[#toc-different-environments]
=============================================

Не се колебайте да персонализирате класа `Bootstrap` според нуждите си. Можете да добавите параметри към метода `boot()`, за да разделите уеб проектите, или да добавите други методи, като например `bootForTests()`, който инициализира средата за тестове на единици, `bootForCli()` за скриптове, извикани от командния ред, и т.н.
Не се колебайте да персонализирате класа `Bootstrap` според нуждите си. Можете да добавите параметри към метода `bootWebApplication()`, за да разграничите отделните уеб проекти. Като алтернатива можете да добавите и други методи, например `bootTestEnvironment()` за инициализиране на средата за unit тестове, `bootConsoleApplication()` за скриптове, извикани от командния ред, и т.н.

```php
public static function bootForTests(): Configurator
public function bootTestEnvironment(): Nette\DI\Container
{
Tester\Environment::setup(); // Инициализация на Nette Tester
$this->setupContainer();
return $this->configurator->createContainer();
}

public function bootConsoleApplication(): Nette\DI\Container
{
$configurator = self::boot();
Tester\Environment::setup(); // Инициализация Nette Tester
return $configurator;
$this->configurator->setDebugMode(false);
$this->initializeEnvironment();
$this->setupContainer();
return $this->configurator->createContainer();
}
```
26 changes: 24 additions & 2 deletions application/bg/components.texy
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,28 @@ $this->redirect(/* ... */); // пренасочване
```


Пренасочване след сигнал .[#toc-redirection-after-a-signal]
===========================================================

След обработката на сигнал от компонент често следва пренасочване. Тази ситуация е подобна на формулярите - след изпращане на формуляр също пренасочваме, за да предотвратим повторното изпращане на данни, когато страницата се опреснява в браузъра.

```php
$this->redirect('this') // redirects to the current presenter and action
```

Тъй като компонентът е елемент за многократна употреба и обикновено не трябва да има пряка зависимост от конкретни презентатори, методите `redirect()` и `link()` автоматично интерпретират параметъра като сигнал за компонент:

```php
$this->redirect('click') // redirects to the 'click' signal of the same component
```

Ако трябва да пренасочите към друг презентатор или действие, можете да го направите чрез презентатора:

```php
$this->getPresenter()->redirect('Product:show'); // redirects to a different presenter/action
```


Постоянни параметри .[#toc-persistent-parameters]
=================================================

Expand Down Expand Up @@ -347,7 +369,7 @@ services:
Накрая ще използваме тази фабрика в нашия презентатор:

```php
class PollPresenter extends Nette\UI\Application\Presenter
class PollPresenter extends Nette\Application\UI\Presenter
{
public function __construct(
private PollControlFactory $pollControlFactory,
Expand Down Expand Up @@ -380,7 +402,7 @@ interface PollControlFactory
Компонентите в Nette Application са части за многократна употреба на уеб приложение, които вграждаме в страници, което е предмет на тази глава. Какви са възможностите на такъв компонент?

1) може да се показва в шаблон
2) той знае каква част от себе си да покаже по време на [заявката AJAX |ajax#invalidation] (фрагменти)
2) знае [коя част от себе си |ajax#snippets] да визуализира по време на заявка AJAX (фрагменти).
3) има възможност да съхранява състоянието си в URL (постоянни параметри).
4) има възможност да реагира на действията (сигналите) на потребителя.
5) създава йерархична структура (където коренът е главният).
Expand Down
Loading
Loading