Merge remote-tracking branch 'upstream/master' into transalting

parents e1faa8fa 8c50ee9e
......@@ -8,7 +8,7 @@ php:
- hhvm-nightly
env:
- CUBRID_VERSION=9.3.0/CUBRID-9.3.0.0206 CUBRID_PDO_VERSION=9.2.0.0001
- CUBRID_VERSION=9.3.0/CUBRID-9.3.0.0206 CUBRID_PDO_VERSION=9.3.0.0001
# run build against hhvm but allow them to fail
# http://docs.travis-ci.com/user/build-configuration/#Rows-That-are-Allowed-To-Fail
......@@ -38,7 +38,7 @@ addons:
install:
- composer self-update && composer --version
- composer global require "fxp/composer-asset-plugin:1.0.0-beta2"
- composer global require "fxp/composer-asset-plugin:1.0.0-beta3"
- export PATH="$HOME/.composer/vendor/bin:$PATH"
# core framework:
- composer install --prefer-dist
......
......@@ -8,16 +8,6 @@ Yii 2 inherits the main spirit behind Yii for being simple, fast and highly exte
Yii 2 requires PHP 5.4 and embraces the best practices and protocols found in modern Web application development.
**Yii 2 is not ready for production use yet.** We may make significant changes without prior notices.
We expect to make the first stable release of Yii 2 in the middle of 2014.
If you mainly want to learn Yii with no real project development requirement, we highly recommend
you start with Yii 2 as it will be our main focus for the next few years.
If you have a real project with tight schedule, you should stick to [Yii 1.1](https://github.com/yiisoft/yii)
which is the latest stable release of Yii.
[![Latest Stable Version](https://poser.pugx.org/yiisoft/yii2/v/stable.png)](https://packagist.org/packages/yiisoft/yii2)
[![Total Downloads](https://poser.pugx.org/yiisoft/yii2/downloads.png)](https://packagist.org/packages/yiisoft/yii2)
[![Dependency Status](https://www.versioneye.com/php/yiisoft:yii2/dev-master/badge.png)](https://www.versioneye.com/php/yiisoft:yii2/dev-master)
......@@ -55,14 +45,11 @@ The minimum requirement by Yii is that your Web server supports PHP 5.4.
DOCUMENTATION
-------------
A draft of the [Definitive Guide](docs/guide/README.md) is available.
API docs and a rendering of the definitive guide are currently
available under the following urls:
Yii 2.0 has a [Definitive Guide](http://www.yiiframework.com/doc-2.0/guide-index.html) and
a [Class Reference](http://www.yiiframework.com/doc-2.0/index.html) which cover every detail of Yii.
- http://www.yiiframework.com/doc-2.0/ API and Definitive Guide (updated daily)
- http://stuff.cebe.cc/yii2docs/ API and Definitive Guide (updated every 15 minutes)
- http://stuff.cebe.cc/yii2-guide.pdf The PDF version of the Guide
There is also a [PDF version](http://stuff.cebe.cc/yii2-guide.pdf) of the Definitive Guide
and a [Definitive Guide Mirror](http://stuff.cebe.cc/yii2docs/) which update every 15 minutes.
For 1.1 users, you may refer to [Upgrading from Yii 1.1](docs/guide/intro-upgrade-from-v1.md)
to have a general idea of what has changed in 2.0.
......
......@@ -74,7 +74,7 @@ at [getcomposer.org](http://getcomposer.org/doc/00-intro.md#installation-nix).
You can then install the application using the following command:
~~~
php composer.phar global require "fxp/composer-asset-plugin:1.0.0-beta2"
php composer.phar global require "fxp/composer-asset-plugin:1.0.0-beta3"
php composer.phar create-project --prefer-dist --stability=dev yiisoft/yii2-app-advanced advanced
~~~
......
......@@ -55,7 +55,7 @@ at [getcomposer.org](http://getcomposer.org/doc/00-intro.md#installation-nix).
You can then install this application template using the following command:
~~~
php composer.phar global require "fxp/composer-asset-plugin:1.0.0-beta2"
php composer.phar global require "fxp/composer-asset-plugin:1.0.0-beta3"
php composer.phar create-project --prefer-dist --stability=dev yiisoft/yii2-app-basic basic
~~~
......
<?php
use yii\helpers\Html;
?><!doctype html>
<html>
<head>
......@@ -27,21 +29,21 @@ use yii\helpers\Html;
</style>
</head>
<body>
<h1><?php echo Html::encode($title)?></h1>
<h1><?= Html::encode($title) ?></h1>
<ul>
<li><strong>Source:</strong> <?php echo Html::encode($sourcePath)?></li>
<li><strong>Translation:</strong> <?php echo Html::encode($translationPath)?></li>
<li><strong>Source:</strong> <?= Html::encode($sourcePath) ?></li>
<li><strong>Translation:</strong> <?= Html::encode($translationPath) ?></li>
</ul>
<?php foreach($results as $name => $result):?>
<h2 class="<?php echo empty($result['errors']) ? 'ok' : 'errors'?>"><?php echo $name?></h2>
<?php foreach($result['errors'] as $error):?>
<p><?php echo Html::encode($error)?></p>
<?php foreach($results as $name => $result): ?>
<h2 class="<?= empty($result['errors']) ? 'ok' : 'errors' ?>"><?= $name ?></h2>
<?php foreach($result['errors'] as $error): ?>
<p><?= Html::encode($error) ?></p>
<?php endforeach ?>
<?php if(!empty($result['diff'])):?>
<code class="diff"><pre><?php echo $this->context->highlightDiff($result['diff'])?></pre></code>
<?php endif?>
<?php if (!empty($result['diff'])): ?>
<code class="diff"><pre><?= $this->context->highlightDiff($result['diff']) ?></pre></code>
<?php endif ?>
<?php endforeach ?>
</body>
</html>
\ No newline at end of file
......@@ -77,7 +77,7 @@
"lib-pcre": "*",
"yiisoft/yii2-composer": "*",
"ezyang/htmlpurifier": "4.6.*",
"cebe/markdown": "0.9.*",
"cebe/markdown": "~1.0.0",
"bower-asset/jquery": "2.1.*@stable | 1.11.*@stable",
"bower-asset/jquery.inputmask": "3.1.*",
"bower-asset/punycode": "1.3.*",
......
......@@ -27,6 +27,8 @@ Blocks use the Markdown `> Type: `. There are four block types:
* `Info`, general information (an aside); not as strong as a "Note"
* `Tip`, pro tips, extras, can be useful but may not be needed by everyone all the time
The sentence after the colon should begin with a capital letter.
## References
* Yii 2.0 or Yii 2 (not Yii2 or Yii2.0)
......
Guía Definitiva de Yii 2.0
==========================
Este tutorial se publica con arreglo a los [Términos de Documentación Yii](http://www.yiiframework.com/doc/terms/).
Este tutorial se publica bajo los [Términos de Documentación Yii](http://www.yiiframework.com/doc/terms/).
Todos los derechos reservados.
......@@ -40,7 +40,7 @@ Estructura de una aplicación
* [Filtros](structure-filters.md)
* [Widgets](structure-widgets.md)
* [Módulos](structure-modules.md)
* **TBD** [Recursos](structure-assets.md)
* **TBD** [Assets](structure-assets.md)
* **TBD** [Extensiones](structure-extensions.md)
......@@ -50,9 +50,9 @@ Gestión de las peticiones
* [Información general](runtime-overview.md)
* [Bootstrapping](runtime-bootstrapping.md)
* [Routing](runtime-routing.md)
* **TBD** [Peticiones](runtime-requests.md)
* **TBD** [Respuestas](runtime-responses.md)
* **TBD** [Sesiones y Cookies](runtime-sessions-cookies.md)
* [Peticiones (Requests)](runtime-requests.md)
* [Respuestas (Responses)](runtime-responses.md)
* [Sesiones (Sessions) y Cookies](runtime-sessions-cookies.md)
* **TBD** [Procesamiento y generación de las URL](runtime-url-handling.md)
* **TBD** [Gestión de errores](runtime-handling-errors.md)
* **TBD** [Registro de anotaciones](runtime-logging.md)
......
Peticiones
==========
Las peticiones(requests) hechas a una aplicación son representadas como objetos [[yii\web\Request]] que proporcionan información como parámetros de la petición, cabeceras HTTP, cookies, etc. Dada una petición, se puede acceder al objeto request correspondiente a través del [componente de aplicación](structure-application-components.md) `request` que, por defecto, es una instancia de [[yii\web\Request]]. En esta sección se describirá como hacer uso de este componente en las aplicaciones.
## Parámetros de Request <a name="request-parameters"></a>
Para obtener los parámetros de la petición, se puede llamar a los métodos [[yii\web\Request::get()|get()]] y [[yii\web\Request::post()|post()]] del componente `request`. Estos devuelven los valores de `$_GET` y `$_POST`, respectivamente. Por ejemplo:
```php
$request = Yii::$app->request;
$get = $request->get();
// equivalente a: $get = $_GET;
$id = $request->get('id');
// equivalente a: $id = isset($_GET['id']) ? $_GET['id'] : null;
$id = $request->get('id', 1);
// equivalente a: $id = isset($_GET['id']) ? $_GET['id'] : 1;
$post = $request->post();
// equivalente a: $post = $_POST;
$name = $request->post('name');
// equivalente a: $name = isset($_POST['name']) ? $_POST['name'] : null;
$name = $request->post('name', '');
// equivalente a: $name = isset($_POST['name']) ? $_POST['name'] : '';
```
>Info: En lugar de acceder directamente a `$_GET` y `$_POST` para obtener los parámetros de la petición, es recomendable que se obtengan mediante el componente `request` como en el ejemplo anterior. Esto facilitará la creación de tests ya que se puede simular una componente de request con datos de peticiones personalizados.
Cuando se implementan [APIs RESTful](rest-quick-start.md), a menudo se necesita obtener parámetros enviados desde el formulario a través de PUT, PATCH u otros [métodos de request](runtime-requests.md#request-methods). Se pueden obtener estos parámetros llamando a los métodos [[yii\web\Request::getBodyParam()]]. Por ejemplo:
```php
$request = Yii::$app->request;
// devuelve todos los parámetros
$params = $request->bodyParams;
// devuelve el parámetro "id"
$param = $request->getBodyParam('id');
```
>Info: A diferencia de los parámetros `GET`, los parámetros enviados desde el formulario a través de `POST`, `PUT`, `PATCH`, etc. se envían en el cuerpo de la petición. El componente `request` convierte los parámetros cuando se acceda a él a través de los métodos descritos anteriormente. Se puede personalizar la manera en como los parámetros se convierten configurando la propiedad [[yii\web\Request::parsers]].
## Métodos de Request <a name="request-methods"></a>
Se puede obtener el método HTTP usado por la petición actual a través de la expresión `Yii::$app->request->method`. Se proporcionan un conjunto de propiedades booleanas para comprobar si el método actual es de un cierto tipo. Por ejemplo:
```php
$request = Yii::$app->request;
if ($request->isAjax) { // la request es una request AJAX }
if ($request->isGet) { // el método de la request es GET }
if ($request->isPost) { // el método de la request es POST }
if ($request->isPut) { // el método de la request es PUT }
```
## URLs de Request <a name="request-urls"></a>
El componente `request` proporciona muchas maneras de inspeccionar la URL solicitada actualmente.
Asumiendo que la URL que se está solicitando es `http://example.com/admin/index.php/product?id=100`, se pueden obtener varias partes de la URL explicadas en los siguientes puntos:
* [[yii\web\Request::url|url]]: devuelve `/admin/index.php/product?id=100`, que es la URL sin la parte de información del host.
* [[yii\web\Request::absoluteUrl|absoluteUrl]]: devuelve `http://example.com/admin/index.php/product?id=100`, que es la URL entera, incluyendo la parte de información del host.
* [[yii\web\Request::hostInfo|hostInfo]]: devuelve `http://example.com`, que es la parte de información del host dentro de la URL.
* [[yii\web\Request::pathInfo|pathInfo]]: devuelve `/product`, que es la parte posterior al script de entrada y anterior al interrogante (query string)
* [[yii\web\Request::queryString|queryString]]: devuelve `id=100`, que es la parte posterior al interrogante.
* [[yii\web\Request::baseUrl|baseUrl]]: devuelve `/admin`, que es la parte posterior a la información del host y anterior al nombre de script de entrada.
* [[yii\web\Request::scriptUrl|scriptUrl]]: devuelve `/admin/index.php`, que es la URL sin la información del la ruta ni la query string.
* [[yii\web\Request::serverName|serverName]]: devuelve `example.com`, que es el nombre del host dentro de la URL.
* [[yii\web\Request::serverPort|serverPort]]: devuelve 80, que es el puerto que usa el servidor web.
## Cabeceras HTTP <a name="http-headers"></a>
Se pueden obtener la información de las cabeceras HTTP a través de [[yii\web\HeaderCollection|header collection]] devueltas por la propiedad [[yii\web\Request::headers]]. Por ejemplo:
```php
// $headers es un objeto de yii\web\HeaderCollection
$headers = Yii::$app->request->headers;
// devuelve el valor Accept de la cabecera
$accept = $headers->get('Accept');
if ($headers->has('User-Agent')) { // la cabecera contiene un User-Agent }
```
El componente `request` también proporciona soporte para acceder rápidamente a las cabeceras usadas más comúnmente, incluyendo:
* [[yii\web\Request::userAgent|userAgent]]: devuelve el valor de la cabecera `User-Agen`.
* [[yii\web\Request::contentType|contentType]]: devuelve el valor de la cabecera `Content-Type` que indica el tipo MIME de los datos del cuerpo de la petición.
* [[yii\web\Request::acceptableContentTypes|acceptableContentTypes]]: devuelve los tipos de contenido MIME aceptado por los usuarios, ordenados por puntuación de calidad. Los que tienen mejor puntuación, se devolverán primero.
* [[yii\web\Request::acceptableLanguages|acceptableLanguages]]: devuelve los idiomas aceptados por el usuario. Los idiomas devueltos son ordenados según su orden de preferencia. El primer elemento representa el idioma preferido.
Si la aplicación soporta múltiples idiomas y se quiere mostrar las páginas en el idioma preferido por el usuario, se puede usar el método de negociación de idioma [[yii\web\Request::getPreferredLanguage()]]. Este método obtiene una lista de idiomas soportados por la aplicación, comparados con [[yii\web\Request::acceptableLanguages|acceptableLanguages]], y devuelve el idioma más apropiado.
>Consejo: También se puede usar el filtro [[yii\filters\ContentNegotiator|ContentNegotiator]] para determinar diatónicamente el content type y el idioma que debe usarse en la respuesta. El filtro implementa la negociación de contenido en la parte superior de las propiedades y métodos descritos anteriormente.
## Información del cliente <a name="client-information"></a>
Se puede obtener el nombre del host y la dirección IP de la máquina cliente a través de [[yii\web\Request::userHost|userHost]] y [[yii\web\Request::userIP|userIP]], respectivamente. Por ejemplo:
```php
$userHost = Yii::$app->request->userHost;
$userIP = Yii::$app->request->userIP;
```
......@@ -31,7 +31,7 @@ Structure Application
---------------------
* [Vue d'ensemble](structure-overview.md)
* [Script d'entrée](structure-entry-scripts.md)
* [Scripts d'entrée](structure-entry-scripts.md)
* [Applications](structure-applications.md)
* [Composants application](structure-application-components.md)
* [Contrôleurs](structure-controllers.md)
......
Scripts d'entrée
=============
Les scripts d'entrée sont la première chaîne dans le processus de d'amorçage de l'application. Une application (qu'elle
soit une application Web ou une application console) a un unique script de démarrage. Les utilisateurs font des
requêtes au scripts de démarrage qui instancient des instances d'application et leur transmettent les requêtes.
Les scripts d'entrée pour application Web doivent être placés dans des dossiers accessibles par le Web pour que les
utilisateurs puissent y accéder. Ils sont souvent nommés `index.php`, mais peuvent également avoir tout autre nom,
du moment que les serveurs Web peuvent les trouver.
Les scripts d'entrée pour les applications console sont généralement placés dans le [répertoire de base](structure-applications.md)
des applications et sont nommés `yii` (avec le suffixe `.php`). Ils doivent être rendus exécutables afin que les
utilisateurs puissent lancer des applications console grâce à la commande `./yii <route> [arguments] [options]`.
Les scipts de démarrage effectuent principalement les tâches suivantes :
* Définir des constantes globales;
* Enregistrer l'[autoloader Composer](http://getcomposer.org/doc/01-basic-usage.md#autoloading);
* Inclure le fichier de classe de [[Yii]];
* Charger la configuration de l'application;
* Créer et configurer une instance d'[application](structure-applications.md);
* Appeler [[yii\base\Application::run()]] pour traiter la requête entrante.
## Applications Web <a name="web-applications"></a>
Ce qui suit est le code du script de démarrage du [Modèle Basique d'Application Web](start-installation.md).
```php
<?php
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');
// register Composer autoloader
require(__DIR__ . '/../vendor/autoload.php');
// include Yii class file
require(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');
// load application configuration
$config = require(__DIR__ . '/../config/web.php');
// create, configure and run application
(new yii\web\Application($config))->run();
```
## Applications Console <a name="console-applications"></a>
De même, le code qui suit est le code du script de démarrage d'une application console :
```php
#!/usr/bin/env php
<?php
/**
* Yii console bootstrap file.
*
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
defined('YII_DEBUG') or define('YII_DEBUG', true);
// fcgi doesn't have STDIN and STDOUT defined by default
defined('STDIN') or define('STDIN', fopen('php://stdin', 'r'));
defined('STDOUT') or define('STDOUT', fopen('php://stdout', 'w'));
// register Composer autoloader
require(__DIR__ . '/vendor/autoload.php');
// include Yii class file
require(__DIR__ . '/vendor/yiisoft/yii2/Yii.php');
// load application configuration
$config = require(__DIR__ . '/config/console.php');
$application = new yii\console\Application($config);
$exitCode = $application->run();
exit($exitCode);
```
## Définir des Constantes <a name="defining-constants"></a>
Les scripts de démarrage sont l'endroit idéal pour définir des constantes globales. Yii supporte les trois constantes suivantes :
* `YII_DEBUG` : spécifie si une application tourne en mode de débogage. Si elle est en mode de débogage, une
application loguera plus d'informations, et révélera des piles d'appels d'erreurs détaillées si des exceptions
sont lancées. C'est pour cette raison que le mode de débogage doit être utilisé principalement pendant la phase
de développement. La valeur par défaut de `YII_DEBUG` est faux.
* `YII_ENV` : spécifie sur quel environnement l'application est en train de tourner. Cela a été décrit plus en détails
dans la section [Configurations](concept-configurations.md#environment-constants). La valeur par défaut de `YII_ENV`
est `'prod'`, ce qui signifie que l'application tourne en environnement de production.
* `YII_ENABLE_ERROR_HANDLER` : spécifie si le gestionnaire d'erreurs fourni par Yii doit être activé. La valeur par
défaut de cette constantes est vrai.
Quand on définit une constant, on utilise souvent le code suivant :
```php
defined('YII_DEBUG') or define('YII_DEBUG', true);
```
qui est l'équivalent du code suivant :
```php
if (!defined('YII_DEBUG')) {
define('YII_DEBUG', true);
}
```
Clairement, le premier est plus succinct et plus aisé à comprendre.
Les définitions de constantes doit être faite au tout début d'un script de démarrage pour qu'elles puissent prendre
effet quand d'autres fichiers PHP sont inclus.
Installare Yii
==============
Puoi installare Yii in due modi, usando [Composer](http://getcomposer.org/) o scaricando un archivio.
Il metodo preferito è il primo, perché ti consente di installare [estensioni](structure-extensions.md) o aggiornare il core di Yii
semplicemente eseguendo un comando.
> Nota: diversamente da Yii 1, le installazioni standard di Yii 2 comportano il download e l'installazione sia del framework che dello scheletro dell'applicazione
Installazione via Composer <a name="installing-via-composer"></a>
--------------------------
Se non hai già installato Composer puoi farlo seguendo le istruzioni al sito
[getcomposer.org](https://getcomposer.org/download/). Su Linux e Mac OS X puoi installare Composer con questo comando:
curl -s http://getcomposer.org/installer | php
mv composer.phar /usr/local/bin/composer
Su Windows devi scaricare ed eseguire [Composer-Setup.exe](https://getcomposer.org/Composer-Setup.exe).
Fai riferimento alla [documentazione di Composer](https://getcomposer.org/doc/) in casodi errori o se vuoi apprendere maggiori
informazioni sull'uso di Composer.
Se hai già Composer installato assicurati di avere una versione aggiornata. Puoi aggiornare Composer con il comando
`composer self-update`.
Una volta installato Composer, puoi installare Yii eseguendo questo comando in una directory accessbile via web:
composer global require "fxp/composer-asset-plugin:1.0.0-beta2"
composer create-project --prefer-dist yiisoft/yii2-app-basic basic
Il primo comando installa il [plugin composer asset](https://github.com/francoispluchino/composer-asset-plugin/)
che consente di gestire le dipendenze di bower e npm tramite Composer. Devi eseguire questo comando solo una volta. Il secondo
installa Yii in una directory di nome `basic`. Puoi scegliere un nome diverso, se preferisci.
> Nota: durante l'installazione potrebbe essere che Composer ti chieda le credenziali di Github, per superato limite di utilizzo
> delle API di Github. Questa situazione è normale perché Composer deve scaricare molte informazioni per tutti i pacchetti da Github.
> Accedendo a Github aumenterà il limite di utilizzo delle API, consentendo a Composer di completare il suo lavoro. Per maggiori
> dettagli fai riferimento alla
> [documentazione di Composer](https://getcomposer.org/doc/articles/troubleshooting.md#api-rate-limit-and-oauth-tokens).
> Suggerimento: se vuoi installare l'ultima versione di sviluppo di Yii, puoi usare questo comando che aggiunge una
> [opzione di stabilità](https://getcomposer.org/doc/04-schema.md#minimum-stability):
>
> composer create-project --prefer-dist --stability=dev yiisoft/yii2-app-basic basic
>
> Considera che la versione di sviluppo di Yii non dovrebbe essere utilizzata per siti di produzione perché potrebbe rendere instabile
> il tuo codice.
Installazione da un archivio <a name="installing-from-archive-file"></a>
----------------------------
L'installazione da un archivio compresso comporta tre passaggi:
1. Scaricare l'archivio da [yiiframework.com](http://www.yiiframework.com/download/).
2. Scompattare l'archivio in una directory accessible via web.
3. Modificare il file `config/web.php` inserendo una chiave segreta per il parametro di configurazione `cookieValidationKey`
(questa operazione viene fatta automaticamente se installi tramite Composer):
```php
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'enter your secret key here',
```
Altre modalità di installazione <a name="other-installation-options"></a>
-------------------------------
Le istruzioni sopra elencate mostrano come installare Yii, e creano inoltre un'applicazione web base funzionante.
Questo approccio è un ottimo punto di partenza per progetti minori, o se stai imparando Yii.
Ma ci sono altre opzioni disponibili per l'installazione:
* se vuoi installare solo il core e costruire l'applocazione da zero puoi seguire le istruzioni della sezione
[costruire un'applicazione da zero](tutorial-start-from-scratch.md).
* se vuoi avviare un'applicazione più sofisticata, che meglio si sposa per uno sviluppo di gruppo, puoi considerare l'insallazione del
[template di applicazione avanzata](tutorial-advanced-app.md).
Verifica dell'installazione <a name="verifying-installation"></a>
---------------------------
Dopo l'installazione puoi usare il tuo browser per accedere all'applicazione Yii installata con l'URL seguente:
```
http://localhost/basic/web/index.php
```
Questo indirizzo assume che hai installato Yii in una directory di nome `basic`, direttamente nella *root* del tuo webserver,
e che il webserver è in esecuzione sulla tua macchina locale (`localhost`). Potresti doverlo modificare a seconda del tuo ambiente
di installazione.
![Installazione di Yii completata con successo](images/start-app-installed.png)
Dovresti vedere la pagina sopra di congratulazioni. In caso contrario verifica se la tua installazione di PHP soddisfa i requisiti minimi
di Yii. Puoi verificare le richieste in due modi:
* accedere all'indirizzo `http://localhost/basic/requirements.php` tramite browser;
* lanciando questi comandi:
```
cd basic
php requirements.php
```
Devi configurare la tua installazione di PHP in modo che soddisfi le richieste minime di Yii. E' molto importante che tu stia usando
PHP 5.4 o successivo. Devi inoltre installare le [estensioni PDO di PHP](http://www.php.net/manual/en/pdo.installation.php) e un driver
di database di PDO (come ad esempio `pdo_mysql` per i database MySQL), se la tua applicazione richiede un database.
Configurazione del webserver <a name="configuring-web-servers"></a>
----------------------------
> Informazione: puoi saltare questa parte per ora se stai solo provando Yii e non hai intenzione di installarlo su un server di produzione.
L'applicazione installata secondo le istruzioni sopra dovrebbe funzionare senza problemi su un server
[Apache](http://httpd.apache.org/) o [Nginx](http://nginx.org/), su Windows, Mac OS X, or Linux equipaggiati con PHP 5.4 o successivo.
Yii 2.0 è anche compatibile con le librerie [HHVM](http://hhvm.com/) di Facebook, tuttavia ci sono alcuni casi limite dove HHVM si
comporta diversamente dal PHP nativo, quindi devi avere maggiore cura se intendi usare HHVM.
Su un server di produzione vorrai probabilmente che la tua applicazione sia accessibile tramite l'url
`http://www.example.com/index.php` invece di `http://www.example.com/basic/web/index.php`. Questo risultato richiede che punti la
*document root* del tuo webserver nella directory `basic/web`. Vorrai magari anche nascondere `index.php` dall'URL, come descritto
nella sezione [analizzare e generare URL](runtime-url-handling.md).
In questa parte vedrai configurare il tuo server Apache o Nginx per ottenere questo risultato.
> Informazione: impostando `basic/web` come *document root* impedisci agli utenti finali di accedere al codice e a file/informazioni
riservate memorizzate nelle directory superiori a `basic/web`. Negare l'accesso a queste altre cartelle è sicuramente un vantaggio
per la sicurezza.
> Informazione: se la tua applicazione andrà installata su un servizio di hosting condiviso non avrai il permesso di modificare la
configurazione del webserver, ma dovrai comunque correggere la struttura della tua applicazione per migliorare la sicurezza. Fai
riferimento alla sezione [ambienti di hosting condiviso](tutorial-shared-hosting.md) per maggiori dettagli.
### Configurazione consigliata di Apache <a name="recommended-apache-configuration"></a>
Usa questa configurazione nel file `httpd.conf` di Apache o nella definizione del tuo *VirtualHost*. Tieni presente che dovrai
modificare `path/to/basic/web` con il percorso reale della tua `basic/web`.
```
# Imposta *DocumentRoot* per essere "basic/web"
DocumentRoot "path/to/basic/web"
<Directory "path/to/basic/web">
# usa mod_rewrite per gli url SEF
RewriteEngine on
# If a directory or a file exists, use the request directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Otherwise forward the request to index.php
RewriteRule . index.php
# ...altre impostazioni...
</Directory>
```
### Configurazione consigliata di Nginx <a name="recommended-nginx-configuration"></a>
Devi aver installato PHP con il demone [FPM](http://php.net/install.fpm) per usare [Nginx](http://wiki.nginx.org/).
Usa questa configurazione per Nginx, sostituendo `path/to/basic/web` con il percorso reale di `basic/web` e `mysite.local` con
il nome reale del server web.
```
server {
charset utf-8;
client_max_body_size 128M;
listen 80; ## listen for ipv4
#listen [::]:80 default_server ipv6only=on; ## listen for ipv6
server_name mysite.local;
root /path/to/basic/web;
index index.php;
access_log /path/to/basic/log/access.log main;
error_log /path/to/basic/log/error.log;
location / {
# Redirect everything that isn't a real file to index.php
try_files $uri $uri/ /index.php?$args;
}
# uncomment to avoid processing of calls to non-existing static files by Yii
#location ~ \.(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar)$ {
# try_files $uri =404;
#}
#error_page 404 /404.html;
location ~ \.php$ {
include fastcgi.conf;
fastcgi_pass 127.0.0.1:9000;
#fastcgi_pass unix:/var/run/php5-fpm.sock;
try_files $uri =404;
}
location ~ /\.(ht|svn|git) {
deny all;
}
}
```
Usando questa configurazione dovresti anche impostare `cgi.fix_pathinfo=0` in `php.ini` per evitare molte chiamate di sistema `stat()`
inutili.
Inoltre considera che nel caso di server HTTPS dovrai aggiungere `fastcgi_param HTTPS on;` così che Yii possa correttamente rilevare
se la connessione è sicura.
Yii 2.0 公式ガイド
==================
このチュートリアルは [Yii ドキュメンテーション規約](http://www.yiiframework.com/doc/terms/) の下に
リリースされています。
All Rights Reserved.
2014 (c) Yii Software LLC.
前書き
------
* [Yii について](intro-yii.md)
* [バージョン 1.1 からのアップグレード](intro-upgrade-from-v1.md)
始めよう
--------
* [Yii をインストールする](start-installation.md)
* [アプリケーションを走らせる](start-workflow.md)
* [ハローと言う](start-hello.md)
* [フォームを扱う](start-forms.md)
* [データベースを扱う](start-databases.md)
* [Gii でコードを生成する](start-gii.md)
* [この先を見る](start-looking-ahead.md)
アプリケーションの構造
----------------------
* [概要](structure-overview.md)
* [エントリースクリプト](structure-entry-scripts.md)
* [アプリケーション](structure-applications.md)
* [アプリケーションコンポーネント](structure-application-components.md)
* [コントローラ](structure-controllers.md)
* [モデル](structure-models.md)
* [ビュー](structure-views.md)
* [モジュール](structure-modules.md)
* [フィルター](structure-filters.md)
* [ウィジェット](structure-widgets.md)
* [アセット](structure-assets.md)
* [エクステンション](structure-extensions.md)
リクエストの処理
----------------
* [概要](runtime-overview.md)
* [ブートストラッピング](runtime-bootstrapping.md)
* [ルーティング](runtime-routing.md)
* [リクエスト](runtime-requests.md)
* [レスポンス](runtime-responses.md)
* [セッションとクッキー](runtime-sessions-cookies.md)
* [URL の解析と生成](runtime-url-handling.md)
* [エラー処理](runtime-handling-errors.md)
* [ログ](runtime-logging.md)
鍵となる概念
------------
* [コンポーネント](concept-components.md)
* [プロパティ](concept-properties.md)
* [イベント](concept-events.md)
* [ビヘイビア](concept-behaviors.md)
* [設定](concept-configurations.md)
* [エイリアス](concept-aliases.md)
* [クラスのオートロード](concept-autoloading.md)
* [サービスロケータ](concept-service-locator.md)
* [依存性注入コンテナ](concept-di-container.md)
データベースの取り扱い
----------------------
* [データアクセスオブジェクト](db-dao.md): データベースへの接続、基本的なクエリ、トランザクション、および、スキーマ操作
* [クエリビルダ](db-query-builder.md): シンプルな抽象レイヤを使ってデータベースに対してクエリを行う
* [アクティブレコード](db-active-record.md): アクティブレコード ORM、レコードの読み出しと操作、リレーションの定義
* [マイグレーション](db-migrations.md): チーム開発環境においてデータベースにバージョンコントロールを適用
* **TBD** [Sphinx](db-sphinx.md)
* **TBD** [Redis](db-redis.md)
* **TBD** [MongoDB](db-mongodb.md)
* **TBD** [ElasticSearch](db-elasticsearch.md)
ユーザからのデータ取得
----------------------
* [フォームを作成する](input-forms.md)
* [入力を検証する](input-validation.md)
* [ファイルをアップロードする](input-file-upload.md)
* **TBD** [複数モデルのためのデータ取得](input-multiple-models.md)
データの表示
------------
* [データの書式設定](output-formatter.md)
* **TBD** [ページネーション](output-pagination.md)
* **TBD** [並べ替え](output-sorting.md)
* [データプロバイダ](output-data-providers.md)
* [データウィジェット](output-data-widgets.md)
* [クライアントスクリプトを使う](output-client-scripts.md)
* [テーマを使う](output-theming.md)
セキュリティ
------------
* [認証](security-authentication.md)
* [権限](security-authorization.md)
* [パスワードを扱う](security-passwords.md)
* **TBD** [Auth クライアント](security-auth-clients.md)
* **TBD** [最善の慣行](security-best-practices.md)
キャッシュ
----------
* [概要](caching-overview.md)
* [データキャッシュ](caching-data.md)
* [断片キャッシュ](caching-fragment.md)
* [ページキャッシュ](caching-page.md)
* [HTTP Caching](caching-http.md)
RESTful ウェブサービス
----------------------
* [クイックスタート](rest-quick-start.md)
* [リソース](rest-resources.md)
* [コントローラ](rest-controllers.md)
* [ルーティング](rest-routing.md)
* [レスポンスの書式設定](rest-response-formatting.md)
* [認証](rest-authentication.md)
* [速度制限](rest-rate-limiting.md)
* [バージョン管理](rest-versioning.md)
* [エラー処理](rest-error-handling.md)
開発ツール
----------
* [デバッグツールバーとデバッガ](tool-debugger.md)
* [Gii を使ってコードを生成する](tool-gii.md)
* **TBD** [API ドキュメンテーションを生成する](tool-api-doc.md)
テスト
------
* [概要](test-overview.md)
* [テスト環境の構築](test-environment-setup.md)
* [ユニットテスト](test-unit.md)
* [機能テスト](test-functional.md)
* [承認テスト](test-acceptance.md)
* [フィクスチャ](test-fixtures.md)
スペシャルトピック
------------------
* [アドバンストアプリケーションテンプレート](tutorial-advanced-app.md)
* [アプリケーションを一から構築する](tutorial-start-from-scratch.md)
* [コンソールコマンド](tutorial-console.md)
* [コアのバリデータ](tutorial-core-validators.md)
* [国際化](tutorial-i18n.md)
* [メール](tutorial-mailing.md)
* [パフォーマンスチューニング](tutorial-performance-tuning.md)
* **TBD** [共有ホスト環境](tutorial-shared-hosting.md)
* [テンプレートエンジン](tutorial-template-engines.md)
* [サードパーティのコードを扱う](tutorial-yii-integration.md)
ウィジェット
------------
* 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 ウィジェット](widget-bootstrap.md)
* [Jquery UI ウィジェット](widget-jui.md)
ヘルパー
--------
* [概要](helper-overview.md)
* **TBD** [ArrayHelper](helper-array.md)
* **TBD** [Html](helper-html.md)
* **TBD** [Url](helper-url.md)
* **TBD** [Security](helper-security.md)
Yii とは何か
============
Yii は現代的なウェブアプリケーションを迅速に開発するための、高性能な、コンポーネントベースの PHP フレームワークです。
Yii という名前 (`イー` すなわち `[ji:]` と発音します) は、中国語で「単純かつ進展的」であることを意味します。
また **Yes It Is** の省略形であると考えることも出来ます。
Yii は何に向いているか
----------------------
Yii は汎用的なウェブプログラミングフレームワークです。
つまり、あらゆる種類のウェブアプリケーションを PHP を使って開発するときに、Yii を使用することが出来ます。
コンポーネントベースのアーキテクチャと洗練されたキャッシュサポートを持っているため、Yii は大規模なアプリケーション、たとえば、ポータル、フォーラム、コンテンツマネージメントシステム (CMS)、電子商取引プロジェクト、RESTful ウェブサービス、等々を開発するのに特に適しています。
Yii を他のフレームワークと比べるとどうか?
-----------------------------------------
あなたが既に他のフレームワークに親しんでいる場合は、Yii を比較するとどうなるのかを知りたいと思うでしょう:
- ほとんどの PHP フレームワーク同様、Yii は MVC (Model-View-Controller) デザインパターンを実装し、このパターンに基いたコードの組織化を促進しています。
- Yii は、コードはシンプルかつエレガントに書かれるべきである、という哲学を採用しています。
Yii は、何らかのデザインパターンを厳密に守ることを主たる目的として大袈裟な設計をすることは、決してしようとしません。
- Yii は、検証済みで直ちに使える多数の機能を提供するフル装備のフレームワークです:
リレーショナルデータベースと NoSQL データベースの両方のためのクエリビルダとアクティブレコード; RESTful API 開発サポート; 多層構成のキャッシュサポート; その他諸々。
- Yii は極めて拡張性の高いフレームワークです。あなたはコアのコードのほとんど全ての要素をカスタマイズしたり置き換えたりすることが出来ます。
また、Yii の堅固なエクステンションアーキテクチャを利用して、再配布可能なエクステンションを使用したり開発したりすることも出来ます。
- 高性能であることは常に Yii の主たる目的の一つです。
Yii は「独演会」ではありません。Yii は [強力なコア開発チーム][] および Yii 開発に間断なく貢献してくれるプロフェッショナルの大きなコミュニティーに支えられたプロジェクトです。
Yii 開発チームは最新のウェブ開発の潮流や、他のフレームワークやプロジェクトに見られる最善の慣行と機能から目を離しません。
他のところで見られる関連性の高い最善の慣行と機能は定期的にコアフレームワークに組み込まれ、シンプルかつエレガントなインターフェイスを通じて公開されます。
[強力なコア開発チーム]: http://www.yiiframework.com/about/
Yii のバージョン
----------------
Yii は現在、利用可能な二つのメジャーバージョン、すなわち 1.1 と 2.0 を持っています。
バージョン 1.1 は古い世代のもので、現在はメンテナンスモードにあります。
バージョン 2.0 は、最新のテクノロジーとプロトコル、例えば、Composer、PSR、名前空間、トレイトなどを採用して、Yii を完全に書き直したものです。
バージョン 2.0 がこのフレームワークの現在の世代を表すものであり、今後数年間にわたって主要な開発努力の対象となるものです。
このガイドは主としてバージョン 2.0 について述べます。
必要条件と前提条件
------------------
Yii 2.0 は PHP 5.4.0 以上を必要とします。
個別の機能に対するさらに詳細な必要条件は、全ての Yii リリースに含まれている必要条件チェッカーを走らせることによって知ることが出来ます。
Yii は純粋なオブジェクト指向のフレームワークですので、Yii を使うためにはオブジェクト指向プログラミング (OOP) の基本的な知識が必要とされます。
また、Yii 2.0 は [名前空間](http://php.net/manual/ja/language.namespaces.php)[トレイト](http://php.net/manual/ja/language.oop5.traits.php) のような PHP の最新の機能を利用しています。
これらの概念を理解することは、Yii 2.0 を採用することをより一層容易にするでしょう。
......@@ -23,9 +23,9 @@ Primeiros Passos
* [Executando Aplicações](start-workflow.md)
* [Como Fazer um "Hello World"](start-hello.md)
* [Trabalhando com Formulários](start-forms.md)
* [Trabalhando com Banco de Dados](start-databases.md)
* [Trabalhando com Bancos de Dados](start-databases.md)
* [Gerando Código com Gii](start-gii.md)
* [Visão Geral](start-looking-ahead.md)
* [Seguindo em Frente](start-looking-ahead.md)
Estrutura de uma Aplicação
......
Seguindo em Frente
==================
Se você leu a seção "Primeiros Passos" inteira, você criou uma aplicação Yii
completa. Neste processo, você aprendeu como implementar algumas funcionalidades
comumente necessárias, tais como obter dados de usuários através de um formulário
HTML, consultar dados de um banco de dados, e exibir os dados de modo paginado.
Você também aprendeu a usar o [Gii](tool-gii.md) para gerar código automaticamente.
Usar o Gii para a geração de código torna a carga do seu processo de desenvolvimento
Web uma tarefa tão simples quanto preencher alguns formulários.
Esta seção resume as referências sobre o Yii que lhe ajudarão a ser mais produtivo
usando o framework.
* Documentação
- O Guia Definitivo:
Conforme o nome indica, o guia define precisamente como o Yii deve funcionar
e fornece orientações gerais sobre como usar o Yii. É o tutorial
mais importante, e que você deveria ler antes de escrever qualquer código
com o Yii.
- A Referência de Classes (Class Reference):
Especifica o uso de todas as classes disponibilizadas pelo Yii. Deve ser
principalmente usado quando você estiver escrevendo o código e quiser entender
o uso de uma classe, método ou propriedade em particular. O uso da referência
de classes só é melhor depois de um entendimento contextual do framework
inteiro.
- Os Artigos do Wiki:
Os artigos do wiki escritos pelos usuários do Yii baseados em suas próprias
experiências. A maioria deles são escritos como receitas de bolo, e mostram
como resolver problemas em particular usando o Yii. Enquanto a qualidade destes
artigos pode não ser tão boa quanto a do Guia Definitivo, eles ainda assim
são úteis porque são mais abrangentes e frequentemente fornecem
soluções prontas para serem usadas.
- Livros
* [Extensões](http://www.yiiframework.com/extensions/):
O Yii ostenta uma biblioteca de milhares de extensões contribuídas por usuários,
que podem facilmente ser plugadas em suas aplicações, desta forma tornando
o seu desenvolvimento ainda mais rápido e mais fácil.
* Comunidade
- Fórum: <http://www.yiiframework.com/forum/>
- Chat do IRC: O canal #yii na rede freenode (<irc://irc.freenode.net/yii>)
- GitHub: <https://github.com/yiisoft/yii2>
- Facebook: <https://www.facebook.com/groups/yiitalk/>
- Twitter: <https://twitter.com/yiiframework>
- LinkedIn: <https://www.linkedin.com/groups/yii-framework-1483367>
......@@ -2,8 +2,8 @@
========
В PHP, переменные-члены класса называются *свойства*. Эти переменные являются частью объявления класса и используются для
хранения состояния объектов этого класса (т.е. именно этим отличается однин экземпляр класса от другого). На практике
вам часто придётся производить чтение и запись свойств особым образом. Например, вам может понадобится обрезать строку
хранения состояния объектов этого класса (т.е. именно этим отличается один экземпляр класса от другого). На практике
вам часто придётся производить чтение и запись свойств особым образом. Например, вам может понадобиться обрезать строку
при её записи в поле `label`. Для этого вы *можете* использовать следующий код:
```php
......
......@@ -24,8 +24,7 @@ Yii – это универсальный фреймворк и может бы
шаблонам проектирования.
- Yii является full-stack фреймворком и включает в себя проверенные и хорошо зарекомендовавшие себя возможности, такие как
ActiveRecord для реляционных и NoSQL баз данных, поддержку REST API, многоуровневое кеширование и другие.
- Yii отлично расширяем. Вы можете настроить или заменить практически любую часть основного кода. Используя архитектуру
расшрений легко делиться кодом или использовать код сообщества.
- Yii отлично расширяем. Вы можете настроить или заменить практически любую часть основного кода. Используя архитектуру расширений легко делиться кодом или использовать код сообщества.
- Одна из главных целей Yii – производительность.
Yii — не проект одного человека. Он поддерживается и развивается [сильной командой][] и большим сообществом разработчиков,
......
......@@ -15,7 +15,7 @@
\Yii::info('Привет, я - тестовое сообщение лога');
```
Вы можете логгировать как данные срокового типа, так и более сложные структуры данных, такие как массивы и объекты.
Вы можете логгировать как данные строкового типа, так и более сложные структуры данных, такие как массивы и объекты.
Если логгируемые данные - не строка, обработчики логов по умолчанию сериализуют значение, используя [[yii\helpers\Vardumper::export()]].
### Категории сообщений
......
......@@ -114,7 +114,7 @@ class SiteController extends Controller
ID контроллеров также могут содержать префикс подпапки. Например, в `admin/article` часть `article` является контроллером в
подпапке `admin` в [[yii\base\Application::controllerNamespace|пространстве имен контроллеров]].
Допустимыми символами для префиксов подпапок являются: Английские буквы в нижнем и верхнем регистре, символы, подчеркивания и
Допустимыми символами для префиксов подпапок являются: Английские буквы в нижнем и верхнем регистре, символы подчеркивания и
слэш, где слэш используется в качестве разграничителя для многовложенных подпапок (например `panels/admin`).
......@@ -252,7 +252,7 @@ class SiteController extends Controller
### Отдельные действия <a name="standalone-actions"></a>
Отдельные действия определяются в качестве классов, унаследованных от [[yii\base\Action]] иди его потомков.
Отдельные действия определяются в качестве классов, унаследованных от [[yii\base\Action]] или его потомков.
Например, в Yii релизах, присутствуют [[yii\web\ViewAction]] и [[yii\web\ErrorAction]], оба из которых являются
отдельными действиями.
......
......@@ -562,7 +562,7 @@ $this->registerLinkTag([
- [[yii\base\View::EVENT_BEFORE_RENDER|EVENT_BEFORE_RENDER]]: вызывается в начале рендеринга файла в контроллере.
Обработчики этого события могут придать атрибуту [[yii\base\ViewEvent::isValid]] значение `false`, чтобы отменить процесс рендеринга.
- [[yii\base\View::EVENT_AFTER_RENDER|EVENT_AFTER_RENDER]]: событие инициируется вызовом [[yii\base\View::beginPage()]] в шаблонах.
- [[yii\base\View::EVENT_AFTER_RENDER|EVENT_AFTER_RENDER]]: событие инициируется после рендеринга файла вызовом [[yii\base\View::afterRender()]].
Обработчики события могут получать результат рендеринга через [[yii\base\ViewEvent::output]] и могут изменять это свойство для изменения
результата рендеринга.
- [[yii\base\View::EVENT_BEGIN_PAGE|EVENT_BEGIN_PAGE]]: инициируется вызовом [[yii\base\View::beginPage()]] в шаблонах.
......
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.
Ushbu qo'llanma [Yii qo'llanmalarining holati](http://www.yiiframework.com/doc/terms/) bilan mos holda yo'lga qo'yildi.
All Rights Reserved.
......
1.1 dan keyingi yangilanishlar
==============================
Yii 2.0 talqini uchun batamom boshqatdan yozilganligi bois 1.1 va 2.0 talqinlar orasida ko'p farqlar mavjud.
Shu tufayli 1.1 dan keyingi yangilanishlar minor talqinlar (talqinlarning bir biridan 1-xonasidan keyingi xonalaridagi sonlari farq qiladiganlari) orasidagi yangilanishlar kabi sodda ko'rinishda bo'lmaydi.
Ushbu qo'llanmada ikki talqin orasidagi asossiy farq yangilanishlari keltirilgan.
Agar siz ilgari Yii 1.1 ni ishlatmagan bo'lsangiz u holda ushbu bo'limni tashlab, [Ishni boshlash][start-installation.md] bo'limiga o'tishingiz mumkin.
Shuningdek shuni unutmangki Yii 2.0 bu yerda yozilganidan ko'proq imkoniyatlarga ega. Qaysi imkoniyatlar qo'shilganini bilish uchun qo'llanmani o'qib chiqish tavsiya etiladi. Balkim siz bunga qadar o'zingiz uchun zarur deb bilib yaratgan imkoniyat endi freymvorkning bir qismidir.
O'rnatish
---------
Yii ning 2.0 talqini PHP uchun bog'liqliklarni boshqaruvchi hisoblangan [Composer](https://getcomposer.org/) ga butunlay asoslangan.
Freymvorkni o'rnatish va shuningdek kengaytirish Composer orqali qilinadi. Yii 2.0 ni o'rnatish bo'yicha yanada batafsilroq ma'lumot
[Yii ni o'rnatish](start-installation.md) bo'limida keltirilgan. Yii 2.0 uchun qanday qilib kengaytmalar yaratish yoki 1.1 talqindagi mavjud kengaytmalarni qanday qilib 2.0 talqinga adaptiatsiyalash ko'rsatmalari [Kengaytmalarni yaratish](extend-creating-extensions.md) bo'limida ko'rsatilgan.
PHP talabi
----------
Yii 2.0 talqin Yii 1.1 talqinda qo'llanilgan PHP 5.2 ga nisbatan ancha yaxshilangan PHP 5.4 yoki undan yuqorisini islatadi.
Shu tufayli siz nazarda tutishingiz kerak bo'lgan tildagi ko'p o'zgarishlar mavjud.
Quyida PHP ning asosiy o'zgarishlari keltirilgan:
- [Nomlar sohasi](http://php.net/manual/ru/language.namespaces.php);
- [Anonim funksiyalar](http://php.net/manual/ru/functions.anonymous.php);
- Massivlar uchun qisqa sintaksisni qo'llash: `[...elementlar...]` ni `array(...элементы...)` o'rniga;
- Qisqartirilgan teglarni qo'llash `<?=` ko'rinish fayllarida chiqarish uchun.
PHP 5.4 talqinida ushbu imkoniyatni hech qanday sozlashlarsiz qo'llash mumkin;
- [SPL ning klaslari va interfeyslari](http://php.net/manual/ru/book.spl.php);
- [Kechroq statik bog'lash (LSB)](http://php.net/manual/ru/language.oop5.late-static-bindings.php);
- [Sana va vaqt uchun klaslar](http://php.net/manual/ru/book.datetime.php);
- [Treytlar](http://php.net/manual/ru/language.oop5.traits.php);
- [Xalqarolashtirish (Intl)](http://php.net/manual/ru/book.intl.php); Xalqarolashtirish imkoniyatlaridan foydalanish maqsadida Yii 2.0 PHP ning `intl` kengaytmasini ishlatadi.
Nomlar sohasi
-------------
Yii 2.0 ning asosiy o'zgarishlaridan biri bu nomlar sohasi hisoblanadi. Freymvorkning deyarli har bir sinfi nomlar sohasida joylashgan, masalan, `yii\web\Request`.
"C" qo'shimchasi endi klaslar nomlarida ishlatilmaydi.
Klaslarni nomlash kelishuvi direktoriyalar strukturasiga asoslanilgan. Masalan, `yii\web\Request` ushbu yozuv klasning yii freymvork direktoriyasidagi web/Request.php faylida joylashganini anglatadi.
(Yii ning klaslarni yuklovchisi evaziga siz freymvork klaslarini hech qanday vositachisiz boglab qo'yishingiz mumkin).
Komponent va obekt
------------------
Yii 2.0 da 1.1 dagi `CComponent` klas ikkita klasga ajratilgan: [[yii\base\Object]] va [[yii\base\Component]].
[[yii\base\Object|Object]] klas oddiy asos klas bo'lib xususiyatlar uchun [getter va setter](concept-properties.md) larni ishlatishga imkon beradi.
[[yii\base\Component|Component]] klas [[yii\base\Object|Object]] klasdan voris bo'lib [xodisalar](concept-events.md) va
[o'zini tutish](concept-behaviors.md) larni qo'llab quvvatlaydi.
Agar sizni klasingizga xodisalar funksiyalari yoki o'zini tutishlar kerak bo'lmasa asos klas sifatida [[yii\base\Object|Object]] ni qo'llashingiz mumkin. Ushbu holat asosan asos strukturali klaslar yaratilayotgan vaqtda yuz beradi.
Obekt sozlashlari
-----------------
[[yii\base\Object|Object]] klas obektlarni sozlashni yagona usulini tashkillashtiradi. Ixtiyoriy [[yii\base\Object|Object]] ga voris bo'lgan klas (agar kerak bo'lsa) o'zini sozlashi uchun quyidagi ko'rinishda o'ziga konstruktor yaratishi mumkin:
```php
class MyClass extends \yii\base\Object
{
public function __construct($param1, $param2, $config = [])
{
// ... sozlashlar qo'llanilishidan oldin initsializatsiyalash (e'lon qilish va qiymatlash)
parent::__construct($config);
}
public function init()
{
parent::init();
// ... sozlashlar qo'llanilganidan keyin initsializatsiyalash
}
}
```
Yuqoridagi misolda oxirgi parametr obekt xususiyatlarini qiymatlovchi sozlashlar massivi ya'ni kalit-qiymat formatidagi juftlikdan iborat bo'lishi kerak. Siz sozlashlar qo'llanilganidan keyin initsializatsiya ishini amalga oshirish uchun oldindan [[yii\base\Object::init()|init()]] metod yaratib qo'yishingiz mumkin.
Ushbu kelishuvga asoslanib siz sozlash massivi yordamida yangi obektlarni yaratish va sozlashingiz mumkin:
```php
$object = Yii::createObject([
'class' => 'MyClass',
'property1' => 'abc',
'property2' => 'cde',
], [$param1, $param2]);
```
Sozlashlar haqidagi batafsil ma'lumotlar [Obektlarni sozlash](concept-configurations.md) bo'limida keltirilgan.
......@@ -90,14 +90,14 @@ Getting Data from Users
* [Creating Forms](input-forms.md)
* [Validating Input](input-validation.md)
* **TBD** [Uploading Files](input-file-upload.md)
* [Uploading Files](input-file-upload.md)
* **TBD** [Getting Data for Multiple Models](input-multiple-models.md)
Displaying Data
---------------
* **TBD** [Data Formatting](output-formatter.md)
* [Data Formatting](output-formatter.md)
* **TBD** [Pagination](output-pagination.md)
* **TBD** [Sorting](output-sorting.md)
* [Data Providers](output-data-providers.md)
......@@ -169,7 +169,7 @@ Special Topics
* [Internationalization](tutorial-i18n.md)
* [Mailing](tutorial-mailing.md)
* [Performance Tuning](tutorial-performance-tuning.md)
* **TBD** [Shared Hosting Environment](tutorial-shared-hosting.md)
* [Shared Hosting Environment](tutorial-shared-hosting.md)
* [Template Engines](tutorial-template-engines.md)
* [Working with Third-Party Code](tutorial-yii-integration.md)
......
......@@ -130,7 +130,7 @@ an [entry script](structure-entry-scripts.md), where the class name is already g
(new yii\web\Application($config))->run();
```
For more details about configuring the `components` property of an application can be found
More details about configuring the `components` property of an application can be found
in the [Applications](structure-applications.md) section and the [Service Locator](concept-service-locator.md) section.
......@@ -153,7 +153,7 @@ echo Menu::widget([
]);
```
The above code creates a `Menu` widget and initializes its `activeItems` property to be false.
The above code creates a `Menu` widget and initializes its `activateItems` property to be false.
The `items` property is also configured with menu items to be displayed.
Note that because the class name is already given, the configuration array should NOT have the `class` key.
......@@ -215,7 +215,7 @@ $config = require('path/to/web.php');
## Default Configurations <a name="default-configurations"></a>
The [[Yii::createObject()]] method is implemented based on a [dependency injection container](concept-di-container.md).
It allows you to specify a set of the so-called *default configurations* which will be applied to ANY instances of
It allows you to specify a set of the so-called *default configurations* which will be applied to ALL instances of
the specified classes when they are being created using [[Yii::createObject()]]. The default configurations
can be specified by calling `Yii::$container->set()` in the [bootstrapping](runtime-bootstrapping.md) code.
......
......@@ -202,7 +202,7 @@ Sometimes, you may want to respond to an event triggered by *every* instance of
a specific instance. Instead of attaching an event handler to every instance, you may attach the handler
on the *class level* by calling the static method [[yii\base\Event::on()]].
For example, an [Active Record](db-active-record.md) object will trigger an [[yii\base\ActiveRecord::EVENT_AFTER_INSERT]]
For example, an [Active Record](db-active-record.md) object will trigger an [[yii\db\BaseActiveRecord::EVENT_AFTER_INSERT|EVENT_AFTER_INSERT]]
event whenever it inserts a new record into the database. In order to track insertions done by *every*
[Active Record](db-active-record.md) object, you may use the following code:
......@@ -216,8 +216,8 @@ Event::on(ActiveRecord::className(), ActiveRecord::EVENT_AFTER_INSERT, function
});
```
The event handler will be invoked whenever an instance of [[yii\base\ActiveRecord|ActiveRecord]], or one of its child classes, triggers
the [[yii\base\ActiveRecord::EVENT_AFTER_INSERT|EVENT_AFTER_INSERT]] event. In the handler, you can get the object
The event handler will be invoked whenever an instance of [[yii\db\ActiveRecord|ActiveRecord]], or one of its child classes, triggers
the [[yii\db\BaseActiveRecord::EVENT_AFTER_INSERT|EVENT_AFTER_INSERT]] event. In the handler, you can get the object
that triggered the event through `$event->sender`.
When an object triggers an event, it will first call instance-level handlers, followed by the class-level handlers.
......
......@@ -10,7 +10,7 @@ $object->label = trim($label);
```
The drawback of the above code is that you would have to call `trim()` everywhere in your code where you might set the `label`
property. If, in the future, the `label` property gets a new requirement, such as the first letter must be captialized, you would again have to modify every bit of code that assigns a value to `label`. The repetition of code leads to bugs, and is a practice you want to avoid as much as possible.
property. If, in the future, the `label` property gets a new requirement, such as the first letter must be capitalized, you would again have to modify every bit of code that assigns a value to `label`. The repetition of code leads to bugs, and is a practice you want to avoid as much as possible.
To solve this problem, Yii introduces a base class called [[yii\base\Object]] that supports defining properties
based on *getter* and *setter* class methods. If a class needs that functionality, it should extend from
......@@ -28,7 +28,7 @@ namespace app\components;
use yii\base\Object;
class Foo extend Object
class Foo extends Object
{
private $_label;
......@@ -44,10 +44,10 @@ class Foo extend Object
}
```
(To be clear, the getter and setter methods create the property `label`, which in this case internally refer to a private attributed named `_label`.)
(To be clear, the getter and setter methods create the property `label`, which in this case internally refers to a private attribute named `_label`.)
Properties defined by getters and setters can be used like class member variables. The main difference is that
when such a property is being read, the corresponding getter method will be called; when the property is
when such property is being read, the corresponding getter method will be called; when the property is
being assigned a value, the corresponding setter method will be called. For example:
```php
......@@ -58,20 +58,20 @@ $label = $object->label;
$object->label = 'abc';
```
A property defined by a getter without a setter is *read only*. Trying to assign a value to such a property will cause
A property defined by a getter without a setter is *read only*. Trying to assign a value to such property will cause
an [[yii\base\InvalidCallException|InvalidCallException]]. Similarly, a property defined by a setter without a getter
is *write only*, and trying to read such a property will also cause an exception. It is not common to have write-only
is *write only*, and trying to read such property will also cause an exception. It is not common to have write-only
properties.
There are several special rules for, and limitations on, the properties defined via getters and setters:
* The names of such properties are *case-insensitive*. For example, `$object->label` and `$object->Label` are the same.
This is because method names in PHP are case-insensitive.
* If the name of such a property is the same as a class member variable, the latter will take precedence.
* If the name of such property is the same as a class member variable, the latter will take precedence.
For example, if the above `Foo` class has a member variable `label`, then the assignment `$object->label = 'abc'`
will affect the *member variable* 'label'; that line would not call the `setLabel()` setter method.
* These properties do not support visibility. It makes no difference for the visibility of a property
if the defining getter or setter method is public, protected or private.
* The properties can only be defined by *non-static* getters and/or setters. Static methods will not be treated in this same manner.
* The properties can only be defined by *non-static* getters and/or setters. Static methods will not be treated in the same manner.
Returning back to the problem described at the beginning of this guide, instead of calling `trim()` everywhere a `label` value is assigned, `trim()` now only needs to be invoked within the setter `setLabel()`. And if a new requirement comes that requires the label be initially capitalized, the `setLabel()` method can quickly be modified without touching any other code. The one change will universally affect every assignment to `label`.
Returning back to the problem described at the beginning of this guide, instead of calling `trim()` everywhere a `label` value is assigned, `trim()` now only needs to be invoked within the setter `setLabel()`. And if a new requirement comes that requires the label to be initially capitalized, the `setLabel()` method can quickly be modified without touching any other code. The one change will universally affect every assignment to `label`.
......@@ -35,7 +35,8 @@ Below is the list of databases that are currently supported by Yii Active Record
* SQLite 2 and 3: via [[yii\db\ActiveRecord]]
* Microsoft SQL Server 2010 or later: via [[yii\db\ActiveRecord]]
* Oracle: via [[yii\db\ActiveRecord]]
* CUBRID 9.1 or later: via [[yii\db\ActiveRecord]]
* CUBRID 9.3 or later: via [[yii\db\ActiveRecord]] (Note that due to a [bug](http://jira.cubrid.org/browse/APIS-658) in
the cubrid PDO extension, quoting of values will not work, so you need CUBRID 9.3 as the client as well as the server)
* Sphnix: via [[yii\sphinx\ActiveRecord]], requires `yii2-sphinx` extension
* ElasticSearch: via [[yii\elasticsearch\ActiveRecord]], requires `yii2-elasticsearch` extension
* Redis 2.6.12 or later: via [[yii\redis\ActiveRecord]], requires `yii2-redis` extension
......@@ -330,6 +331,16 @@ $customer->loadDefaultValues();
// ... render HTML form for $customer ...
```
If you want to set some initial values for the attributes yourself you can override the `init()` method
of the active record class and set the values there. For example to set the default value for the `status` attribute:
```php
public function init()
{
parent::init();
$this->status = 'active';
}
```
Active Record Life Cycles
-------------------------
......
File mode changed from 100755 to 100644
......@@ -391,7 +391,7 @@ class CountryValidator extends Validator
public function validateAttribute($model, $attribute)
{
if (!in_array($model->$attribute, ['USA', 'Web'])) {
$this->addError($attribute, 'The country must be either "USA" or "Web".');
$this->addError($model, $attribute, 'The country must be either "USA" or "Web".');
}
}
}
......
......@@ -143,7 +143,7 @@ supported in most places in the Yii core code. For example, [[yii\caching\FileCa
both a path alias and a normal directory path.
A path alias is also closely related to a class namespace. It is recommended that a path
alias be defined for each root namespace, thereby allowing you to use Yii the class autoloader without
alias be defined for each root namespace, thereby allowing you to use Yii class autoloader without
any further configuration. For example, because `@yii` refers to the Yii installation directory,
a class like `yii\web\Request` can be autoloaded. If you use a third party library,
such as the Zend Framework, you may define a path alias `@Zend` that refers to that framework's installation
......
......@@ -8,7 +8,7 @@ when rendered. A single application may use multiple themes and each may provide
time only one theme can be active.
> Note: Themes usually do not meant to be redistributed since views are too application specific. If you want to
redistribute customized look and feel consider CSS and JavaScript files in form of [asset bundles](assets.md) instead.
redistribute customized look and feel consider CSS and JavaScript files in form of [asset bundles](structure-assets.md) instead.
Configuring a theme
-------------------
......
......@@ -3,14 +3,14 @@ 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.
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.
by default.
### Opening and Closing Sessions <a name="opening-closing-sessions"></a>
......@@ -74,7 +74,7 @@ if it has not been done so before. This is different from accessing session data
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,
directly modifying an array element. For example,
```php
$session = Yii::$app->session;
......@@ -122,7 +122,7 @@ $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>
......@@ -131,7 +131,7 @@ 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\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
......@@ -174,7 +174,10 @@ where 'BLOB' refers to the BLOB-type of your preferred DBMS. Below are the BLOB
- PostgreSQL: BYTEA
- MSSQL: BLOB
Note that length of id column should be adjusted if `session.hash_function` is changed in `php.ini`.
> Note: According to the php.ini setting of `session.hash_function`, you may need to adjust
the length of the `id` column. For example, if `session.hash_function=sha256`, you should use
length 64 instead of 40.
### Flash Data <a name="flash-data"></a>
......@@ -191,7 +194,7 @@ $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');
......@@ -201,11 +204,11 @@ echo $session->getFlash('postDeleted');
$result = $session->hasFlash('postDeleted');
```
Like regular session data, you can store arbitrary data as flash data.
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,
For example:
```php
$session = Yii::$app->session;
......@@ -222,8 +225,8 @@ $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
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.
......@@ -231,8 +234,8 @@ $alerts = $session->getFlash('alerts');
## 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
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.
......@@ -275,10 +278,10 @@ $cookies = Yii::$app->response->cookies;
$cookies->add(new \yii\web\Cookie([
'name' => 'language',
'value' => 'zh-CN',
]);
]));
// remove a cookie
$cookies->remove('language');
$cookies->remove('language');
// equivalent to the following
unset($cookies['language']);
```
......@@ -288,9 +291,9 @@ examples, the [[yii\web\Cookie]] class also defines other properties to fully re
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.
> Note: For better security, the default value of [[yii\web\Cookie::httpOnly]] is set true. This helps mitigate
> Note: For better security, the default value of [[yii\web\Cookie::httpOnly]] is set true. This helps mitigate
the risk of client side script accessing the protected cookie (if the browser supports it). You may read
the [httpOnly wiki article](https://www.owasp.org/index.php/HttpOnly) for more details.
the [httpOnly wiki article](https://www.owasp.org/index.php/HttpOnly) for more details.
### Cookie Validation <a name="cookie-validation"></a>
......@@ -299,15 +302,15 @@ When you are reading and sending cookies through the `request` and `response` co
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, which allows the application to
tell if a cookie is modified on the client side or not. If so, the cookie will NOT be accessible through the
[[yii\web\Request::cookies|cookie collection]] of the `request` component.
[[yii\web\Request::cookies|cookie collection]] of the `request` component.
> Info: If a cookie fails the validation, you may still access it through `$_COOKIE`. This is because third-party
libraries may manipulate cookies in their own way, which does not involve cookie validation.
libraries may manipulate cookies in their own way, which does not involve cookie validation.
Cookie validation is enabled by default. You can disable it by setting the [[yii\web\Request::enableCookieValidation]]
Cookie validation is enabled by default. You can disable it by setting the [[yii\web\Request::enableCookieValidation]]
property to be false, although we strongly recommend you do not do so.
> Note: Cookies that are directly read/sent via `$_COOKIE` and `setcookie()` will NOT be validated.
> 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:
......
......@@ -219,8 +219,8 @@ Building authorization data is all about the following tasks:
Depending on authorization flexibility requirements the tasks above could be done in different ways.
If your permissions hierarchy doesn't change at all and you have a fixed number of users you can create a console
command that will initialize authorization data once via APIs offered by `authManager`:
If your permissions hierarchy doesn't change at all and you have a fixed number of users you can create a
[console command](tutorial-console.md#create-command) command that will initialize authorization data once via APIs offered by `authManager`:
```php
<?php
......@@ -347,7 +347,7 @@ $rule = new \app\rbac\AuthorRule;
$auth->add($rule);
// add the "updateOwnPost" permission and associate the rule with it.
$updateOwnPost = $this->auth->createPermission('updateOwnPost');
$updateOwnPost = $auth->createPermission('updateOwnPost');
$updateOwnPost->description = 'Update own post';
$updateOwnPost->ruleName = $rule->name;
$auth->add($updateOwnPost);
......
......@@ -26,7 +26,7 @@ by running `composer self-update`.
With Composer installed, you can install Yii by running the following commands under a Web-accessible folder:
composer global require "fxp/composer-asset-plugin:1.0.0-beta2"
composer global require "fxp/composer-asset-plugin:1.0.0-beta3"
composer create-project --prefer-dist yiisoft/yii2-app-basic basic
The first command installs the [composer asset plugin](https://github.com/francoispluchino/composer-asset-plugin/)
......
File mode changed from 100755 to 100644
......@@ -388,7 +388,7 @@ the following syntax and file name extensions:
- [CoffeeScript](http://coffeescript.org/): `.coffee`
- [TypeScript](http://www.typescriptlang.org/): `.ts`
Yii relies on the installed pre-processor tools to convert assets. For example, o use [LESS](http://lesscss.org/)
Yii relies on the installed pre-processor tools to convert assets. For example, to use [LESS](http://lesscss.org/)
you should install the `lessc` pre-processor command.
You can customize the pre-processor commands and the supported extended syntax by configuring
......
......@@ -636,7 +636,7 @@ to these events to inject content into views or process the rendering results be
- [[yii\base\View::EVENT_BEFORE_RENDER|EVENT_BEFORE_RENDER]]: triggered at the beginning of rendering a file
in a controller. Handlers of this event may set [[yii\base\ViewEvent::isValid]] to be false to cancel the rendering process.
- [[yii\base\View::EVENT_AFTER_RENDER|EVENT_AFTER_RENDER]]: triggered by the call of [[yii\base\View::beginPage()]] in layouts.
- [[yii\base\View::EVENT_AFTER_RENDER|EVENT_AFTER_RENDER]]: triggered after rendering a file by the call of [[yii\base\View::afterRender()]].
Handlers of this event may obtain the rendering result through [[yii\base\ViewEvent::output]] and may modify
this property to change the rendering result.
- [[yii\base\View::EVENT_BEGIN_PAGE|EVENT_BEGIN_PAGE]]: triggered by the call of [[yii\base\View::beginPage()]] in layouts.
......
......@@ -29,8 +29,8 @@ The process of developing a feature is the following:
After it's done the process is repeated again for another feature or improvement. If existing feature is to be changed,
tests should be changed as well.
> **Tip**: If you feel that you are loosing time doing a lot of small and simple iterations try covering more by your
> test scenario so you do more before executing tests again. If you're debugging too much try doing the opposite.
> **Tip**: If you feel that you are losing time doing a lot of small and simple iterations, try covering more by your
> test scenario so you do more before executing tests again. If you're debugging too much, try doing the opposite.
The reason to create tests before doing any implemenation is that it allows you to focus on what do we want to achieve
and fully dive into "how to do it" afterwards. Usually it leads to better abstractions and easier test maintenance when
......
......@@ -17,8 +17,8 @@ If you do not have [Composer](http://getcomposer.org/), follow the instructions
With Composer installed, you can then install the application using the following commands:
composer global require "fxp/composer-asset-plugin:1.0.0-beta2"
composer create-project --prefer-dist --stability=dev yiisoft/yii2-app-advanced yii-application
composer global require "fxp/composer-asset-plugin:1.0.0-beta3"
composer create-project --prefer-dist yiisoft/yii2-app-advanced yii-application
The first command installs the [composer asset plugin](https://github.com/francoispluchino/composer-asset-plugin/)
which allows managing bower and npm package dependencies through Composer. You only need to run this command
......
......@@ -6,7 +6,8 @@ Console applications
Yii has full featured support for console applications, whose structure is very similar to a Yii web application. A console application
consists of one or more [[yii\console\Controller]] classes, which are often referred to as "commands" in the console environment. Each controller can also have one or more actions, just like web controllers.
Usage
Usage <a name="usage"></a>
-----
You execute a console controller action using the following syntax:
......@@ -23,13 +24,18 @@ be called from command line like so:
yii migrate/create --migrationTable=my_migration
```
In the above `yii` is the console application entry script described below.
In the above `yii` is the console application entry script which is described below.
> **Note**: When using `*` in console don't forget to quote it as `"*"` in order to avoid executing it as a shell
> glob that will be replaced by all file names of the current directory.
Entry script
Entry script <a name="entry-script"></a>
------------
The console application entry script is equivalent to the `index.php` bootstrap file used for the web application. The console entry script is typically called `yii`, and located in your application's root directory. The contents of the console application entry script contains
code like the following:
The console application entry script is equivalent to the `index.php` bootstrap file used for the web application.
The console entry script is typically called `yii`, and located in your application's root directory.
It contains code like the following:
```php
#!/usr/bin/env php
......@@ -52,14 +58,14 @@ $config = require(__DIR__ . '/config/console.php');
$application = new yii\console\Application($config);
$exitCode = $application->run();
exit($exitCode);
```
This script will be created as part of your application; you're free to edit it to suit your needs. The `YII_DEBUG` constant can be set `false` if you do
not want to see a stack trace on error, and/or if you want to improve the overall performance. In both basic and advanced application
templates, the console application entry script has debugging enabled to provide a more developer-friendly environment.
templates, the console application entry script has debugging enabled by default to provide a more developer-friendly environment.
Configuration
Configuration <a name="configuration"></a>
-------------
As can be seen in the code above, the console application uses its own configuration file, named `console.php`. In this file
......@@ -68,20 +74,18 @@ you should configure various [application components](structure-application-comp
If your web application and the console application share a lot of configuration parameters and values, you may consider moving the common
parts into a separate file, and including this file in both of the application configurations (web and console). You can see an example of this in the "advanced" application template.
Sometimes, you may want to run a console command using an application configuration that is different from the one
specified in the entry script. For example, you may want to use the `yii migrate` command to upgrade your
test databases, which are configured in each individual test suite. To do change the configuration dynamically, simply specify a custom application configuration
file via the `appconfig` option when executing the command:
```
yii <route> --appconfig=path/to/config.php ...
```
> **Note**: When using `*` in console don't forget to quote it as `"*"` in order to avoid executing it as a shell
> command.
> Tipp: Sometimes, you may want to run a console command using an application configuration that is different
> from the one specified in the entry script. For example, you may want to use the `yii migrate` command to
> upgrade your test databases, which are configured in each individual test suite. To do change the configuration
> dynamically, simply specify a custom application configuration
> file via the `appconfig` option when executing the command:
>
> ```
> yii <route> --appconfig=path/to/config.php ...
> ```
Creating your own console commands
Creating your own console commands <a name="create-command"></a>
----------------------------------
### Console Controller and Action
......
......@@ -97,7 +97,7 @@ is as specified by the `operator` property.
```php
[
[['from', 'to'], 'date'],
[['from_date', 'to_date'], 'date'],
]
```
......@@ -113,6 +113,13 @@ specified via [[yii\validators\DateValidator::timestampAttribute|timestampAttrib
- `timestampAttribute`: the name of the attribute to which this validator may assign the UNIX timestamp
converted from the input date/time.
In case the input is optional you may also want to add a default value filter in addition to the date validator
to ensure empty input is stored as `NULL`. Other wise you may end up with dates like `0000-00-00` in your database
or `1970-01-01` in the input field of a date picker.
```php
[['from_date', 'to_date'], 'default', 'value' => null],
```
## [[yii\validators\DefaultValueValidator|default]] <a name="default"></a>
......
......@@ -61,7 +61,7 @@ $message->setTo(Yii::$app->params['adminEmail'])
```
> Note: each 'mailer' extension comes in 2 major classes: 'Mailer' and 'Message'. 'Mailer' always knows
the class name and specific of the 'Message'. Do not attempt ot instantiate 'Message' object directly -
the class name and specific of the 'Message'. Do not attempt to instantiate 'Message' object directly -
always use `compose()` method for it.
You may also send several messages at once:
......
......@@ -85,7 +85,7 @@ Note that the `cache` [application component](structure-application-components.m
It is possible to combine and minimize assets, typically JavaScript and CSS, in order to slightly improve page load
time and therefore deliver better experience for end user of your application.
In order to learn how it can be achieved, refer to [assets](assets.md) guide section.
In order to learn how it can be achieved, refer to [assets](structure-assets.md) guide section.
### Using better storage for sessions
......
Shared Hosting Environment
==========================
Shared hosting environments are often quite limited about configuration and directory structure. Still in most cases
you can run Yii 2.0 on these.
Deploying basic application
---------------------------
Since there's typically only one webroot it is recommended to use basic application template. Refer to
[Installing Yii chapter](start-installation.md) and install application template locally.
### Add extras for webserver
If webserver used is Apache you'll need to add `.htaccess` file with the following content to `web`
(where `index.php` is):
```
Options +FollowSymLinks
IndexIgnore */*
RewriteEngine on
# if a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# otherwise forward it to index.php
RewriteRule . index.php
```
In case of nginx you should not need any extra config files.
### Renaming webroot
If after connecting to your shared hosting via FTP or by other means you're seeing something like the following, you're
most probably lucky.
```
config/
logs/
www/
```
In the above `www` is webserver directory root (i.e. webroot). It could be named differently. Common names are: `www`,
`htdocs`, `public_html`. Since we have webroot in our basic application template named `web` we need to rename it to
whatever hosting webroot is before uploading.
### FTP root directory is writeable
If you can write to the root level directory i.e. where `config`, `logs` and `www` are, just upload `assets`, `commands`
etc. as is.
### Check requirements
In order to run Yii hosting should meet its requirements. The very minimum requirement is PHP 5.4. In order to check
the rest copy `requirements.php` from root directory into webroot directory and run it via browser using
`http://example.com/requirements.php` URL. Don't forget to delete the file afterwards.
Deploying advanced application
------------------------------
Deploying advanced application to shared hosting is a bit trickier than doing it with basic application because it has
two webroots.
\ No newline at end of file
......@@ -3,13 +3,15 @@ Creating your own Application structure
> Note: This section is under development.
While the [basic](apps-basic.md) and [advanced](apps-advanced.md) application templates are great for most of your needs,
you may want to create your own application template with which to start your projects.
While the [basic](https://github.com/yiisoft/yii2/tree/master/apps/basic) and [advanced](https://github.com/yiisoft/yii2/tree/master/apps/advanced)
application templates are great for most of your needs, you may want to create your own application template with which
to start your projects.
Application templates in Yii are simply repositories containing a `composer.json` file, and registered as a Composer package. Any repository can be identified as a Composer package, making it installable via `create-project` Composer command.
Application templates in Yii are simply repositories containing a `composer.json` file, and registered as a Composer package.
Any repository can be identified as a Composer package, making it installable via `create-project` Composer command.
Since it's a bit too much to start building your entire template from scratch, it is better to use one of the built-in templates
as a base. Let's use the basic template here.
Since it's a bit too much to start building your entire template from scratch, it is better to use one of the built-in
templates as a base. Let's use the basic template here.
Clone the Basic Template
----------------------------------------
......@@ -37,10 +39,10 @@ Next, actually modify the structure and contents of the application as you would
Make a Package
--------------
With the template defined, create a Git repository from it, and push your files there. If you're going to open source your template, [Github](http://githumb.com) is the best place to host it. If you intend to keep your template non-collaborative, any Git repository site will do.
With the template defined, create a Git repository from it, and push your files there. If you're going to open source your template, [Github](http://github.com) is the best place to host it. If you intend to keep your template non-collaborative, any Git repository site will do.
Next, you need to register your package for Composer's sake. For public templates, the package should be registered at [Packagist](https://packagist.org/).
For private templates, it is a bit more tricky to register the packge. For instructions, see the [Composer documentation](https://getcomposer.org/doc/05-repositories.md#hosting-your-own).
For private templates, it is a bit more tricky to register the package. For instructions, see the [Composer documentation](https://getcomposer.org/doc/05-repositories.md#hosting-your-own).
Use the Template
------
......@@ -48,6 +50,6 @@ Use the Template
That's all that's required to create a new Yii application template. Now you can create projects using your template:
```
composer global require "fxp/composer-asset-plugin:1.0.0-beta2"
composer global require "fxp/composer-asset-plugin:1.0.0-beta3"
composer create-project --prefer-dist --stability=dev mysoft/yii2-app-coolone new-project
```
......@@ -21,8 +21,11 @@ component's behavior:
],
'twig' => [
'class' => 'yii\twig\ViewRenderer',
//'cachePath' => '@runtime/Twig/cache',
//'options' => [], /* Array of twig options */
'cachePath' => '@runtime/Twig/cache',
// Array of twig options:
'options' => [
'auto_reload' => true,
],
'globals' => ['html' => '\yii\helpers\Html'],
'uses' => ['yii\bootstrap'],
],
......
Flujo de Trabajo de Traducción
==============================
Yii se traduce en muchos idiomas con el fin de ser útil para desarrolladores de aplicaciones e internacionales. Dos áreas principales donde la contribución es muy bienvenida son la documentación y los mensajes del framework.
Yii se traduce en muchos idiomas con el fin de ser útil para desarrolladores de aplicaciones e internacionales.
Dos áreas principales donde la contribución es muy bienvenida son la documentación y los mensajes del framework.
Framework Mensajes
------------------
Mensajes del Framework
----------------------
Framework tiene dos tipos de mensajes: excepciones que están destinados al desarrollador y nunca se traducen y mensajes
El framework tiene dos tipos de mensajes: excepciones que están destinadas al desarrollador y nunca se traducen, y mensajes
que en realidad son visibles para el usuario final, tales como errores de validación.
El orden para comenzar con la traducción de mensajes:
1. Comprobar `framework/messages/config.php` y asegúrese de que su lenguaje aparece en `lenguajes`. Si no, añadir su lenguaje allí (recuerde que debe mantener la lista en orden alfabético). El formato de código de idioma debe seguir [Código de Idiomas IETF](http://es.wikipedia.org/wiki/C%C3%B3digo_de_idioma_IETF), por ejemplo, `es`.
2. Ir al `framework` y ejecutar `yii message/extract messages/config.php`.
3. Traducir los mensajes en `framework/messages/your_lenguaje/yii.php`. Asegúrese de guardar el archivo con codificación UTF-8.
1. Comprobar que en `framework/messages/config.php` su idioma aparece en `languages`. Si no, añade tu idioma allí (recuerda que debes mantener la lista en orden alfabético).
El formato de código de idioma debe seguir el [Código de Idiomas IETF](http://es.wikipedia.org/wiki/C%C3%B3digo_de_idioma_IETF), por ejemplo, `es`.
2. Ir al directorio `framework` y ejecutar el comando `yii message/extract messages/config.php`.
3. Traducir los mensajes en `framework/messages/tu-idioma/yii.php`. Asegúrate de guardar el archivo con codificación UTF-8.
4. [Crear un pull request](https://github.com/yiisoft/yii2/blob/master/docs/internals-es/git-workflow.md).
Con el fin de mantener la traducción al día puede ejecutar `yii message/extract messages/config.php` nuevamente. Se volverán a extraer automáticamente los mensajes de mantenimiento intactos sin los cambios.
Con el fin de mantener la traducción al día puedes ejecutar `yii message/extract messages/config.php` nuevamente.
Se volverán a extraer automáticamente los mensajes de mantenimiento intactos sin los cambios.
En el archivo de traducción de cada elemento de la matriz representa la traducción (valor) de un mensaje (clave). Si el valor está vacío, el mensaje se considera como no traducida. Los mensajes que ya no necesiten traducción tendrán sus traducciones encerrado entre un par de marcas »@@. Cadena de mensaje se puede utilizar con el formato de formas plurales. Compruebe [sección i18n de la guía](../guide-es/tutorial-i18n.md) para más detalles.
En el archivo de traducción de cada elemento del `array` representa un mensaje (clave) y su la traducción (valor). Si el valor está vacío, el mensaje se considera como no traducido.
Los mensajes que ya no necesiten traducción tendrán sus traducciones encerrado entre un par de marcas '@@'. El texto de los mensajes se puede utilizar con el formato de formas plurales.
Chequea la [sección i18n de la guía](../guide-es/tutorial-i18n.md) para más detalles.
Documentación
-------------
Coloque traducciones de documentación bajo `docs/<original>-<lenguaje>` donde `<original>` es el nombre de la documentación original como `guide` o `internals` y `<lenguaje>` es el código de Lenguaje de los docs Lenguaje se convierten a. Para la traducción de guias es `docs/guide-es`.
Coloca las traducciones de la documentación bajo `docs/<original>-<language>` donde `<original>` es el nombre de la documentación original como `guide` o `internals`
y `<language>` es el código del idioma al que se está traduciendo. Para la traducción al español de la guía, es `docs/guide-es`.
Después del trabajo inicial se lleva a cabo usted puede conseguir lo que ha cambiado desde la última traducción del fichero usando un comando especial del directorio `build`:
Después de que el trabajo inicial está hecho, puedes obtener los cambios desde la última traducción del archivo usando un comando especial del directorio `build`:
```
php build translation "../docs/guide" "../docs/guide-es" "Reporte de traducción guia en Español" > report_guide_es.html
```
Si se quejan de composer, ejecutar `composer install` en el directorio raíz.
Si recibes un error de composer, ejecuta `composer install` en el directorio raíz.
Convenios para la traducción
----------------------------
- active record — sin traducción
- cache — sin traducción
- framework — sin traducción
- helper — sin traducción
- hash — sin traducción
- id — sin traducción
- widget — sin traducción
- script — sin traducción
- assets — sin traducción
- bootstrapping | bootstrap — sin traducción
- routing — sin traducción
- logging — sin traducción
- cookies — sin traducción
- controller — controlador
- model — modelo
- view — vista
- themes — temas o plantillas
- behaviors — comportamientos
- handlers — manipuladores
- instantiating — instanciando
- link — enlace
- render — sin traducción
- DatePicker — sin traducción
- rendering — renderizando
Las palabras en inglés que son propias del framework o de PHP se pueden dejar en el idioma original. Ejemplos: `namespace`, `assets`, `helper`, `widget`, etc.
Para las palabras que están muy ligadas a conceptos extendidos se deben traducir y poner entre paréntesis su equivalente en el idioma original. Ejemplos : `petición` (request), `respuesta` (response), `comportamiento` (behavior), etc.
Los bloques han de ser traducidos, las traducciones se muestran a continuación :
* `Warning` : `Aviso`
* `Note` : `Nota`
* `Info` : `Información`
* `Tip` : `Consejo`
> Aclaraciones :
* Sólo mencionar una vez entre paréntesis la palabra original en su primera aparición en el texto o en el fichero README.md .
* Si una palabra se refiere a un concepto o acción se aplicará la traducción, si por el contrario se refiere a un tipo de dato de php o del framework no se debe traducir.
自動化
======
Yii の開発に取り組む際に、自動化できるタスクがいくつかあります:
- フレームワークのルートディレクトリに配置されるクラスマップ `classes.php` の生成。
`./build/build classmap` を走らせて生成してください。
- クラスファイルの中の、ゲッターとセッターによって導入されるプロパティを記述する `@property` 注釈の生成。
`./build/build php-doc/property` を走らせて注釈を更新してください。
- コードスタイルと phpdoc コメントの些細な問題の修正。
`./build/build php-doc/fix` を走らせて修正してください。
このコマンドは完璧なものではないため、望ましくない変更があるかもしれませんので、コミットする前に変更点をチェックしてください。
`git add -p` を使って変更をプレビューすることも出来ます。
課題を報告する
==============
あなたが報告する課題(issue 問題)がより迅速に解決されるように、課題を作成するときには下記のガイドラインに従って下さい:
* 以下の情報を提供して下さい: PHP と Yii のバージョン、オペレーティングシステムとウェブサーバのタイプ、ブラウザのタイプとバージョン;
* 出来れば、**完全な**エラーのコールスタックを提供して下さい。問題を説明するスクリーンショットは大いに歓迎します。
* 問題を再現する手順を記述して下さい。問題を再現するコードを提供してくださるならば、なお一層良いでしょう。
**以下の場合は課題を報告しないでください**
* Yii の何らかの機能の使い方に関する質問。この目的のためには、[フォーラム](http://www.yiiframework.com/forum/index.php/forum/42-general-discussions-for-yii-20/) または [チャットルーム](http://www.yiiframework.com/chat/) を使うべきです。
* 問題がセキュリティに関するものである場合。セキュリティ問題を報告するときは、[開発者に直接コンタクト](http://www.yiiframework.com/security/) してください。
**課題の重複を避ける**
課題を報告する前に、[既存の課題](https://github.com/yiisoft/yii2/issues) を検索して、あなたが報告しようとしている課題が既に報告されていたり解決されていたりしないかを確かめ、重複した課題を報告しないようにしてください。
さらにまた、Yii の最新のバージョンを使ってみて、それでもまだ問題が残っているかどうかを確かめてください。
翻訳ワークフロー
================
Yii は国際的なアプリケーションと開発者にとって役に立つように、数多くの言語に翻訳されています。
貢献が大いに歓迎される主な領域はドキュメンテーションとフレームワークメッセージです。
フレームワークメッセージ
------------------------
フレームワークは二種類のメッセージを持っています: 一つは開発者向けの例外メッセージで、これは決して翻訳されません。
もう一つはエンドユーザーが実際に目にする検証エラーのようなメッセージです。
メッセージの翻訳を開始するためには:
1. `framework/messages/config.php` をチェックして、あなたの言語が `languages` のリストに挙っていることを確認してください。
もし挙っていなければ、あなたの言語をそこに追加します(リストをアルファベット順に保つことを忘れないでください)。
言語コードの形式は、例えば `ru``zh-CN` のように、[IETF言語タグ](http://ja.wikipedia.org/wiki/IETF%E8%A8%80%E8%AA%9E%E3%82%BF%E3%82%B0) に従うべきです。
2. `framework` に入って、`yii message/extract messages/config.php` を走らせます。
3. `framework/messages/your_language/yii.php` のメッセージを翻訳します。ファイルは必ず UTF-8 エンコーディングを使って保存してください。
4. [プルリクエスト](https://github.com/yiisoft/yii2/blob/master/docs/internals/git-workflow.md)をします。
あなたの翻訳を最新状態に保つために、`yii message/extract messages/config.php` を再び走らせることが出来ます。
これによって、変更のなかった箇所には触れることなく、自動的にメッセージを再抽出することが出来ます。
翻訳ファイルの中で、配列の各要素は、メッセージ(キー)と翻訳(値)をあらわします。
値が空白の場合は、メッセージは翻訳されないものと見なされます。
翻訳が不要になったメッセージは、翻訳が一組の '@@' マークで囲まれます。
メッセージ文字列は複数形書式とともに使うことが出来ます。
詳細は [ガイドの国際化の章](../guide-ja/tutorial-i18n.md) を参照してください。
ドキュメンテーション
--------------------
ドキュメンテーションの翻訳は `docs/<original>-<language>` の下に置きます。
ここで `<original>` は、`guide``internals` などの元の文書の名前であり、`<language>` は文書が翻訳先の言語のコードです。
例えば、ロシア語のガイドの翻訳は `docs/guide-ru` です。
初期の仕事が完了した後は、最新の翻訳以後に変更された元の文書の箇所を取得するために、`build` ディレクトリにある専用のコマンドを使うことが出来ます:
```
php build translation "../docs/guide" "../docs/guide-ru" "Russian guide translation report" > report_guide_ru.html
```
このコマンドが composer に関して不平を言うようであれば、ソースのルートディレクトリで `composer install` を実行してください。
Yii バージョン番号規約
======================
リリース
--------
A.B.C
A = Yii2 では常に 2。
B = メジャーバージョン。アップグレードのための説明をともなう非後方互換な変更。
C = 後方互換な変更と追加。
リリース候補
------------
A.B.C-rc
A.B.C-rc2
リリース候補を出したいときに用います。RC 番号は、安定したリリースを得て、致命的なバグと後方互換性に関する問題報告が無くなるまで、増加します。
アルファとベータ
----------------
A.B.C-alpha
A.B.C-alpha2
アルファは、著しいバグがおそらく存在するであろう、不安定なバージョンです。
API はまだ固まっておらず、大きく変更されるかもしれません。
`alpha2` などは、コードと API の全体的な安定性によって、リリースされたり、リリースされなかったりします。
A.B.C-beta
A.B.C-beta2
ベータはアルファに比べていくらか安定して、バグや API の不安定性が少なくなったものです。
まだ API が変更されることがあり得ますが、そのためにはかなりの理由がなければならないでしょう。
......@@ -29,6 +29,11 @@ Italian
- Lorenzo Milesi, [@maxxer](https://github.com/maxxer), maxxer@yetopen.it
Japanese
-------
- Nobuo Kihara 木原伸夫, [@softark](https://github.com/softark), softark@gmail.com
Russian
-------
......@@ -41,6 +46,7 @@ Spanish
- Luciano Baraglia, [@lucianobaraglia](https://github.com/lucianobaraglia)
- Marco Da Silva, [@markmarco16](https://github.com/markmarco16), markmarco16@gmail.com
- Daniel Gómez Pan [@pana1990](https://github.com/pana1990), pana_1990@hotmail.com
Ukrainian
---------
......
......@@ -4,17 +4,21 @@ Yii version numbering
Releases
--------
```
A.B.C
```
A = For Yii2 it's always 2.
B = Major version. Non-BC changes with upgrade instructions.
C = BC changes and additions.
- A = For Yii2 it's always 2.
- B = Major version. Non-BC changes with upgrade instructions.
- C = BC changes and additions.
Release candidates
------------------
```
A.B.C-rc
A.B.C-rc2
```
This is when we want to do a release candidate. RC number increments till we're getting a stable release with no
critical bugs and backwards incompatibility reports.
......@@ -22,14 +26,18 @@ critical bugs and backwards incompatibility reports.
Alphas and betas
----------------
```
A.B.C-alpha
A.B.C-alpha2
```
Alphas are unstable versions where significant bugs may and probably do exist. API isn't fixed yet and may be changed
significantly. `alpha2` etc. may or may not be released based on overall stability of code and API.
```
A.B.C-beta
A.B.C-beta2
```
Beta is more or less stable with less bugs and API instability than alphas. There still could be changes in API but
there should be a significant reason for it.
Yii Framework 2 apidoc extension Change Log
===========================================
2.0.0 under development
2.0.1 under development
-----------------------
- no changes in this release.
2.0.0 October 12, 2014
----------------------
- Chg: Updated cebe/markdown to 1.0.0 which includes breaking changes in its internal API (cebe)
2.0.0-rc September 27, 2014
---------------------------
......
......@@ -25,7 +25,7 @@
"phpdocumentor/reflection-docblock": ">2.0.1",
"nikic/php-parser": "0.9.*",
"cebe/js-search": "*",
"cebe/markdown": "dev-master as 0.9.0",
"cebe/markdown": "~1.0.0",
"cebe/markdown-latex": "*"
},
"autoload": {
......
......@@ -40,7 +40,7 @@ class ApiMarkdown extends GithubMarkdown
if (isset($block['language'])) {
$class = isset($block['language']) ? ' class="language-' . $block['language'] . '"' : '';
return "<pre><code$class>" . $this->highlight(implode("\n", $block['content']) . "\n", $block['language']) . '</code></pre>';
return "<pre><code$class>" . $this->highlight($block['content'] . "\n", $block['language']) . "</code></pre>\n";
} else {
return parent::renderCode($block);
}
......@@ -49,7 +49,7 @@ class ApiMarkdown extends GithubMarkdown
public static function highlight($code, $language)
{
if ($language !== 'php') {
return htmlspecialchars($code, ENT_NOQUOTES, 'UTF-8');
return htmlspecialchars($code, ENT_NOQUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
// TODO improve code highlighting
......@@ -68,39 +68,32 @@ class ApiMarkdown extends GithubMarkdown
return $text;
}
protected function inlineMarkers()
{
return array_merge(parent::inlineMarkers(), [
'[[' => 'parseApiLinks',
]);
}
/**
* @inheritDoc
*/
protected function renderHeadline($block)
{
$content = $this->parseInline($block['content']);
$content = $this->renderAbsy($block['content']);
$hash = Inflector::slug(strip_tags($content));
$hashLink = "<a href=\"#$hash\" name=\"$hash\" class=\"hashlink\">&para;</a>";
$tag = 'h' . $block['level'];
$tag = 'h' . $block['level'];
return "<$tag>$content $hashLink</$tag>";
}
/**
* @inheritdoc
*/
protected function parseLink($markdown)
protected function renderLink($block)
{
list($result, $skip) = parent::parseLink($markdown);
$result = parent::renderLink($block);
// add special syntax for linking to the guide
$result = preg_replace_callback('/href="guide:([A-z0-9-.#]+)"/i', function($match) {
return 'href="' . static::$renderer->generateGuideUrl($match[1]) . '"';
}, $result, 1);
return [$result, $skip];
return $result;
}
/**
......
......@@ -30,21 +30,11 @@ class ApiMarkdownLaTeX extends GithubMarkdown
protected $renderingContext;
protected function inlineMarkers()
protected function renderApiLink($block)
{
return array_merge(parent::inlineMarkers(), [
'[[' => 'parseApiLinksLatex',
]);
}
protected function parseApiLinksLatex($text)
{
list($html, $offset) = $this->parseApiLinks($text);
// TODO allow break also on camel case
$latex = '\texttt{'.str_replace(['\\textbackslash', '::'], ['\allowbreak{}\\textbackslash', '\allowbreak{}::\allowbreak{}'], $this->escapeLatex(strip_tags($html))).'}';
return [$latex, $offset];
$latex = '\texttt{'.str_replace(['\\textbackslash', '::'], ['\allowbreak{}\\textbackslash', '\allowbreak{}::\allowbreak{}'], $this->escapeLatex(strip_tags($block[1]))).'}';
return $latex;
}
/**
......
......@@ -18,6 +18,9 @@ use yii\apidoc\models\TypeDoc;
*/
trait ApiMarkdownTrait
{
/**
* @marker [[
*/
protected function parseApiLinks($text)
{
$context = $this->renderingContext;
......@@ -45,7 +48,7 @@ trait ApiMarkdownTrait
];
return [
'<span style="background: #f00;">' . $typeName . '::' . $subjectName . '</span>',
['text', '<span style="background: #f00;">' . $typeName . '::' . $subjectName . '</span>'],
$offset
];
} else {
......@@ -58,7 +61,7 @@ trait ApiMarkdownTrait
}
return [
static::$renderer->createSubjectLink($subject, $title),
['apiLink', static::$renderer->createSubjectLink($subject, $title)],
$offset
];
} else {
......@@ -68,14 +71,14 @@ trait ApiMarkdownTrait
];
return [
'<span style="background: #ff0;">' . $type->name . '</span><span style="background: #f00;">::' . $subjectName . '</span>',
['text', '<span style="background: #ff0;">' . $type->name . '</span><span style="background: #f00;">::' . $subjectName . '</span>'],
$offset
];
}
}
} elseif ($context !== null && ($subject = $context->findSubject($object)) !== null) {
return [
static::$renderer->createSubjectLink($subject, $title),
['apiLink', static::$renderer->createSubjectLink($subject, $title)],
$offset
];
}
......@@ -86,12 +89,12 @@ trait ApiMarkdownTrait
}
if (($type = static::$renderer->apiContext->getType($object)) !== null) {
return [
static::$renderer->createTypeLink($type, null, $title),
['apiLink', static::$renderer->createTypeLink($type, null, $title)],
$offset
];
} elseif (strpos($typeLink = static::$renderer->createTypeLink($object, null, $title), '<a href') !== false) {
return [
$typeLink,
['apiLink', $typeLink],
$offset
];
}
......@@ -101,11 +104,16 @@ trait ApiMarkdownTrait
];
return [
'<span style="background: #f00;">' . $object . '</span>',
['text', '<span style="background: #f00;">' . $object . '</span>'],
$offset
];
}
return ['[[', 2];
return [['text', '[['], 2];
}
protected function renderApiLink($block)
{
return $block[1];
}
}
......@@ -28,13 +28,13 @@ class IndexFileAnalyzer extends Markdown
protected function renderHeadline($block)
{
if ($this->_chapter === 0) {
$this->title = $block['content'];
$this->title = $this->renderAbsy($block['content']);
$this->introduction = '';
$this->_chapter++;
} else {
$this->_chapter++;
$this->_chapters[$this->_chapter] = [
'headline' => $block['content'],
'headline' => $this->renderAbsy($block['content']),
'content' => [],
];
}
......@@ -44,7 +44,7 @@ class IndexFileAnalyzer extends Markdown
protected function renderParagraph($block)
{
if ($this->_chapter < 1) {
$this->introduction .= implode("\n", $block['content']);
$this->introduction .= $this->renderAbsy($block['content']);
}
return parent::renderParagraph($block);
}
......@@ -52,13 +52,14 @@ class IndexFileAnalyzer extends Markdown
protected function renderList($block)
{
if ($this->_chapter > 0) {
foreach ($block['items'] as $item => $itemLines) {
if (preg_match('~\[([^\]]+)\]\(([^\)]+)\)(.*)~', implode("\n", $itemLines), $matches)) {
$this->_chapters[$this->_chapter]['content'][] = [
'headline' => $matches[1],
'file' => $matches[2],
'teaser' => $matches[3],
];
foreach ($block['items'] as $item => $absyElements) {
foreach($absyElements as $element) {
if ($element[0] === 'link') {
$this->_chapters[$this->_chapter]['content'][] = [
'headline' => $this->renderAbsy($element['text']),
'file' => $element['url'],
];
}
}
}
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment