mirror of
https://github.com/yiisoft/yii2.git
synced 2025-11-23 18:18:21 +08:00
Merge pull request #3 from yiisoft/master
Merge pull request #3 from yiisoft/master
This commit is contained in:
202
docs/guide-it/README.md
Normal file
202
docs/guide-it/README.md
Normal file
@@ -0,0 +1,202 @@
|
||||
La guida definitiva a Yii 2.0
|
||||
=============================
|
||||
|
||||
Questa guida è rilasciata nei [termini della documnetazione di Yii](http://www.yiiframework.com/doc/terms/).
|
||||
|
||||
Tutti i diritti riservati.
|
||||
|
||||
2014 (c) Yii Software LLC.
|
||||
|
||||
Traduzione italiana a cura di Lorenzo Milesi ([yetopen.it](http://www.yetopen.it)).
|
||||
|
||||
|
||||
Introduzione
|
||||
------------
|
||||
|
||||
* [Informazioni su Yii](intro-yii.md)
|
||||
* [Aggiornare dalla versione 1.1](intro-upgrade-from-v1.md)
|
||||
|
||||
|
||||
Primi passi
|
||||
-----------
|
||||
|
||||
* [Installare Yii](start-installation.md)
|
||||
* [Esecuzione applicazioni](start-workflow.md)
|
||||
* [Dire Ciao](start-hello.md)
|
||||
* [Utilizzo dei form](start-forms.md)
|
||||
* [Utilizzo dei database](start-databases.md)
|
||||
* [Generare codice con Gii](start-gii.md)
|
||||
* [Passi successivi](start-looking-ahead.md)
|
||||
|
||||
|
||||
Struttura dell'applicazione
|
||||
---------------------------
|
||||
|
||||
* [Panoramica](structure-overview.md)
|
||||
* [Entry Scripts](structure-entry-scripts.md)
|
||||
* [Applicazioni](structure-applications.md)
|
||||
* [Componenti applicazioni](structure-application-components.md)
|
||||
* [Controller](structure-controllers.md)
|
||||
* [Modelli](structure-models.md)
|
||||
* [Viste](structure-views.md)
|
||||
* [Moduli](structure-modules.md)
|
||||
* [Filtri](structure-filters.md)
|
||||
* [Widget](structure-widgets.md)
|
||||
* [Asset](structure-assets.md)
|
||||
* [Estensioni](structure-extensions.md)
|
||||
|
||||
|
||||
Gestione delle richieste
|
||||
------------------------
|
||||
|
||||
* [Panoramica](runtime-overview.md)
|
||||
* [Bootstrapping](runtime-bootstrapping.md)
|
||||
* [Instradamenti (routing)](runtime-routing.md)
|
||||
* [Richieste](runtime-requests.md)
|
||||
* [Risposte](runtime-responses.md)
|
||||
* **TBD** [Sessioni e cookie](runtime-sessions-cookies.md)
|
||||
* [Analisi e generazione URL](runtime-url-handling.md)
|
||||
* [Gestione errori](runtime-handling-errors.md)
|
||||
* [Log](runtime-logging.md)
|
||||
|
||||
|
||||
Concetti chiave
|
||||
---------------
|
||||
|
||||
* [Componenti](concept-components.md)
|
||||
* [Proprietà](concept-properties.md)
|
||||
* [Eventi](concept-events.md)
|
||||
* [Behavior](concept-behaviors.md)
|
||||
* [Configurazioni](concept-configurations.md)
|
||||
* [Alias](concept-aliases.md)
|
||||
* [Caricamento automatico delle classi (autoload)](concept-autoloading.md)
|
||||
* [Service Locator](concept-service-locator.md)
|
||||
* [Container per Dependency Injection](concept-di-container.md)
|
||||
|
||||
|
||||
Utilizzo del database
|
||||
------------------------
|
||||
|
||||
* [Data Access Objects](db-dao.md): Connessione ad un database, query semplici, transazioni e modifiche allo schema
|
||||
* [Query Builder](db-query-builder.md): Esecuzione di query al database usando un semplice livello di astrazione
|
||||
* [Active Record](db-active-record.md): The Active Record ORM, retrieving and manipulating records, and defining relations
|
||||
* [Migrazoni](db-migrations.md): Applicare il controllo di versione al database in un ambiente di sviluppo di gruppo
|
||||
* **TBD** [Sphinx](db-sphinx.md)
|
||||
* **TBD** [Redis](db-redis.md)
|
||||
* **TBD** [MongoDB](db-mongodb.md)
|
||||
* **TBD** [ElasticSearch](db-elasticsearch.md)
|
||||
|
||||
|
||||
Ricezione dati dagli utenti
|
||||
---------------------------
|
||||
|
||||
* [Creare form](input-forms.md)
|
||||
* [Validazione informazioni](input-validation.md)
|
||||
* **TBD** [Caricamento file](input-file-upload.md)
|
||||
* **TBD** [Raccogliere dati per più modelli](input-multiple-models.md)
|
||||
|
||||
|
||||
Visualizzazione dei dati
|
||||
------------------------
|
||||
|
||||
* **TBD** [Formattazione](output-formatter.md)
|
||||
* **TBD** [Paginazione](output-pagination.md)
|
||||
* **TBD** [Ordinamento](output-sorting.md)
|
||||
* [Data Provider](output-data-providers.md)
|
||||
* [Data Widget](output-data-widgets.md)
|
||||
* [Utilizzo del Client Scripts](output-client-scripts.md)
|
||||
* [Temi](output-theming.md)
|
||||
|
||||
|
||||
Sicurezza
|
||||
---------
|
||||
|
||||
* [Autenticazione](security-authentication.md)
|
||||
* [Autorizzazione](security-authorization.md)
|
||||
* [Utilizzo delle password](security-passwords.md)
|
||||
* **TBD** [Auth Clients](security-auth-clients.md)
|
||||
* **TBD** [Buona prassi](security-best-practices.md)
|
||||
|
||||
|
||||
Cache
|
||||
-----
|
||||
|
||||
* [Panoramica](caching-overview.md)
|
||||
* [Cache dati](caching-data.md)
|
||||
* [Fragment Caching](caching-fragment.md)
|
||||
* [Cache pagina](caching-page.md)
|
||||
* [Cache HTTP](caching-http.md)
|
||||
|
||||
|
||||
Servizi web RESTful
|
||||
-------------------
|
||||
|
||||
* [Avvio veloce](rest-quick-start.md)
|
||||
* [Risorse](rest-resources.md)
|
||||
* [Controller](rest-controllers.md)
|
||||
* [Instradamenti](rest-routing.md)
|
||||
* [Formattazione risposte](rest-response-formatting.md)
|
||||
* [Autenticazione](rest-authentication.md)
|
||||
* [Limitazione di utilizzo](rest-rate-limiting.md)
|
||||
* [Versioning](rest-versioning.md)
|
||||
* [Gestione degli errori](rest-error-handling.md)
|
||||
|
||||
|
||||
Strumenti di sviluppo
|
||||
---------------------
|
||||
|
||||
* [Barra di debug e debugger](tool-debugger.md)
|
||||
* [Generazione codice con Gii](tool-gii.md)
|
||||
* **TBD** [Generazione documentazione API](tool-api-doc.md)
|
||||
|
||||
|
||||
Test
|
||||
----
|
||||
|
||||
* [Panoramica](test-overview.md)
|
||||
* [Inizializzazione ambiente di test](test-environment-setup.md)
|
||||
* [Unit Test](test-unit.md)
|
||||
* [Functional Test](test-functional.md)
|
||||
* [Acceptance Test](test-acceptance.md)
|
||||
* [Fixture](test-fixtures.md)
|
||||
|
||||
|
||||
Argomenti speciali
|
||||
------------------
|
||||
|
||||
* [Modello di applicazione avanzata](tutorial-advanced-app.md)
|
||||
* [Creazione di una applicazione da zero](tutorial-start-from-scratch.md)
|
||||
* [Comandi da console](tutorial-console.md)
|
||||
* [Validazioni predefinite](tutorial-core-validators.md)
|
||||
* [Internazionalizzazione](tutorial-i18n.md)
|
||||
* [Invio email](tutorial-mailing.md)
|
||||
* [Ottimizzazione delle prestazioni](tutorial-performance-tuning.md)
|
||||
* **TBD** [Ambienti di hosting condiviso](tutorial-shared-hosting.md)
|
||||
* [Template Engine](tutorial-template-engines.md)
|
||||
* [Utilizzo di codice di terze parti](tutorial-yii-integration.md)
|
||||
|
||||
|
||||
Widget
|
||||
------
|
||||
|
||||
* GridView: link to demo page
|
||||
* ListView: link to demo page
|
||||
* DetailView: link to demo page
|
||||
* ActiveForm: link to demo page
|
||||
* Pjax: link to demo page
|
||||
* Menu: link to demo page
|
||||
* LinkPager: link to demo page
|
||||
* LinkSorter: link to demo page
|
||||
* [Widget Bootstrap](widget-bootstrap.md)
|
||||
* [Widget Jquery UI](widget-jui.md)
|
||||
|
||||
|
||||
Helper
|
||||
------
|
||||
|
||||
* [Panoramica](helper-overview.md)
|
||||
* **TBD** [ArrayHelper](helper-array.md)
|
||||
* **TBD** [Html](helper-html.md)
|
||||
* **TBD** [Url](helper-url.md)
|
||||
* **TBD** [Security](helper-security.md)
|
||||
|
||||
59
docs/guide-it/intro-yii.md
Normal file
59
docs/guide-it/intro-yii.md
Normal file
@@ -0,0 +1,59 @@
|
||||
Cos'è Yii
|
||||
===========
|
||||
|
||||
Yii è un framework PHP ad alte prestazioni, basato su component, per lo sviluppo veloce di applicazioni web moderne.
|
||||
Il nome Yii (pronunciato `Yii` o `[ji:]`) significa "semplice ed evoutivo" in cinese. Può anche essere visto come un acronimo di **Yes It Iss** (si lo è)!
|
||||
|
||||
|
||||
Qual'è il migliore impiego di Yii?
|
||||
----------------------------------
|
||||
|
||||
Yii è un framework di programmazione, il che significa che può essere utilizzato per sviluppare ogni
|
||||
tipo di appicazione con PHP. Grazie alla sua architettura basata sui componenti e al suo avanzato
|
||||
supporto della cache, è particolarmente adeguato per lo sviluppo di applicazioni su larga scala quali
|
||||
portali, forum, gestori di contenuti (CMS), progetti di e-commerce, servizi web RESTful, e così via.
|
||||
|
||||
|
||||
Come si pone Yii rispetto ad altri framework?
|
||||
---------------------------------------------
|
||||
|
||||
Se hai già familiarità con altri framework potrai apprezzare questi punti in comune:
|
||||
- Come la maggior parte dei framework, Yii implementa il paradigma di sviluppo MVC (Model-View-Controller) e
|
||||
promuove l'organizzazione del codice secondo quelle regole.
|
||||
- Yii usa la filosofia secondo cui il codice dovrebbe essere semplice ed elegante. Yii non cercherà mai di
|
||||
ridisegnare le cose solo per seguire dei pattern di sviluppo.
|
||||
- Yii è un framework completo in grado di fornire diverse funzionalità testate e pronte all'uso: costruttori di
|
||||
query ed ActiveRecord sia per i database relazionali che NoSQL; supporto allo sviluppo di applicazioni RESTful;
|
||||
supporto di caching a diversi livelli; e altro.
|
||||
- Yii è estremamente estensibile. Puoi pesonalizzare o sostituire quasi ogni singolo pezzo del codice base. Puoi anche
|
||||
sfuttare la solida architettura delle estensioni di Yii per usare o sviluppare estensioni ridistribuibili.
|
||||
- Le prestazioni elevate sono sempre il focus primario di Yii.
|
||||
|
||||
Yii non è frutto di un uomo solo, ma è supportato da un [folto gruppo di sviluppatori][], così come da una numerosa
|
||||
comunità di professionisti che contribuiscono costantemente allo sviluppo. Il gruppo di sviluppatori tiene sempre
|
||||
sott'occhio le ultime tendenze e tecnologie di sviluppo web, sulle pratiche ottimali e funzionalità degli altri
|
||||
framework e progetti. Le peculiarità più rilevanti che si trovano altrove sono regolarmente incorporate nel
|
||||
codice principale del framework, e rese disponibili tramite semplici ed eleganti interfacce.
|
||||
|
||||
[folto gruppo di sviluppatori]: http://www.yiiframework.com/about/
|
||||
|
||||
Versioni di Yii
|
||||
---------------
|
||||
|
||||
Yii al momento ha due versioni principali disponibili: 1.1 e 2.0. La versione 1.1 è la vecchia generazione ed è ora in
|
||||
uno stato di manutenzione. La versione 2.0 è una riscrittura completa di Yii che utilizza le ultime tecnologie e protocolli,
|
||||
inclusi Composer, PSR, namespace, trait, e così via. La versione 2.0 rappresenta l'attuale generazione del framework e
|
||||
riceverà i maggiori sforzi di sviluppo nei prossimi anni.
|
||||
Questa guida è focalizzata principalmente sulla versione 2.0.
|
||||
|
||||
|
||||
Richieste e requisiti di sistema
|
||||
---------------------------------
|
||||
|
||||
Yii 2.0 richiede PHP 5.4.0 o successivo. Puoi trovare maggiori dettagli sulle richieste delle singole funzionalità
|
||||
eseguendo lo script di verifica requisiti incluso in ogni versione di Yii.
|
||||
|
||||
L'uso di Yii richiede una conoscenza base della programmazione ad oggetti (OOP), dato che Yii è un framework puramente OOP.
|
||||
Yii 2.0 fa uso delle più recenti funzionalità di PHP, come i [namespace](http://www.php.net/manual/it/language.namespaces.php) e
|
||||
[trait](http://www.php.net/manual/it/language.oop5.traits.php). La compresione di questi concetti ti aiuterà a semplificare
|
||||
l'uso di Yii 2.0.
|
||||
317
docs/guide-ru/concept-di-container.md
Normal file
317
docs/guide-ru/concept-di-container.md
Normal file
@@ -0,0 +1,317 @@
|
||||
Контейнер внедрения зависимостей
|
||||
==============================
|
||||
|
||||
Контейнер внедрения зависимостей - это объект, который знает, как создать и настроить экземпляр объекта и зависимых от него объектов.
|
||||
[Статья Мартина Фаулера](http://martinfowler.com/articles/injection.html) хорошо объясняет, почему контейнер внедрения зависимостей является полезным. Здесь, преимущественно, будет объясняться использование контейнера внедрения зависимостей, предоставляемого в Yii.
|
||||
|
||||
|
||||
|
||||
|
||||
Внедрение зависимостей <a name="dependency-injection"></a>
|
||||
--------------------
|
||||
|
||||
Yii обеспечивает функционал контейнера внедрения зависимостей через класс [[yii\di\Container]]. Он поддерживает следующие виды внедрения зависимостей:
|
||||
|
||||
* Внедрение зависимости через конструктор.
|
||||
* Внедрение зависимости через сеттер и свойство.
|
||||
* Внедрение зависимости через PHP callback.
|
||||
|
||||
|
||||
### Внедрение зависимости через конструктор <a name="constructor-injection"></a>
|
||||
|
||||
Контейнер внедрения зависимостей поддерживает внедрение зависимости через конструктор при помощи указания типов для параметров конструктора.
|
||||
Указанные типы сообщают контейнеру, какие классы или интерфейсы зависят от него при создании нового объекта.
|
||||
Контейнер попытается получить экземпляры зависимых классов или интерфейсов, а затем передать их в новый объект через конструктор. Например,
|
||||
|
||||
```php
|
||||
class Foo
|
||||
{
|
||||
public function __construct(Bar $bar)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
$foo = $container->get('Foo');
|
||||
// что равносильно следующему:
|
||||
$bar = new Bar;
|
||||
$foo = new Foo($bar);
|
||||
```
|
||||
|
||||
|
||||
### Внедрение зависимости через сеттер и свойство <a name="setter-and-property-injection"></a>
|
||||
|
||||
Внедрение зависимости через сеттер и свойство поддерживается через [конфигурации](concept-configurations.md).
|
||||
При регистрации зависимости или при создании нового объекта, вы можете предоставить конфигурацию, которая
|
||||
будет использована контейнером для внедрения зависимостей через соответствующие сеттеры или свойства.
|
||||
Например,
|
||||
|
||||
```php
|
||||
use yii\base\Object;
|
||||
|
||||
class Foo extends Object
|
||||
{
|
||||
public $bar;
|
||||
|
||||
private $_qux;
|
||||
|
||||
public function getQux()
|
||||
{
|
||||
return $this->_qux;
|
||||
}
|
||||
|
||||
public function setQux(Qux $qux)
|
||||
{
|
||||
$this->_qux = $qux;
|
||||
}
|
||||
}
|
||||
|
||||
$container->get('Foo', [], [
|
||||
'bar' => $container->get('Bar'),
|
||||
'qux' => $container->get('Qux'),
|
||||
]);
|
||||
```
|
||||
|
||||
|
||||
### Внедрение зависимости через PHP callback <a name="php-callable-injection"></a>
|
||||
|
||||
В данном случае, контейнер будет использовать зарегистрированный PHP callback для создания новых экземпляров класса.
|
||||
Callback отвечает за разрешения зависимостей и внедряет их в соответствии с вновь создаваемыми объектами. Например,
|
||||
|
||||
```php
|
||||
$container->set('Foo', function () {
|
||||
return new Foo(new Bar);
|
||||
});
|
||||
|
||||
$foo = $container->get('Foo');
|
||||
```
|
||||
|
||||
|
||||
Регистрация зависимостей <a name="registering-dependencies"></a>
|
||||
------------------------
|
||||
|
||||
Вы можете использовать [[yii\di\Container::set()]] для регистрации зависимостей. При регистрации требуется имя зависимости, а так же определение зависимости.
|
||||
Именем звисимости может быть имя класса, интерфейса или алиас, так же определением зависимости может быть имя класса, конфигурационным массивом, или PHP calback'ом.
|
||||
|
||||
```php
|
||||
$container = new \yii\di\Container;
|
||||
|
||||
// регистрация имени класса, как есть. это может быть пропущено.
|
||||
$container->set('yii\db\Connection');
|
||||
|
||||
// регистраци интерфейса
|
||||
// Когда класс зависит от интерфейса, соответствующий класс
|
||||
// будет использован в качестве зависимости объекта
|
||||
$container->set('yii\mail\MailInterface', 'yii\swiftmailer\Mailer');
|
||||
|
||||
// регистрация алиаса. Вы можете использовать $container->get('foo')
|
||||
// для создания экземпляра Connection
|
||||
$container->set('foo', 'yii\db\Connection');
|
||||
|
||||
// Регистрация класса с конфигурацией. Конфигурация
|
||||
// будет применена при создании экземпляра класса через get()
|
||||
$container->set('yii\db\Connection', [
|
||||
'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
|
||||
'username' => 'root',
|
||||
'password' => '',
|
||||
'charset' => 'utf8',
|
||||
]);
|
||||
|
||||
// регистрация алиаса с конфигурацией класса
|
||||
// В данном случае, параметр "class" требуется для указания класса
|
||||
$container->set('db', [
|
||||
'class' => 'yii\db\Connection',
|
||||
'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
|
||||
'username' => 'root',
|
||||
'password' => '',
|
||||
'charset' => 'utf8',
|
||||
]);
|
||||
|
||||
// регистрация PHP callback'a
|
||||
// Callback будет выполняться каждый раз при вызове $container->get('db')
|
||||
$container->set('db', function ($container, $params, $config) {
|
||||
return new \yii\db\Connection($config);
|
||||
});
|
||||
|
||||
// регистрация экземпляра компонента
|
||||
// $container->get('pageCache') вернёт тот же экземпляр при каждом вызове
|
||||
$container->set('pageCache', new FileCache);
|
||||
```
|
||||
|
||||
> Подсказка: Если имя зависимости такое же, как и определение соответствующей зависимости, то её повторная регистрация в контейнере внедрения зависимостей не нужна.
|
||||
|
||||
Зависимость, зарегистрированная через `set()` создаёт экземпляр каждый раз, когда зависимость необходима.
|
||||
Вы можете использовать [[yii\di\Container::setSingleton()]] для регистрации зависимости, которая создаст только один экземпляр:
|
||||
|
||||
```php
|
||||
$container->setSingleton('yii\db\Connection', [
|
||||
'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
|
||||
'username' => 'root',
|
||||
'password' => '',
|
||||
'charset' => 'utf8',
|
||||
]);
|
||||
```
|
||||
|
||||
|
||||
Разрешение зависимостей <a name="resolving-dependencies"></a>
|
||||
----------------------
|
||||
После регистрации зависимостей, вы можете использовать контейнер внедрения зависимостей для создания новых объектов,
|
||||
и контейнер автоматически разрешит зависимости их экземпляра и их внедрений во вновь создаваемых объектах. Разрешение зависимостей рекурсивно, то есть
|
||||
если зависимость имеет другие зависимости, эти зависимости также будут автоматически разрешены.
|
||||
|
||||
Вы можете использовать [[yii\di\Container::get()]] для создания новых объектов. Метод принимает имя зависимости, которым может быть имя класса, имя интерфейса или псевдоним.
|
||||
Имя зависимости может быть или не может быть зарегистрировано через `set()` или `setSingleton()`.
|
||||
Вы можете опционально предоставить список параметров конструктора класса и [конфигурацию](concept-configurations.md) для настройки созданного объекта.
|
||||
Например,
|
||||
|
||||
```php
|
||||
// "db" ранее зарегистрированный псевдоним
|
||||
$db = $container->get('db');
|
||||
|
||||
// эквивалентно: $engine = new \app\components\SearchEngine($apiKey, ['type' => 1]);
|
||||
$engine = $container->get('app\components\SearchEngine', [$apiKey], ['type' => 1]);
|
||||
```
|
||||
|
||||
За кулисами, контейнер внедрения зависимостей делает гораздо больше работы, чем просто создание нового объекта.
|
||||
Прежде всего, контейнер, осмотрит конструктор класса, что бы узнать имя зависимого класса или интерфейса, а затем автоматически разрешит эти зависимости рекурсивно.
|
||||
|
||||
Следующий код демонстрирует более сложный пример. Класс `UserLister` зависит от объекта, реализующего интерфейс `UserFinderInterface`; класс `UserFinder` реализует этот интерфейс и зависит от
|
||||
объекта `Connection`. Все эти зависимости были объявлены через тип подсказки параметров конструктора класса.
|
||||
При регистрации зависимости через свойство, контейнер внедрения зависимостей позволяет автоматически разрешить эти зависимости и создаёт новый экземпляр `UserLister` простым вызовом `get('userLister')`.
|
||||
|
||||
```php
|
||||
namespace app\models;
|
||||
|
||||
use yii\base\Object;
|
||||
use yii\db\Connection;
|
||||
use yii\di\Container;
|
||||
|
||||
interface UserFinderInterface
|
||||
{
|
||||
function findUser();
|
||||
}
|
||||
|
||||
class UserFinder extends Object implements UserFinderInterface
|
||||
{
|
||||
public $db;
|
||||
|
||||
public function __construct(Connection $db, $config = [])
|
||||
{
|
||||
$this->db = $db;
|
||||
parent::__construct($config);
|
||||
}
|
||||
|
||||
public function findUser()
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
class UserLister extends Object
|
||||
{
|
||||
public $finder;
|
||||
|
||||
public function __construct(UserFinderInterface $finder, $config = [])
|
||||
{
|
||||
$this->finder = $finder;
|
||||
parent::__construct($config);
|
||||
}
|
||||
}
|
||||
|
||||
$container = new Container;
|
||||
$container->set('yii\db\Connection', [
|
||||
'dsn' => '...',
|
||||
]);
|
||||
$container->set('app\models\UserFinderInterface', [
|
||||
'class' => 'app\models\UserFinder',
|
||||
]);
|
||||
$container->set('userLister', 'app\models\UserLister');
|
||||
|
||||
$lister = $container->get('userLister');
|
||||
|
||||
// что эквивалентно:
|
||||
|
||||
$db = new \yii\db\Connection(['dsn' => '...']);
|
||||
$finder = new UserFinder($db);
|
||||
$lister = new UserLister($finder);
|
||||
```
|
||||
|
||||
|
||||
Практическое использование <a name="practical-usage"></a>
|
||||
---------------
|
||||
|
||||
Yii создаёт контейнер внедрения зависимостей когда вы подключаете файл `Yii.php` во [входном скрипте](structure-entry-scripts.md)
|
||||
вашего приложения. Контейнер внедрения зависимостей доступен через [[Yii::$container]]. При вызове [[Yii::createObject()]],
|
||||
метод на самом деле вызовет метод контейнера [[yii\di\Container::get()|get()]], что бы создать новый объект.
|
||||
Как упомянуто выше, контейнер внедрения зависимостей автоматически разрешит зависимости (если таковые имеются) и внедрит их в только что созданный объект.
|
||||
Поскольку Yii использует [[Yii::createObject()]] в большей части кода своего ядра для создания новых объектов, это означает,
|
||||
что вы можете настроить глобальные объекты, имея дело с [[Yii::$container]].
|
||||
|
||||
Например, вы можете настроить по умолчанию глобальное количество кнопок в пейджере [[yii\widgets\LinkPager]]:
|
||||
|
||||
```php
|
||||
\Yii::$container->set('yii\widgets\LinkPager', ['maxButtonCount' => 5]);
|
||||
```
|
||||
|
||||
Теперь, если вы вызовете в представлении виджет, используя следующий код, то свойство `maxButtonCount` будет инициальзировано, как 5, вместо значения по умолчанию 10, как это определено в классе.
|
||||
|
||||
```php
|
||||
echo \yii\widgets\LinkPager::widget();
|
||||
```
|
||||
|
||||
Хотя, вы всё ещё можете переопределить установленное значение через контейнер внедрения зависимостей:
|
||||
|
||||
```php
|
||||
echo \yii\widgets\LinkPager::widget(['maxButtonCount' => 20]);
|
||||
```
|
||||
Другим примером является использование автоматического внедрения зависимости через конструктор контейнера внедрения зависимостей.
|
||||
Предположим, ваш класс контроллера зависит от ряда других объектов, таких как сервис бронирования гостиницы. Вы
|
||||
можете объявить зависимость через параметр конструктора и позволить контейнеру внедрения зависимостей, разрешить её за вас.
|
||||
|
||||
```php
|
||||
namespace app\controllers;
|
||||
|
||||
use yii\web\Controller;
|
||||
use app\components\BookingInterface;
|
||||
|
||||
class HotelController extends Controller
|
||||
{
|
||||
protected $bookingService;
|
||||
|
||||
public function __construct($id, $module, BookingInterface $bookingService, $config = [])
|
||||
{
|
||||
$this->bookingService = $bookingService;
|
||||
parent::__construct($id, $module, $config);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Если у вас есть доступ к этому контроллеру из браузера, вы увидите сообщение об ошибке, который жалуется на то, что `BookingInterface`
|
||||
не может быть создан. Это потому что вы должны указать контейнеру внедрения зависимостей, как обращаться с этой зависимостью:
|
||||
|
||||
```php
|
||||
\Yii::$container->set('app\components\BookingInterface', 'app\components\BookingService');
|
||||
```
|
||||
|
||||
Теперь, если вы попытаетесь получить доступ к контроллеру снова, то экземпляр `app\components\BookingService` будет создан и введён в качестве 3-го параметра конструктора контроллера.
|
||||
|
||||
|
||||
Когда следует регистрировать зависимости <a name="when-to-register-dependencies"></a>
|
||||
-----------------------------
|
||||
|
||||
Поскольку зависимости необходимы тогда, когда создаются новые объекты, то их регистрация должна быть сделана
|
||||
как можно раньше. Ниже приведены рекомендуемые практики:
|
||||
|
||||
* Если вы разработчик приложения, то вы можете зарегистрировать зависимости во [входном скрипте](structure-entry-scripts.md) вашего приложения или в скрипте, подключённого во входном скрипте.
|
||||
* Если вы разработчик распространяемого [расширения](structure-extensions.md), то вы можете зарегистрировать зависимости в загрузочном классе расширения.
|
||||
|
||||
|
||||
Итог <a name="summary"></a>
|
||||
-------
|
||||
Как dependency injection, так и [service locator](concept-service-locator.md) являются популярными паттернами проектирования, которые позволяют
|
||||
создавать программное обеспечение в слабосвязаной и более тестируемой манере.
|
||||
Мы настоятельно рекомендуем к прочтению
|
||||
[статью Мартина Фаулера](http://martinfowler.com/articles/injection.html), для более глубокого понимания dependency injection и service locator.
|
||||
|
||||
Yii реализует свой [service locator](concept-service-locator.md) поверх контейнера внедрения зависимостей.
|
||||
Когда service locator пытается создать новый экземпляр объекта, он перенаправляет вызов на контейнер внедрения зависимостей.
|
||||
Последний будет разрешать зависимости автоматически, как описано выше.
|
||||
|
||||
210
docs/guide-uz/README.md
Normal file
210
docs/guide-uz/README.md
Normal file
@@ -0,0 +1,210 @@
|
||||
Yii 2.0 bo`yicha to`liq qo`llanma
|
||||
=============================
|
||||
|
||||
Ushbu qo`llanma [Yii qo`llanmalarining holati bilan](http://www.yiiframework.com/doc/terms/) bilan mos holda yo`lga qo`yildi.
|
||||
|
||||
<<<<<<< HEAD
|
||||
All Rights Reserved.
|
||||
|
||||
2014 © Yii Software LLC.
|
||||
|
||||
Kirish
|
||||
------
|
||||
|
||||
* [Yii haqida](intro-yii.md)
|
||||
* [1.1 dan keyingi yangilanishlar](intro-upgrade-from-v1.md)
|
||||
|
||||
|
||||
Birinchi tanishuv
|
||||
-----------------
|
||||
|
||||
* [Yii ni o`rnatish](start-installation.md)
|
||||
* [Ilovani ishga tushirish](start-workflow.md)
|
||||
* [«Salom» deymiz](start-hello.md)
|
||||
* [Formalar bilan ishlash](start-forms.md)
|
||||
* [Ma`lumotlar ombori bilan ishlash](start-databases.md)
|
||||
* [Gii yordamida kodlarni generatsiya qilish](start-gii.md)
|
||||
* [Keyin nima?](start-looking-ahead.md)
|
||||
|
||||
|
||||
Ilova strukturasi
|
||||
-----------------
|
||||
|
||||
* [Sharh](structure-overview.md)
|
||||
* [Kirish skriptlari](structure-entry-scripts.md)
|
||||
* [Ilova](structure-applications.md)
|
||||
* [Ilova komponentlari](structure-application-components.md)
|
||||
* [Kontrollerlar](structure-controllers.md)
|
||||
* [Namoyish](structure-views.md)
|
||||
* [Modellar](structure-models.md)
|
||||
* **TBD** [Filtrlar](structure-filters.md)
|
||||
* **TBD** [Vidjetlar](structure-widgets.md)
|
||||
* **TBD** [Modullar](structure-modules.md)
|
||||
* [Ресурсы](structure-assets.md)
|
||||
* **TBD** [Kengaytmalar](structure-extensions.md)
|
||||
|
||||
|
||||
So`rovlarni qayta ishlash
|
||||
-------------------------
|
||||
|
||||
* **TBD** [Bootstrapping](runtime-bootstrapping.md)
|
||||
* **TBD** [Routing](runtime-routing.md)
|
||||
* **TBD** [So`rovlar](runtime-requests.md)
|
||||
* **TBD** [Javoblar](runtime-responses.md)
|
||||
* **TBD** [Sessiyalar va kuklar](runtime-sessions-cookies.md)
|
||||
* [URL ni tahlil va generatsiya qilish](runtime-url-handling.md)
|
||||
* [Xatolilarni qayta ishlash](runtime-handling-errors.md)
|
||||
* [Jurnallarga yozish](runtime-logging.md)
|
||||
|
||||
|
||||
Asosiy tushunchalar
|
||||
-------------------
|
||||
|
||||
* [Komponentlar](concept-components.md)
|
||||
* [Xususiyat](concept-properties.md)
|
||||
* [Xodisa](concept-events.md)
|
||||
* [O`zini tutish](concept-behaviors.md)
|
||||
* [Muxim sozlashlar](concept-configurations.md)
|
||||
* [Taxalluslar](concept-aliases.md)
|
||||
* [Sinflarni avtoyuklash](concept-autoloading.md)
|
||||
* [Service Locator](concept-service-locator.md)
|
||||
* [Dependency Injection Container](concept-di-container.md)
|
||||
|
||||
|
||||
Ma`lumotlar ombori bilan ishlash
|
||||
--------------------------------
|
||||
|
||||
* [Ma`lumotlarga imkon beruvchi obektlar(DAO)](db-dao.md) - Ma`lumotlar ombori bilan bog`lanish, oddiy so`rovlar, tranzaksiya va sxema bilan ishlash.
|
||||
* [So`rovlarni yaratuvchi](db-query-builder.md) - Ma`lumotlar omboriga abstraksiyaning oddiy qatlamidan so`rovlar.
|
||||
* [Active Record](db-active-record.md) - AR obektlarini olish, ular bilan ishlash va bog`lanishlarni aniqlash.
|
||||
* [Migratsiyalar](db-migrations.md) - Komandada ishlaganda ma`lumotlar sxemasini talqinlarini boshqarish.
|
||||
* **TBD** [Sphinx](db-sphinx.md)
|
||||
* **TBD** [Redis](db-redis.md)
|
||||
* **TBD** [MongoDB](db-mongodb.md)
|
||||
* **TBD** [ElasticSearch](db-elastic-search.md)
|
||||
|
||||
|
||||
Foydalanuvchidan ma`lumotlarni qabul qilish
|
||||
-------------------------------------------
|
||||
|
||||
* [Formani yaratish](input-forms.md)
|
||||
* [Validatsiya](input-validation.md)
|
||||
* **TBD** [Fayllarni yuklash](input-file-uploading.md)
|
||||
* **TBD** [Bir nechta modellar bilan ishlash](input-multiple-models.md)
|
||||
|
||||
|
||||
Ma`lumotlarni namoyish etish
|
||||
----------------------------
|
||||
|
||||
* **TBD** [Ma`lumotlarni formatlash](output-formatting.md)
|
||||
* **TBD** [Sahifalar bo`yicha bo`ajratish](output-pagination.md)
|
||||
* **TBD** [Saralash](output-sorting.md)
|
||||
* [Ma`lumotlar provayderlari](output-data-providers.md)
|
||||
* [Ma`lumotlar uchun vidjetlar](output-data-widgets.md)
|
||||
* [Mavzulashtirish](output-theming.md)
|
||||
|
||||
|
||||
Xavfsizlik
|
||||
----------
|
||||
|
||||
* [Autentifikatsiya](security-authentication.md)
|
||||
* [Mualliflikka tekshiruvi](security-authorization.md)
|
||||
* [Parollar bilan ishlash](security-passwords.md)
|
||||
* **TBD** [Mualliflikka tekshiruvlar mijozlari](security-auth-clients.md)
|
||||
* **TBD** [Eng yaxshi amaliyotlar](security-best-practices.md)
|
||||
|
||||
|
||||
Keshlash
|
||||
--------
|
||||
|
||||
* [Sharh](caching-overview.md)
|
||||
* [Ma`lumotlarni keshlash](caching-data.md)
|
||||
* [Fragmentlasrni keshlash](caching-fragment.md)
|
||||
* [Sahifalarni keshlash](caching-page.md)
|
||||
* [HTTP ni keshlash](caching-http.md)
|
||||
|
||||
|
||||
REST veb-xizmatlari
|
||||
-------------------
|
||||
|
||||
* [Tezkor boshlash](rest-quick-start.md)
|
||||
* [Resurslar](rest-resources.md)
|
||||
* [Kontrollerlar](rest-controllers.md)
|
||||
* [Routing](rest-routing.md)
|
||||
* [Javoblarni formatlash](rest-response-formatting.md)
|
||||
* [Autentifikatsiya](rest-authentication.md)
|
||||
* [So`rovlarni chastotasini chegaralash](rest-rate-limiting.md)
|
||||
* [Talqin yaratish](rest-versioning.md)
|
||||
* [Xatoliklarni qayta ishlash](rest-error-handling.md)
|
||||
|
||||
|
||||
Ishlab chiquvchi uskunalari
|
||||
---------------------------
|
||||
|
||||
* [Sozlashlar paneli va sozlovchi](tool-debugger.md)
|
||||
* [Gii bilan kodni generatsiya qilish](tool-gii.md)
|
||||
* **TBD** [API qo`llanmani generatori](tool-api-doc.md)
|
||||
|
||||
|
||||
Test o`tkazish
|
||||
--------------
|
||||
|
||||
* [Sharh](test-overview.md)
|
||||
* **TBD** [MOdulli testlar](test-unit.md)
|
||||
* **TBD** [Funksional testlar](test-functional.md)
|
||||
* **TBD** [Qabul qiluvchi testlar](test-acceptance.md)
|
||||
* [Fiksturalar](test-fixtures.md)
|
||||
|
||||
|
||||
Yii kengaytmalari
|
||||
-----------------
|
||||
|
||||
* [Kengaytmani yaratish](extend-creating-extensions.md)
|
||||
* [Freymvork kodini kengaytirish](extend-customizing-core.md)
|
||||
* [Tashqi kutubxonalarni qo`llash](extend-using-libs.md)
|
||||
* **TBD** [Tashqi tizimlarda Yii integratsiyasi](extend-embedding-in-others.md)
|
||||
* **TBD** [Yii 1.1 va 2.0 larni bir vaqtda ishlatish](extend-using-v1-v2.md)
|
||||
* [Composer ni ishlatish](extend-using-composer.md)
|
||||
|
||||
|
||||
Maxsus mavzular
|
||||
---------------
|
||||
|
||||
* [advanced ilova shabloni](tutorial-advanced-app.md)
|
||||
* [Ilovani noldan yaratish](tutorial-start-from-scratch.md)
|
||||
* [Konsol komandalari](tutorial-console.md)
|
||||
* [Xalqarolashtirish](tutorial-i18n.md)
|
||||
* [Pochta yuborish](tutorial-mailing.md)
|
||||
* [Ish inumdorligini oshirish](tutorial-performance-tuning.md)
|
||||
* **TBD** [shared xostingida ishlash](tutorial-shared-hosting.md)
|
||||
* [Shablonlashtiruvchilar](tutorial-template-engines.md)
|
||||
|
||||
|
||||
Vidjetlar
|
||||
---------
|
||||
|
||||
* GridView: link to demo page
|
||||
* ListView: link to demo page
|
||||
* DetailView: link to demo page
|
||||
* ActiveForm: link to demo page
|
||||
* Pjax: link to demo page
|
||||
* Menu: link to demo page
|
||||
* LinkPager: link to demo page
|
||||
* LinkSorter: link to demo page
|
||||
* [Bootstrap vidjetlari](bootstrap-widgets.md)
|
||||
* **TBD** [Jquery UI vidjetlari](jui-widgets.md)
|
||||
|
||||
|
||||
Xelperlar
|
||||
---------
|
||||
|
||||
* [Sharh](helper-overview.md)
|
||||
* **TBD** [ArrayHelper](helper-array.md)
|
||||
* **TBD** [Html](helper-html.md)
|
||||
* **TBD** [Url](helper-url.md)
|
||||
* **TBD** [Security](helper-security.md)
|
||||
=======
|
||||
Barcha huquqlar ximoyalangan.
|
||||
|
||||
2014 © Yii Software LLC.
|
||||
>>>>>>> 6a3cce2e267f590c38f910d571adea6a38028329
|
||||
@@ -52,7 +52,7 @@ Handling Requests
|
||||
* [Routing](runtime-routing.md)
|
||||
* [Requests](runtime-requests.md)
|
||||
* [Responses](runtime-responses.md)
|
||||
* **TBD** [Sessions and Cookies](runtime-sessions-cookies.md)
|
||||
* [Sessions and Cookies](runtime-sessions-cookies.md)
|
||||
* [URL Parsing and Generation](runtime-url-handling.md)
|
||||
* [Handling Errors](runtime-handling-errors.md)
|
||||
* [Logging](runtime-logging.md)
|
||||
|
||||
@@ -3,8 +3,8 @@ Requests
|
||||
|
||||
Requests made to an application are represented in terms of [[yii\web\Request]] objects which provide information
|
||||
such as request parameters, HTTP headers, cookies, etc. For a given request, you can get access to the corresponding
|
||||
request object via the `request` [application component](structure-application-components.md). In this section,
|
||||
we will describe how you can make use of this component in your applications.
|
||||
request object via the `request` [application component](structure-application-components.md) which is an instance
|
||||
of [[yii\web\Request]], by default. In this section, we will describe how you can make use of this component in your applications.
|
||||
|
||||
|
||||
## Request Parameters <a name="request-parameters"></a>
|
||||
|
||||
@@ -5,8 +5,9 @@ When an application finishes handling a [request](runtime-requests.md), it gener
|
||||
and sends it to the end user. The response object contains information such as the HTTP status code, HTTP headers and body.
|
||||
The ultimate goal of Web application development is essentially to build such response objects upon various requests.
|
||||
|
||||
In most cases you should mainly deal with the `response` [application component](structure-application-components.md).
|
||||
However, Yii also allows you to create your own response objects and send them to end users.
|
||||
In most cases you should mainly deal with the `response` [application component](structure-application-components.md)
|
||||
which is an instance of [[yii\web\Response]], by default. However, Yii also allows you to create your own response
|
||||
objects and send them to end users as we will explain in the following.
|
||||
|
||||
In this section, we will describe how to compose and send responses to end users.
|
||||
|
||||
|
||||
318
docs/guide/runtime-sessions-cookies.md
Normal file
318
docs/guide/runtime-sessions-cookies.md
Normal file
@@ -0,0 +1,318 @@
|
||||
Sessions and Cookies
|
||||
====================
|
||||
|
||||
Sessions and cookies allow data to be persisted across multiple user requests. In plain PHP, you may access them
|
||||
through the global variables `$_SESSION` and `$_COOKIE`, respectively. Yii encapsulates sessions and cookies as objects
|
||||
and thus allows you to access them in an object-oriented fashion with additional nice enhancements.
|
||||
|
||||
|
||||
## Sessions <a name="sessions"></a>
|
||||
|
||||
Like [requests](runtime-requests.md) and [responses](runtime-responses.md), you can get access to sessions via
|
||||
the `session` [application component](structure-application-components.md) which is an instance of [[yii\web\Session]],
|
||||
by default.
|
||||
|
||||
|
||||
### Opening and Closing Sessions <a name="opening-closing-sessions"></a>
|
||||
|
||||
To open and close a session, you can do the following:
|
||||
|
||||
```php
|
||||
$session = Yii::$app->session;
|
||||
|
||||
// check if a session is already open
|
||||
if ($session->isActive) ...
|
||||
|
||||
// open a session
|
||||
$session->open();
|
||||
|
||||
// close a session
|
||||
$session->close();
|
||||
|
||||
// destroys all data registered to a session.
|
||||
$session->destroy();
|
||||
```
|
||||
|
||||
You can call the [[yii\web\Session::open()|open()]] and [[yii\web\Session::close()|close()]] multiple times
|
||||
without causing errors. This is because internally the methods will first check if the session is already opened.
|
||||
|
||||
|
||||
### Accessing Session Data <a name="access-session-data"></a>
|
||||
|
||||
To access the data stored in session, you can do the following:
|
||||
|
||||
```php
|
||||
$session = Yii::$app->session;
|
||||
|
||||
// get a session variable. The following usages are equivalent:
|
||||
$language = $session->get('language');
|
||||
$language = $session['language'];
|
||||
$language = isset($_SESSION['language']) ? $_SESSION['language'] : null;
|
||||
|
||||
// set a session variable. The following usages are equivalent:
|
||||
$session->set('language', 'en-US');
|
||||
$session['language'] = 'en-US';
|
||||
$_SESSION['language'] = 'en-US';
|
||||
|
||||
// remove a session variable. The following usages are equivalent:
|
||||
$session->remove('language');
|
||||
unset($session['language']);
|
||||
unset($_SESSION['language']);
|
||||
|
||||
// check if a session variable exists. The following usages are equivalent:
|
||||
if ($session->has('language')) ...
|
||||
if (isset($session['language'])) ...
|
||||
if (isset($_SESSION['language'])) ...
|
||||
|
||||
// traverse all session variables. The following usages are equivalent:
|
||||
foreach ($session as $name => $value) ...
|
||||
foreach ($_SESSION as $name => $value) ...
|
||||
```
|
||||
|
||||
> Info: When you access session data through the `session` component, a session will be automatically opened
|
||||
if it has not been done so before. This is different from accessing session data through `$_SESSION`, which requires
|
||||
an explicit call of `session_start()`.
|
||||
|
||||
When working with session data that are arrays, the `session` component has a limitation which prevents you from
|
||||
directly modifying an array element. For example,
|
||||
|
||||
```php
|
||||
$session = Yii::$app->session;
|
||||
|
||||
// the following code will NOT work
|
||||
$session['captcha']['number'] = 5;
|
||||
$session['captcha']['lifetime'] = 3600;
|
||||
|
||||
// the following code works:
|
||||
$session['captcha'] = [
|
||||
'number' => 5,
|
||||
'lifetime' => 3600,
|
||||
];
|
||||
|
||||
// the following code also works:
|
||||
echo $session['captcha']['lifetime'];
|
||||
```
|
||||
|
||||
You can use one of the following workarounds to solve this problem:
|
||||
|
||||
```php
|
||||
$session = Yii::$app->session;
|
||||
|
||||
// directly use $_SESSION (make sure Yii::$app->session->open() has been called)
|
||||
$_SESSION['captcha']['number'] = 5;
|
||||
$_SESSION['captcha']['lifetime'] = 3600;
|
||||
|
||||
// get the whole array out first, modify it and then save it back
|
||||
$captcha = $session['captcha'];
|
||||
$captcha['number'] = 5;
|
||||
$captcha['lifetime'] = 3600;
|
||||
$session['captcha'] = $captcha;
|
||||
|
||||
// use ArrayObject instead of array
|
||||
$session['captcha'] = new \ArrayObject;
|
||||
...
|
||||
$session['captcha']['number'] = 5;
|
||||
$session['captcha']['lifetime'] = 3600;
|
||||
|
||||
// store array data by keys with common prefix
|
||||
$session['captcha.number'] = 5;
|
||||
$session['captcha.lifetime'] = 3600;
|
||||
```
|
||||
|
||||
For better performance and code readability, we recommend the last workaround. That is, instead of storing
|
||||
an array as a single session variable, you store each array element as a session variable which shares the same
|
||||
key prefix with other array elements.
|
||||
|
||||
|
||||
### Custom Session Storage <a name="custom-session-storage"></a>
|
||||
|
||||
The default [[yii\web\Session]] class stores session data as files on the server. Yii also provides the following
|
||||
session classes implementing different session storage:
|
||||
|
||||
* [[yii\web\DbSession]]: stores session data in a database table.
|
||||
* [[yii\web\CacheSession]]: stores session data in a cache with the help of a configured [cache component](caching-data.md#cache-components).
|
||||
* [[yii\redis\Session]]: stores session data using [redis](http://redis.io/) as the storage medium
|
||||
* [[yii\mongodb\Session]]: stores session data in a [MongoDB](http://www.mongodb.org/).
|
||||
|
||||
All these session classes support the same set of API methods. As a result, you can switch to use a different
|
||||
session storage without the need to modify your application code that uses session.
|
||||
|
||||
> Note: If you want to access session data via `$_SESSION` while using custom session storage, you must make
|
||||
sure that the session is already started by [[yii\web\Session::open()]]. This is because custom session storage
|
||||
handlers are registered within this method.
|
||||
|
||||
To learn how to configure and use these component classes, please refer to their API documentation. Below is
|
||||
an example showing how to configure [[yii\web\DbSession]] in the application configuration to use database table
|
||||
as session storage:
|
||||
|
||||
```php
|
||||
return [
|
||||
'components' => [
|
||||
'session' => [
|
||||
'class' => 'yii\web\DbSession',
|
||||
// 'db' => 'mydb', // the application component ID of the DB connection. Defaults to 'db'.
|
||||
// 'sessionTable' => 'my_session', // session table name. Defaults to 'session'.
|
||||
],
|
||||
],
|
||||
];
|
||||
```
|
||||
|
||||
You also need to create the following database table to store session data:
|
||||
|
||||
```sql
|
||||
CREATE TABLE session
|
||||
(
|
||||
id CHAR(40) NOT NULL PRIMARY KEY,
|
||||
expire INTEGER,
|
||||
data BLOB
|
||||
)
|
||||
```
|
||||
|
||||
where 'BLOB' refers to the BLOB-type of your preferred DBMS. Below are the BLOB type that can be used for some popular DBMS:
|
||||
|
||||
- MySQL: LONGBLOB
|
||||
- PostgreSQL: BYTEA
|
||||
- MSSQL: BLOB
|
||||
|
||||
|
||||
|
||||
### Flash Data <a name="flash-data"></a>
|
||||
|
||||
Flash data is a special kind of session data which, once set in one request, will only be available during
|
||||
the next request and will be automatically deleted afterwards. Flash data is most commonly used to implement
|
||||
messages that should only be displayed to end users once, such as a confirmation message displayed after
|
||||
a user successfully submits a form.
|
||||
|
||||
You can set and access flash data through the `session` application component. For example,
|
||||
|
||||
```php
|
||||
$session = Yii::$app->session;
|
||||
|
||||
// Request #1
|
||||
// set a flash message named as "postDeleted"
|
||||
$session->setFlash('postDeleted', 'You have successfully deleted your post.');
|
||||
|
||||
// Request #2
|
||||
// display the flash message named "postDeleted"
|
||||
echo $session->getFlash('postDeleted');
|
||||
|
||||
// Request #3
|
||||
// $result will be false since the flash message was automatically deleted
|
||||
$result = $session->hasFlash('postDeleted');
|
||||
```
|
||||
|
||||
Like regular session data, you can store arbitrary data as flash data.
|
||||
|
||||
When you call [[yii\web\Session::setFlash()]], it will overwrite any existing flash data that has the same name.
|
||||
To append new flash data to the existing one(s) of the same name, you may call [[yii\web\Session::addFlash()]] instead.
|
||||
For example,
|
||||
|
||||
```php
|
||||
$session = Yii::$app->session;
|
||||
|
||||
// Request #1
|
||||
// add a few flash messages under the name of "alerts"
|
||||
$session->addFlash('alerts', 'You have successfully deleted your post.');
|
||||
$session->addFlash('alerts', 'You have successfully added a new friend.');
|
||||
$session->addFlash('alerts', 'You are promoted.');
|
||||
|
||||
// Request #2
|
||||
// $alerts is an array of the flash messages under the name of "alerts"
|
||||
$alerts = $session->getFlash('alerts');
|
||||
```
|
||||
|
||||
> Note: Try not to use [[yii\web\Session::setFlash()]] together with [[yii\web\Session::addFlash()]] for flash data
|
||||
of the same name. This is because the latter method will automatically turn the flash data into an array so that it
|
||||
can append new flash data of the same name. As a result, when you call [[yii\web\Session::getFlash()]], you may
|
||||
find sometimes you are getting an array while sometimes you are getting a string, depending on the order of
|
||||
the invocation of these two methods.
|
||||
|
||||
|
||||
## Cookies <a name="cookies"></a>
|
||||
|
||||
Yii represents each cookie as an object of [[yii\web\Cookie]]. Both [[yii\web\Request]] and [[yii\web\Response]]
|
||||
maintain a collection of cookies via the property named `cookies`. The cookie collection in the former represents
|
||||
the cookies submitted in a request, while the cookie collection in the latter represents the cookies that are to
|
||||
be sent to the user.
|
||||
|
||||
|
||||
### Reading Cookies <a name="reading-cookies"></a>
|
||||
|
||||
You can get the cookies in the current request using the following code:
|
||||
|
||||
```php
|
||||
// get the cookie collection (yii\web\CookieCollection) from "request" component
|
||||
$cookies = Yii::$app->request->cookies;
|
||||
|
||||
// get the "language" cookie value. If the cookie does not exist, return "en" as the default value.
|
||||
$language = $cookies->getValue('language', 'en');
|
||||
|
||||
// an alternative way of getting the "language" cookie value
|
||||
if (($cookie = $cookies->get('language')) !== null) {
|
||||
$language = $cookie->value;
|
||||
}
|
||||
|
||||
// you may also use $cookies like an array
|
||||
if (isset($cookies['language'])) {
|
||||
$language = $cookies['language']->value;
|
||||
}
|
||||
|
||||
// check if there is a "language" cookie
|
||||
if ($cookies->has('language')) ...
|
||||
if (isset($cookies['language'])) ...
|
||||
```
|
||||
|
||||
|
||||
### Sending Cookies <a name="sending-cookies"></a>
|
||||
|
||||
You can send cookies to end users using the following code:
|
||||
|
||||
```php
|
||||
// get the cookie collection (yii\web\CookieCollection) from "response" component
|
||||
$cookies = Yii::$app->response->cookies;
|
||||
|
||||
// add a new cookie to the response to be sent
|
||||
$cookies->add(new \yii\web\Cookie([
|
||||
'name' => 'language',
|
||||
'value' => 'zh-CN',
|
||||
]);
|
||||
|
||||
// remove a cookie
|
||||
$cookies->remove('language');
|
||||
// equivalent to the following
|
||||
unset($cookies['language']);
|
||||
```
|
||||
|
||||
Besides the [[yii\web\Cookie::name|name]], [[yii\web\Cookie::value|value]] properties shown in the above
|
||||
examples, the [[yii\web\Cookie]] class also defines other properties to fully represent all possible information
|
||||
of cookies, such as [[yii\web\Cookie::domain|domain]], [[yii\web\Cookie::expire|expire]]. You may configure these
|
||||
properties as needed to prepare a cookie and then add it to the response's cookie collection.
|
||||
|
||||
|
||||
### Cookie Validation <a name="cookie-validation"></a>
|
||||
|
||||
When you are reading and sending cookies through the `request` and `response` components like shown in the last
|
||||
two subsections, you enjoy the added security of cookie validation which protects cookies from being modified
|
||||
on the client side. This is achieved by signing each cookie with a hash string. If a cookie is modified somehow,
|
||||
it will fail the validation of its associated hash and will be removed from the cookie collection in the request.
|
||||
|
||||
Cookie validation is enabled by default. You can disable it by setting the [[yii\web\Request::enableCookieValidation]]
|
||||
property to be false, although we recommend you not to do so.
|
||||
|
||||
> Note: Cookies that are directly read/sent via `$_COOKIE` and `setcookie()` will NOT be validated.
|
||||
|
||||
When using cookie validation, you must specify a [[yii\web\Request::cookieValidationKey]] that will be used to generate
|
||||
the aforementioned hash strings. You can do so by configuring the `request` component in the application configuration:
|
||||
|
||||
```php
|
||||
return [
|
||||
'components' => [
|
||||
'request' => [
|
||||
'cookieValidationKey' => 'fill in a secret key here',
|
||||
],
|
||||
],
|
||||
];
|
||||
```
|
||||
|
||||
> Info: [[yii\web\Request::cookieValidationKey|cookieValidationKey]] is critical to your application's security.
|
||||
It should only be known to people you trust. Do not store it in version control system.
|
||||
@@ -51,7 +51,7 @@ Installing from an Archive File <a name="installing-from-archive-file"></a>
|
||||
|
||||
Installing Yii from an archive file involves three steps:
|
||||
|
||||
1. Download the archive file from [yiiframework.com](https://github.com/yiisoft/yii2/releases/download/2.0.0-rc/yii-basic-app-2.0.0-rc.tgz).
|
||||
1. Download the archive file from [yiiframework.com](http://www.yiiframework.com/download/).
|
||||
2. Unpack the downloaded file to a Web-accessible folder.
|
||||
3. Modify the `config/web.php` file by entering a secret key for the `cookieValidationKey` configuration item
|
||||
(this is done automatically if you are installing Yii using Composer):
|
||||
|
||||
@@ -30,7 +30,7 @@ runtime-bootstrapping.md | Yes
|
||||
runtime-routing.md | Yes
|
||||
runtime-requests.md | Yes
|
||||
runtime-responses.md | Yes
|
||||
runtime-sessions-cookies.md |
|
||||
runtime-sessions-cookies.md | Yes
|
||||
runtime-url-handling.md |
|
||||
runtime-handling-errors.md |
|
||||
runtime-logging.md |
|
||||
|
||||
@@ -14,11 +14,21 @@ China
|
||||
- [@Aliciamiao](https://github.com/aliciamiao)
|
||||
- [@riverlet ](https://github.com/riverlet)
|
||||
|
||||
Finnish
|
||||
------
|
||||
|
||||
- Jani Mikkonen, [@janisto](https://github.com/janisto), janisto@php.net
|
||||
|
||||
German
|
||||
------
|
||||
|
||||
- Carsten Brandt, [@cebe](https://github.com/cebe), mail@cebe.cc
|
||||
|
||||
Italian
|
||||
-------
|
||||
|
||||
- Lorenzo Milesi, [@maxxer](https://github.com/maxxer), maxxer@yetopen.it
|
||||
|
||||
Russian
|
||||
-------
|
||||
|
||||
|
||||
@@ -85,7 +85,7 @@ return [
|
||||
'{attribute} must not be equal to "{compareValue}".' => '{attribute} musi mieć wartość różną od "{compareValue}".',
|
||||
'{attribute} should contain at least {min, number} {min, plural, one{character} other{characters}}.' => '{attribute} powinien zawierać co najmniej {min, number} {min, plural, one{znak} few{znaki} many{znaków} other{znaku}}.',
|
||||
'{attribute} should contain at most {max, number} {max, plural, one{character} other{characters}}.' => '{attribute} powinien zawierać nie więcej niż {max, number} {min, plural, one{znak} few{znaki} many{znaków} other{znaku}}.',
|
||||
'{attribute} should contain {length, number} {length, plural, one{character} other{characters}}.' => '{attribute} powinien zawierać dokładnie {length, number} {min, plural, one{znak} few{znaki} many{znaków} other{znaku}}.',
|
||||
'{attribute} should contain {length, number} {length, plural, one{character} other{characters}}.' => '{attribute} powinien zawierać dokładnie {length, number} {length, plural, one{znak} few{znaki} many{znaków} other{znaku}}.',
|
||||
'{delta, plural, =1{a day} other{# days}} ago' => '{delta, plural, =1{jeden dzień} other{# dni} other{# dnia}} temu',
|
||||
'{delta, plural, =1{a minute} other{# minutes}} ago' => '{delta, plural, =1{minutę} few{# minuty} many{# minut} other{# minuty}} temu',
|
||||
'{delta, plural, =1{a month} other{# months}} ago' => '{delta, plural, =1{miesiąc} few{# miesiące} many{# miesięcy} other{# miesiąca}} temu',
|
||||
|
||||
Reference in New Issue
Block a user