Commit eaaf5f02 by Qiang Xue

replaced tabs with spaces in docs.

parent 994780d1
...@@ -125,45 +125,45 @@ directory: ...@@ -125,45 +125,45 @@ directory:
```json ```json
{ {
"name": "yiisoft/yii2-app-advanced", "name": "yiisoft/yii2-app-advanced",
"description": "Yii 2 Advanced Application Template", "description": "Yii 2 Advanced Application Template",
"keywords": ["yii", "framework", "advanced", "application template"], "keywords": ["yii", "framework", "advanced", "application template"],
"homepage": "http://www.yiiframework.com/", "homepage": "http://www.yiiframework.com/",
"type": "project", "type": "project",
"license": "BSD-3-Clause", "license": "BSD-3-Clause",
"support": { "support": {
"issues": "https://github.com/yiisoft/yii2/issues?state=open", "issues": "https://github.com/yiisoft/yii2/issues?state=open",
"forum": "http://www.yiiframework.com/forum/", "forum": "http://www.yiiframework.com/forum/",
"wiki": "http://www.yiiframework.com/wiki/", "wiki": "http://www.yiiframework.com/wiki/",
"irc": "irc://irc.freenode.net/yii", "irc": "irc://irc.freenode.net/yii",
"source": "https://github.com/yiisoft/yii2" "source": "https://github.com/yiisoft/yii2"
}, },
"minimum-stability": "dev", "minimum-stability": "dev",
"require": { "require": {
"php": ">=5.4.0", "php": ">=5.4.0",
"yiisoft/yii2": "*", "yiisoft/yii2": "*",
"yiisoft/yii2-swiftmailer": "*", "yiisoft/yii2-swiftmailer": "*",
"yiisoft/yii2-bootstrap": "*", "yiisoft/yii2-bootstrap": "*",
"yiisoft/yii2-debug": "*", "yiisoft/yii2-debug": "*",
"yiisoft/yii2-gii": "*" "yiisoft/yii2-gii": "*"
}, },
"scripts": { "scripts": {
"post-create-project-cmd": [ "post-create-project-cmd": [
"yii\\composer\\Installer::setPermission" "yii\\composer\\Installer::setPermission"
] ]
}, },
"extra": { "extra": {
"writable": [ "writable": [
"backend/runtime", "backend/runtime",
"backend/web/assets", "backend/web/assets",
"console/runtime", "console/runtime",
"console/migrations", "console/migrations",
"frontend/runtime", "frontend/runtime",
"frontend/web/assets" "frontend/web/assets"
] ]
} }
} }
``` ```
...@@ -184,15 +184,15 @@ contain its own URL manager rules you need to duplicate that for backend applica ...@@ -184,15 +184,15 @@ contain its own URL manager rules you need to duplicate that for backend applica
```php ```php
return [ return [
'components' => [ 'components' => [
'urlManager' => [ 'urlManager' => [
// here is your normal backend url manager config // here is your normal backend url manager config
], ],
'urlManagerFrontend' => [ 'urlManagerFrontend' => [
// here is your frontend URL manager config // here is your frontend URL manager config
], ],
], ],
]; ];
``` ```
......
...@@ -72,13 +72,13 @@ Views directory contains templates your application is using. In the basic templ ...@@ -72,13 +72,13 @@ Views directory contains templates your application is using. In the basic templ
``` ```
layouts layouts
main.php main.php
site site
about.php about.php
contact.php contact.php
error.php error.php
index.php index.php
login.php login.php
``` ```
`layouts` contains HTML layouts i.e. page markup except content: doctype, head section, main menu, footer etc. `layouts` contains HTML layouts i.e. page markup except content: doctype, head section, main menu, footer etc.
...@@ -113,42 +113,42 @@ directory: ...@@ -113,42 +113,42 @@ directory:
```json ```json
{ {
"name": "yiisoft/yii2-app-basic", "name": "yiisoft/yii2-app-basic",
"description": "Yii 2 Basic Application Template", "description": "Yii 2 Basic Application Template",
"keywords": ["yii", "framework", "basic", "application template"], "keywords": ["yii", "framework", "basic", "application template"],
"homepage": "http://www.yiiframework.com/", "homepage": "http://www.yiiframework.com/",
"type": "project", "type": "project",
"license": "BSD-3-Clause", "license": "BSD-3-Clause",
"support": { "support": {
"issues": "https://github.com/yiisoft/yii2/issues?state=open", "issues": "https://github.com/yiisoft/yii2/issues?state=open",
"forum": "http://www.yiiframework.com/forum/", "forum": "http://www.yiiframework.com/forum/",
"wiki": "http://www.yiiframework.com/wiki/", "wiki": "http://www.yiiframework.com/wiki/",
"irc": "irc://irc.freenode.net/yii", "irc": "irc://irc.freenode.net/yii",
"source": "https://github.com/yiisoft/yii2" "source": "https://github.com/yiisoft/yii2"
}, },
"minimum-stability": "dev", "minimum-stability": "dev",
"require": { "require": {
"php": ">=5.4.0", "php": ">=5.4.0",
"yiisoft/yii2": "*", "yiisoft/yii2": "*",
"yiisoft/yii2-swiftmailer": "*", "yiisoft/yii2-swiftmailer": "*",
"yiisoft/yii2-bootstrap": "*", "yiisoft/yii2-bootstrap": "*",
"yiisoft/yii2-debug": "*", "yiisoft/yii2-debug": "*",
"yiisoft/yii2-gii": "*" "yiisoft/yii2-gii": "*"
}, },
"scripts": { "scripts": {
"post-create-project-cmd": [ "post-create-project-cmd": [
"yii\\composer\\Installer::setPermission" "yii\\composer\\Installer::setPermission"
] ]
}, },
"extra": { "extra": {
"writable": [ "writable": [
"runtime", "runtime",
"web/assets" "web/assets"
], ],
"executable": [ "executable": [
"yii" "yii"
] ]
} }
} }
``` ```
......
...@@ -29,17 +29,17 @@ use yii\web\AssetBundle as AssetBundle; ...@@ -29,17 +29,17 @@ use yii\web\AssetBundle as AssetBundle;
class AppAsset extends AssetBundle class AppAsset extends AssetBundle
{ {
public $basePath = '@webroot'; public $basePath = '@webroot';
public $baseUrl = '@web'; public $baseUrl = '@web';
public $css = [ public $css = [
'css/site.css', 'css/site.css',
]; ];
public $js = [ public $js = [
]; ];
public $depends = [ public $depends = [
'yii\web\YiiAsset', 'yii\web\YiiAsset',
'yii\bootstrap\BootstrapAsset', 'yii\bootstrap\BootstrapAsset',
]; ];
} }
``` ```
...@@ -81,17 +81,17 @@ following way: ...@@ -81,17 +81,17 @@ following way:
```php ```php
class LanguageAsset extends AssetBundle class LanguageAsset extends AssetBundle
{ {
public $language; public $language;
public $sourcePath = '@app/assets/language'; public $sourcePath = '@app/assets/language';
public $js = [ public $js = [
]; ];
public function registerAssetFiles($view) public function registerAssetFiles($view)
{ {
$language = $this->language ? $this->language : Yii::$app->language; $language = $this->language ? $this->language : Yii::$app->language;
$this->js[] = 'language-' . $language . '.js'; $this->js[] = 'language-' . $language . '.js';
parent::registerAssetFiles($view); parent::registerAssetFiles($view);
} }
} }
``` ```
...@@ -205,25 +205,25 @@ The template itself looks like the following: ...@@ -205,25 +205,25 @@ The template itself looks like the following:
* Please define these missing path aliases. * Please define these missing path aliases.
*/ */
return [ return [
// The list of asset bundles to compress: // The list of asset bundles to compress:
'bundles' => [ 'bundles' => [
// 'yii\web\YiiAsset', // 'yii\web\YiiAsset',
// 'yii\web\JqueryAsset', // 'yii\web\JqueryAsset',
], ],
// Asset bundle for compression output: // Asset bundle for compression output:
'targets' => [ 'targets' => [
'app\config\AllAsset' => [ 'app\config\AllAsset' => [
'basePath' => 'path/to/web', 'basePath' => 'path/to/web',
'baseUrl' => '', 'baseUrl' => '',
'js' => 'js/all-{ts}.js', 'js' => 'js/all-{ts}.js',
'css' => 'css/all-{ts}.css', 'css' => 'css/all-{ts}.css',
], ],
], ],
// Asset manager configuration: // Asset manager configuration:
'assetManager' => [ 'assetManager' => [
'basePath' => __DIR__, 'basePath' => __DIR__,
'baseUrl' => '', 'baseUrl' => '',
], ],
]; ];
``` ```
...@@ -260,8 +260,8 @@ like the following, ...@@ -260,8 +260,8 @@ like the following,
```php ```php
return [ return [
'cssCompressor' => 'java -jar path.to.file\yuicompressor.jar --type css {from} -o {to}', 'cssCompressor' => 'java -jar path.to.file\yuicompressor.jar --type css {from} -o {to}',
'jsCompressor' => 'java -jar path.to.file\compiler.jar --js {from} --js_output_file {to}', 'jsCompressor' => 'java -jar path.to.file\compiler.jar --js {from} --js_output_file {to}',
]; ];
``` ```
...@@ -282,10 +282,10 @@ assets file like the following: ...@@ -282,10 +282,10 @@ assets file like the following:
```php ```php
'components' => [ 'components' => [
// ... // ...
'assetManager' => [ 'assetManager' => [
'bundles' => require '/path/to/myapp/config/assets_compressed.php', 'bundles' => require '/path/to/myapp/config/assets_compressed.php',
], ],
], ],
``` ```
...@@ -310,18 +310,18 @@ So if the corresponding tool is installed you can specify any of these in asset ...@@ -310,18 +310,18 @@ So if the corresponding tool is installed you can specify any of these in asset
```php ```php
class AppAsset extends AssetBundle class AppAsset extends AssetBundle
{ {
public $basePath = '@webroot'; public $basePath = '@webroot';
public $baseUrl = '@web'; public $baseUrl = '@web';
public $css = [ public $css = [
'css/site.less', 'css/site.less',
]; ];
public $js = [ public $js = [
'js/site.ts', 'js/site.ts',
]; ];
public $depends = [ public $depends = [
'yii\web\YiiAsset', 'yii\web\YiiAsset',
'yii\bootstrap\BootstrapAsset', 'yii\bootstrap\BootstrapAsset',
]; ];
} }
``` ```
...@@ -330,15 +330,15 @@ In order to adjust conversion tool call parameters or add new ones you can use a ...@@ -330,15 +330,15 @@ In order to adjust conversion tool call parameters or add new ones you can use a
```php ```php
// ... // ...
'components' => [ 'components' => [
'assetManager' => [ 'assetManager' => [
'converter' => [ 'converter' => [
'class' => 'yii\web\AssetConverter', 'class' => 'yii\web\AssetConverter',
'commands' => [ 'commands' => [
'less' => ['css', 'lessc {from} {to} --no-color'], 'less' => ['css', 'lessc {from} {to} --no-color'],
'ts' => ['js', 'tsc --out {to} {from}'], 'ts' => ['js', 'tsc --out {to} {from}'],
], ],
], ],
], ],
], ],
``` ```
......
...@@ -11,54 +11,54 @@ You can find a fully featured example of authentication in the ...@@ -11,54 +11,54 @@ You can find a fully featured example of authentication in the
```php ```php
class User extends ActiveRecord implements IdentityInterface class User extends ActiveRecord implements IdentityInterface
{ {
// ... // ...
/** /**
* Finds an identity by the given ID. * Finds an identity by the given ID.
* *
* @param string|integer $id the ID to be looked for * @param string|integer $id the ID to be looked for
* @return IdentityInterface|null the identity object that matches the given ID. * @return IdentityInterface|null the identity object that matches the given ID.
*/ */
public static function findIdentity($id) public static function findIdentity($id)
{ {
return static::find($id); return static::find($id);
} }
/** /**
* Finds an identity by the given token. * Finds an identity by the given token.
* *
* @param string $token the token to be looked for * @param string $token the token to be looked for
* @return IdentityInterface|null the identity object that matches the given token. * @return IdentityInterface|null the identity object that matches the given token.
*/ */
public static function findIdentityByAccessToken($token) public static function findIdentityByAccessToken($token)
{ {
return static::find(['access_token' => $token]); return static::find(['access_token' => $token]);
} }
/** /**
* @return int|string current user ID * @return int|string current user ID
*/ */
public function getId() public function getId()
{ {
return $this->id; return $this->id;
} }
/** /**
* @return string current user auth key * @return string current user auth key
*/ */
public function getAuthKey() public function getAuthKey()
{ {
return $this->auth_key; return $this->auth_key;
} }
/** /**
* @param string $authKey * @param string $authKey
* @return boolean if auth key is valid for current user * @return boolean if auth key is valid for current user
*/ */
public function validateAuthKey($authKey) public function validateAuthKey($authKey)
{ {
return $this->getAuthKey() === $authKey; return $this->getAuthKey() === $authKey;
} }
} }
``` ```
...@@ -68,13 +68,13 @@ Two of the other methods--`getAuthKey` and `validateAuthKey`--are used to provid ...@@ -68,13 +68,13 @@ Two of the other methods--`getAuthKey` and `validateAuthKey`--are used to provid
```php ```php
public function beforeSave($insert) public function beforeSave($insert)
{ {
if (parent::beforeSave($insert)) { if (parent::beforeSave($insert)) {
if ($this->isNewRecord) { if ($this->isNewRecord) {
$this->auth_key = Security::generateRandomKey(); $this->auth_key = Security::generateRandomKey();
} }
return true; return true;
} }
return false; return false;
} }
``` ```
......
...@@ -12,28 +12,28 @@ Basic access control is very simple to implement using [[yii\web\AccessControl]] ...@@ -12,28 +12,28 @@ Basic access control is very simple to implement using [[yii\web\AccessControl]]
```php ```php
class SiteController extends Controller class SiteController extends Controller
{ {
public function behaviors() public function behaviors()
{ {
return [ return [
'access' => [ 'access' => [
'class' => \yii\web\AccessControl::className(), 'class' => \yii\web\AccessControl::className(),
'only' => ['login', 'logout', 'signup'], 'only' => ['login', 'logout', 'signup'],
'rules' => [ 'rules' => [
[ [
'actions' => ['login', 'signup'], 'actions' => ['login', 'signup'],
'allow' => true, 'allow' => true,
'roles' => ['?'], 'roles' => ['?'],
], ],
[ [
'actions' => ['logout'], 'actions' => ['logout'],
'allow' => true, 'allow' => true,
'roles' => ['@'], 'roles' => ['@'],
], ],
], ],
], ],
]; ];
} }
// ... // ...
``` ```
In the code above we're attaching access control behavior to a controller. Since there's `only` option specified, it In the code above we're attaching access control behavior to a controller. Since there's `only` option specified, it
...@@ -52,31 +52,31 @@ checked. If no rules matched access is denied. ...@@ -52,31 +52,31 @@ checked. If no rules matched access is denied.
```php ```php
class SiteController extends Controller class SiteController extends Controller
{ {
public function behaviors() public function behaviors()
{ {
return [ return [
'access' => [ 'access' => [
'class' => \yii\web\AccessControl::className(), 'class' => \yii\web\AccessControl::className(),
'only' => ['special-callback'], 'only' => ['special-callback'],
'rules' => [ 'rules' => [
[ [
'actions' => ['special-callback'], 'actions' => ['special-callback'],
'allow' => true, 'allow' => true,
'matchCallback' => function ($rule, $action) { 'matchCallback' => function ($rule, $action) {
return date('d-m') === '31-10'; return date('d-m') === '31-10';
} }
], ],
``` ```
And the action: And the action:
```php ```php
// ... // ...
// Match callback called! This page can be accessed only each October 31st // Match callback called! This page can be accessed only each October 31st
public function actionSpecialCallback() public function actionSpecialCallback()
{ {
return $this->render('happy-halloween'); return $this->render('happy-halloween');
} }
``` ```
Sometimes you want a custom action to be taken when access is denied. In this case you can specify `denyCallback`. Sometimes you want a custom action to be taken when access is denied. In this case you can specify `denyCallback`.
......
...@@ -23,20 +23,20 @@ use yii\behaviors\TimestampBehavior; ...@@ -23,20 +23,20 @@ use yii\behaviors\TimestampBehavior;
class User extends ActiveRecord class User extends ActiveRecord
{ {
// ... // ...
public function behaviors() public function behaviors()
{ {
return [ return [
'timestamp' => [ 'timestamp' => [
'class' => TimestampBehavior::className(), 'class' => TimestampBehavior::className(),
'attributes' => [ 'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'], ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
ActiveRecord::EVENT_BEFORE_UPDATE => 'updated_at', ActiveRecord::EVENT_BEFORE_UPDATE => 'updated_at',
], ],
], ],
]; ];
} }
} }
``` ```
...@@ -60,16 +60,16 @@ use yii\behaviors\TimestampBehavior; ...@@ -60,16 +60,16 @@ use yii\behaviors\TimestampBehavior;
class User extends ActiveRecord class User extends ActiveRecord
{ {
// ... // ...
public function behaviors() public function behaviors()
{ {
return [ return [
TimestampBehavior::className(), TimestampBehavior::className(),
// or the following if you want to access the behavior object // or the following if you want to access the behavior object
// 'timestamp' => TimestampBehavior::className(), // 'timestamp' => TimestampBehavior::className(),
]; ];
} }
} }
``` ```
...@@ -89,16 +89,16 @@ following: ...@@ -89,16 +89,16 @@ following:
```php ```php
return [ return [
// ... // ...
'components' => [ 'components' => [
'myComponent' => [ 'myComponent' => [
// ... // ...
'as tree' => [ 'as tree' => [
'class' => 'Tree', 'class' => 'Tree',
'root' => 0, 'root' => 0,
], ],
], ],
], ],
]; ];
``` ```
...@@ -130,7 +130,7 @@ use yii\base\Behavior; ...@@ -130,7 +130,7 @@ use yii\base\Behavior;
class MyBehavior extends Behavior class MyBehavior extends Behavior
{ {
public $attr; public $attr;
} }
``` ```
...@@ -143,17 +143,17 @@ use yii\db\ActiveRecord; ...@@ -143,17 +143,17 @@ use yii\db\ActiveRecord;
class User extends ActiveRecord class User extends ActiveRecord
{ {
// ... // ...
public function behaviors() public function behaviors()
{ {
return [ return [
'mybehavior' => [ 'mybehavior' => [
'class' => 'app\components\MyBehavior', 'class' => 'app\components\MyBehavior',
'attr' => 'member_type' 'attr' => 'member_type'
], ],
]; ];
} }
} }
``` ```
...@@ -168,24 +168,24 @@ use yii\db\ActiveRecord; ...@@ -168,24 +168,24 @@ use yii\db\ActiveRecord;
class MyBehavior extends Behavior class MyBehavior extends Behavior
{ {
public $attr; public $attr;
public function events() public function events()
{ {
return [ return [
ActiveRecord::EVENT_BEFORE_INSERT => 'beforeInsert', ActiveRecord::EVENT_BEFORE_INSERT => 'beforeInsert',
ActiveRecord::EVENT_BEFORE_UPDATE => 'beforeUpdate', ActiveRecord::EVENT_BEFORE_UPDATE => 'beforeUpdate',
]; ];
} }
public function beforeInsert() { public function beforeInsert() {
$model = $this->owner; $model = $this->owner;
// Use $model->$attr // Use $model->$attr
} }
public function beforeUpdate() { public function beforeUpdate() {
$model = $this->owner; $model = $this->owner;
// Use $model->$attr // Use $model->$attr
} }
} }
``` ```
...@@ -18,9 +18,9 @@ convenient way to include bootstrap assets in your pages with a single line adde ...@@ -18,9 +18,9 @@ convenient way to include bootstrap assets in your pages with a single line adde
```php ```php
public $depends = [ public $depends = [
'yii\web\YiiAsset', 'yii\web\YiiAsset',
'yii\bootstrap\BootstrapAsset', // this line 'yii\bootstrap\BootstrapAsset', // this line
// 'yii\bootstrap\BootstrapThemeAsset' // uncomment to apply bootstrap 2 style to bootstrap 3 // 'yii\bootstrap\BootstrapThemeAsset' // uncomment to apply bootstrap 2 style to bootstrap 3
]; ];
``` ```
......
...@@ -15,21 +15,21 @@ in case you're using basic sample application. ...@@ -15,21 +15,21 @@ in case you're using basic sample application.
```php ```php
'components' => [ 'components' => [
'cache' => [ 'cache' => [
'class' => '\yii\caching\MemCache', 'class' => '\yii\caching\MemCache',
'servers' => [ 'servers' => [
[ [
'host' => 'server1', 'host' => 'server1',
'port' => 11211, 'port' => 11211,
'weight' => 100, 'weight' => 100,
], ],
[ [
'host' => 'server2', 'host' => 'server2',
'port' => 11211, 'port' => 11211,
'weight' => 50, 'weight' => 50,
], ],
], ],
], ],
], ],
``` ```
...@@ -117,13 +117,13 @@ in cache and we should regenerate it: ...@@ -117,13 +117,13 @@ in cache and we should regenerate it:
```php ```php
public function getCachedData() public function getCachedData()
{ {
$key = /* generate unique key here */; $key = /* generate unique key here */;
$value = Yii::$app->cache->get($key); $value = Yii::$app->cache->get($key);
if ($value === false) { if ($value === false) {
$value = /* regenerate value because it is not found in cache and then save it in cache for later use */; $value = /* regenerate value because it is not found in cache and then save it in cache for later use */;
Yii::$app->cache->set($key, $value); Yii::$app->cache->set($key, $value);
} }
return $value; return $value;
} }
``` ```
......
...@@ -43,12 +43,12 @@ stored in a PHP file stored in the `/config` application directory. The file has ...@@ -43,12 +43,12 @@ stored in a PHP file stored in the `/config` application directory. The file has
```php ```php
<?php <?php
return [ return [
'id' => 'applicationId', 'id' => 'applicationId',
'basePath' => dirname(__DIR__), 'basePath' => dirname(__DIR__),
'components' => [ 'components' => [
// configuration of application components goes here... // configuration of application components goes here...
], ],
'params' => require(__DIR__ . '/params.php'), 'params' => require(__DIR__ . '/params.php'),
]; ];
``` ```
...@@ -68,23 +68,23 @@ The majority of the Yii functionality comes from application components. These c ...@@ -68,23 +68,23 @@ The majority of the Yii functionality comes from application components. These c
```php ```php
<?php <?php
return [ return [
'id' => 'applicationId', 'id' => 'applicationId',
'basePath' => dirname(__DIR__), 'basePath' => dirname(__DIR__),
'components' => [ 'components' => [
'cache' => ['class' => 'yii\caching\FileCache'], 'cache' => ['class' => 'yii\caching\FileCache'],
'user' => ['identityClass' => 'app\models\User'], 'user' => ['identityClass' => 'app\models\User'],
'errorHandler' => ['errorAction' => 'site/error'], 'errorHandler' => ['errorAction' => 'site/error'],
'log' => [ 'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0, 'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [ 'targets' => [
[ [
'class' => 'yii\log\FileTarget', 'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'], 'levels' => ['error', 'warning'],
], ],
], ],
], ],
], ],
// ... // ...
]; ];
``` ```
......
...@@ -22,20 +22,20 @@ Lets assume we have fixtures data to load: ...@@ -22,20 +22,20 @@ Lets assume we have fixtures data to load:
#users.php file under fixtures data path, by default @tests\unit\fixtures\data #users.php file under fixtures data path, by default @tests\unit\fixtures\data
return [ return [
[ [
'name' => 'Chase', 'name' => 'Chase',
'login' => 'lmayert', 'login' => 'lmayert',
'email' => 'strosin.vernice@jerde.com', 'email' => 'strosin.vernice@jerde.com',
'auth_key' => 'K3nF70it7tzNsHddEiq0BZ0i-OU8S3xV', 'auth_key' => 'K3nF70it7tzNsHddEiq0BZ0i-OU8S3xV',
'password' => '$2y$13$WSyE5hHsG1rWN2jV8LRHzubilrCLI5Ev/iK0r3jRuwQEs2ldRu.a2', 'password' => '$2y$13$WSyE5hHsG1rWN2jV8LRHzubilrCLI5Ev/iK0r3jRuwQEs2ldRu.a2',
], ],
[ [
'name' => 'Celestine', 'name' => 'Celestine',
'login' => 'napoleon69', 'login' => 'napoleon69',
'email' => 'aileen.barton@heaneyschumm.com', 'email' => 'aileen.barton@heaneyschumm.com',
'auth_key' => 'dZlXsVnIDgIzFgX4EduAqkEPuphhOh9q', 'auth_key' => 'dZlXsVnIDgIzFgX4EduAqkEPuphhOh9q',
'password' => '$2y$13$kkgpvJ8lnjKo8RuoR30ay.RjDf15bMcHIF7Vz1zz/6viYG5xJExU6', 'password' => '$2y$13$kkgpvJ8lnjKo8RuoR30ay.RjDf15bMcHIF7Vz1zz/6viYG5xJExU6',
], ],
]; ];
``` ```
If we are using fixture that loads data into database then these rows will be applied to `users` table. If we are using nosql fixtures, for example `mongodb` If we are using fixture that loads data into database then these rows will be applied to `users` table. If we are using nosql fixtures, for example `mongodb`
...@@ -114,12 +114,12 @@ different migration path as follows: ...@@ -114,12 +114,12 @@ different migration path as follows:
'controllerMap' => [ 'controllerMap' => [
'fixture' => [ 'fixture' => [
'class' => 'yii\console\controllers\FixtureController', 'class' => 'yii\console\controllers\FixtureController',
'db' => 'customDbConnectionId', 'db' => 'customDbConnectionId',
'namespace' => 'myalias\some\custom\namespace', 'namespace' => 'myalias\some\custom\namespace',
'globalFixtures' => [ 'globalFixtures' => [
'some\name\space\Foo', 'some\name\space\Foo',
'other\name\space\Bar' 'other\name\space\Bar'
], ],
], ],
] ]
``` ```
......
...@@ -42,15 +42,15 @@ file named `m101129_185401_create_news_table.php`. This file will be created wit ...@@ -42,15 +42,15 @@ file named `m101129_185401_create_news_table.php`. This file will be created wit
```php ```php
class m101129_185401_create_news_table extends \yii\db\Migration class m101129_185401_create_news_table extends \yii\db\Migration
{ {
public function up() public function up()
{ {
} }
public function down() public function down()
{ {
echo "m101129_185401_create_news_table cannot be reverted.\n"; echo "m101129_185401_create_news_table cannot be reverted.\n";
return false; return false;
} }
} }
``` ```
...@@ -78,19 +78,19 @@ use yii\db\Schema; ...@@ -78,19 +78,19 @@ use yii\db\Schema;
class m101129_185401_create_news_table extends \yii\db\Migration class m101129_185401_create_news_table extends \yii\db\Migration
{ {
public function up() public function up()
{ {
$this->createTable('tbl_news', [ $this->createTable('tbl_news', [
'id' => 'pk', 'id' => 'pk',
'title' => Schema::TYPE_STRING . ' NOT NULL', 'title' => Schema::TYPE_STRING . ' NOT NULL',
'content' => Schema::TYPE_TEXT, 'content' => Schema::TYPE_TEXT,
]); ]);
} }
public function down() public function down()
{ {
$this->dropTable('tbl_news'); $this->dropTable('tbl_news');
} }
} }
``` ```
...@@ -122,26 +122,26 @@ use yii\db\Schema; ...@@ -122,26 +122,26 @@ use yii\db\Schema;
class m101129_185401_create_news_table extends \yii\db\Migration class m101129_185401_create_news_table extends \yii\db\Migration
{ {
public function safeUp() public function safeUp()
{ {
$this->createTable('tbl_news', [ $this->createTable('tbl_news', [
'id' => 'pk', 'id' => 'pk',
'title' => Schema::TYPE_STRING . ' NOT NULL', 'title' => Schema::TYPE_STRING . ' NOT NULL',
'content' => Schema::TYPE_TEXT, 'content' => Schema::TYPE_TEXT,
]); ]);
$this->createTable('tbl_user', [ $this->createTable('tbl_user', [
'id' => 'pk', 'id' => 'pk',
'login' => Schema::TYPE_STRING . ' NOT NULL', 'login' => Schema::TYPE_STRING . ' NOT NULL',
'password' => Schema::TYPE_STRING . ' NOT NULL', 'password' => Schema::TYPE_STRING . ' NOT NULL',
]); ]);
} }
public function safeDown() public function safeDown()
{ {
$this->dropTable('tbl_news'); $this->dropTable('tbl_news');
$this->dropTable('tbl_user'); $this->dropTable('tbl_user');
} }
} }
``` ```
......
...@@ -120,16 +120,16 @@ The follow examples show how to declare arguments: ...@@ -120,16 +120,16 @@ The follow examples show how to declare arguments:
```php ```php
class ExampleController extends \yii\console\Controller class ExampleController extends \yii\console\Controller
{ {
// The command "yii example/create test" will call "actionCreate('test')" // The command "yii example/create test" will call "actionCreate('test')"
public function actionCreate($name) { ... } public function actionCreate($name) { ... }
// The command "yii example/index city" will call "actionIndex('city', 'name')" // The command "yii example/index city" will call "actionIndex('city', 'name')"
// The command "yii example/index city id" will call "actionIndex('city', 'id')" // The command "yii example/index city id" will call "actionIndex('city', 'id')"
public function actionIndex($category, $order = 'name') { ... } public function actionIndex($category, $order = 'name') { ... }
// The command "yii example/add test" will call "actionAdd(['test'])" // The command "yii example/add test" will call "actionAdd(['test'])"
// The command "yii example/add test1,test2" will call "actionAdd(['test1', 'test2'])" // The command "yii example/add test1,test2" will call "actionAdd(['test1', 'test2'])"
public function actionAdd(array $name) { ... } public function actionAdd(array $name) { ... }
} }
``` ```
...@@ -148,11 +148,11 @@ method: ...@@ -148,11 +148,11 @@ method:
```php ```php
public function actionIndex() public function actionIndex()
{ {
if (/* some problem */) { if (/* some problem */) {
echo "A problem occured!\n"; echo "A problem occured!\n";
return 1; return 1;
} }
// do something // do something
return 0; return 0;
} }
``` ```
...@@ -20,17 +20,17 @@ use yii\web\Controller; ...@@ -20,17 +20,17 @@ use yii\web\Controller;
class SiteController extends Controller class SiteController extends Controller
{ {
public function actionIndex() public function actionIndex()
{ {
// will render view from "views/site/index.php" // will render view from "views/site/index.php"
return $this->render('index'); return $this->render('index');
} }
public function actionTest() public function actionTest()
{ {
// will just print "test" to the browser // will just print "test" to the browser
return 'test'; return 'test';
} }
} }
``` ```
...@@ -49,12 +49,12 @@ use yii\web\Controller; ...@@ -49,12 +49,12 @@ use yii\web\Controller;
class SiteController extends Controller class SiteController extends Controller
{ {
public $enableCsrfValidation = false; public $enableCsrfValidation = false;
public function actionIndex() public function actionIndex()
{ {
// CSRF validation will not be applied to this and other actions // CSRF validation will not be applied to this and other actions
} }
} }
``` ```
...@@ -68,12 +68,12 @@ use yii\web\Controller; ...@@ -68,12 +68,12 @@ use yii\web\Controller;
class SiteController extends Controller class SiteController extends Controller
{ {
public function beforeAction($action) public function beforeAction($action)
{ {
// ...set `$this->enableCsrfValidation` here based on some conditions... // ...set `$this->enableCsrfValidation` here based on some conditions...
// call parent method that will check CSRF if such property is true. // call parent method that will check CSRF if such property is true.
return parent::beforeAction($action); return parent::beforeAction($action);
} }
} }
``` ```
...@@ -125,20 +125,20 @@ use yii\web\Controller; ...@@ -125,20 +125,20 @@ use yii\web\Controller;
class BlogController extends Controller class BlogController extends Controller
{ {
public function actionView($id, $version = null) public function actionView($id, $version = null)
{ {
$post = Post::find($id); $post = Post::find($id);
$text = $post->text; $text = $post->text;
if ($version) { if ($version) {
$text = $post->getHistory($version); $text = $post->getHistory($version);
} }
return $this->render('view', [ return $this->render('view', [
'post' => $post, 'post' => $post,
'text' => $text, 'text' => $text,
]); ]);
} }
} }
``` ```
...@@ -159,22 +159,22 @@ use yii\web\HttpException; ...@@ -159,22 +159,22 @@ use yii\web\HttpException;
class BlogController extends Controller class BlogController extends Controller
{ {
public function actionUpdate($id) public function actionUpdate($id)
{ {
$post = Post::find($id); $post = Post::find($id);
if (!$post) { if (!$post) {
throw new NotFoundHttpException(); throw new NotFoundHttpException();
} }
if (\Yii::$app->request->isPost) { if (\Yii::$app->request->isPost) {
$post->load(Yii::$app->request->post()); $post->load(Yii::$app->request->post());
if ($post->save()) { if ($post->save()) {
return $this->redirect(['view', 'id' => $post->id]); return $this->redirect(['view', 'id' => $post->id]);
} }
} }
return $this->render('update', ['post' => $post]); return $this->render('update', ['post' => $post]);
} }
} }
``` ```
...@@ -189,12 +189,12 @@ namespace app\actions; ...@@ -189,12 +189,12 @@ namespace app\actions;
class Page extends \yii\base\Action class Page extends \yii\base\Action
{ {
public $view = 'index'; public $view = 'index';
public function run() public function run()
{ {
return $this->controller->render($view); return $this->controller->render($view);
} }
} }
``` ```
...@@ -204,15 +204,15 @@ can be used in your controller as following: ...@@ -204,15 +204,15 @@ can be used in your controller as following:
```php ```php
class SiteController extends \yii\web\Controller class SiteController extends \yii\web\Controller
{ {
public function actions() public function actions()
{ {
return [ return [
'about' => [ 'about' => [
'class' => 'app\actions\Page', 'class' => 'app\actions\Page',
'view' => 'about', 'view' => 'about',
], ],
]; ];
} }
} }
``` ```
...@@ -253,14 +253,14 @@ dynamically or via application config: ...@@ -253,14 +253,14 @@ dynamically or via application config:
```php ```php
$config = [ $config = [
'id' => 'basic', 'id' => 'basic',
'basePath' => dirname(__DIR__), 'basePath' => dirname(__DIR__),
// ... // ...
'catchAll' => [ // <-- here 'catchAll' => [ // <-- here
'offline/notice', 'offline/notice',
'param1' => 'value1', 'param1' => 'value1',
'param2' => 'value2', 'param2' => 'value2',
], ],
``` ```
In the above `offline/notice` refer to `OfflineController::actionNotice()`. `param1` and `param2` are parameters passed In the above `offline/notice` refer to `OfflineController::actionNotice()`. `param1` and `param2` are parameters passed
...@@ -277,15 +277,15 @@ use app\components\web\MyCustomResponse; #extended from yii\web\Response ...@@ -277,15 +277,15 @@ use app\components\web\MyCustomResponse; #extended from yii\web\Response
class SiteController extends Controller class SiteController extends Controller
{ {
public function actionCustom() public function actionCustom()
{ {
/* /*
* do your things here * do your things here
* since Response in extended from yii\base\Object, you can initialize its values by passing in * since Response in extended from yii\base\Object, you can initialize its values by passing in
* __constructor() simple array. * __constructor() simple array.
*/ */
return new MyCustomResponse(['data' => $myCustomData]); return new MyCustomResponse(['data' => $myCustomData]);
} }
} }
``` ```
......
...@@ -19,13 +19,13 @@ use yii\data\GridView; ...@@ -19,13 +19,13 @@ use yii\data\GridView;
use yii\data\ActiveDataProvider; use yii\data\ActiveDataProvider;
$dataProvider = new ActiveDataProvider([ $dataProvider = new ActiveDataProvider([
'query' => Post::find(), 'query' => Post::find(),
'pagination' => [ 'pagination' => [
'pageSize' => 20, 'pageSize' => 20,
], ],
]); ]);
echo GridView::widget([ echo GridView::widget([
'dataProvider' => $dataProvider, 'dataProvider' => $dataProvider,
]); ]);
``` ```
...@@ -41,21 +41,21 @@ These are defined in the columns part of GridView config like the following: ...@@ -41,21 +41,21 @@ These are defined in the columns part of GridView config like the following:
```php ```php
echo GridView::widget([ echo GridView::widget([
'dataProvider' => $dataProvider, 'dataProvider' => $dataProvider,
'columns' => [ 'columns' => [
['class' => 'yii\grid\SerialColumn'], ['class' => 'yii\grid\SerialColumn'],
// A simple column defined by the data contained in $dataProvider. // A simple column defined by the data contained in $dataProvider.
// Data from model's column1 will be used. // Data from model's column1 will be used.
'id', 'id',
'username', 'username',
// More complex one. // More complex one.
[ [
'class' => 'yii\grid\DataColumn', // can be omitted, default 'class' => 'yii\grid\DataColumn', // can be omitted, default
'value' => function ($data) { 'value' => function ($data) {
return $data->name; return $data->name;
}, },
], ],
], ],
]); ]);
``` ```
...@@ -67,12 +67,12 @@ Grid columns could be customized by using different column classes: ...@@ -67,12 +67,12 @@ Grid columns could be customized by using different column classes:
```php ```php
echo GridView::widget([ echo GridView::widget([
'dataProvider' => $dataProvider, 'dataProvider' => $dataProvider,
'columns' => [ 'columns' => [
[ [
'class' => 'yii\grid\SerialColumn', // <-- here 'class' => 'yii\grid\SerialColumn', // <-- here
// you may configure additional properties here // you may configure additional properties here
], ],
``` ```
Additionally to column classes provided by Yii that we'll review below you can create your own column classes. Additionally to column classes provided by Yii that we'll review below you can create your own column classes.
...@@ -87,7 +87,7 @@ grid columns. ...@@ -87,7 +87,7 @@ grid columns.
```php ```php
function ($model, $key, $index, $grid) { function ($model, $key, $index, $grid) {
return 'a string'; return 'a string';
} }
``` ```
...@@ -111,12 +111,12 @@ Action column displays action buttons such as update or delete for each row. ...@@ -111,12 +111,12 @@ Action column displays action buttons such as update or delete for each row.
```php ```php
echo GridView::widget([ echo GridView::widget([
'dataProvider' => $dataProvider, 'dataProvider' => $dataProvider,
'columns' => [ 'columns' => [
[ [
'class' => 'yii\grid\ActionColumn', 'class' => 'yii\grid\ActionColumn',
// you may configure additional properties here // you may configure additional properties here
], ],
``` ```
Available properties you can configure are: Available properties you can configure are:
...@@ -133,7 +133,7 @@ Available properties you can configure are: ...@@ -133,7 +133,7 @@ Available properties you can configure are:
```php ```php
function ($url, $model) { function ($url, $model) {
// return the button HTML code // return the button HTML code
} }
``` ```
...@@ -152,14 +152,14 @@ To add a CheckboxColumn to the [[yii\grid\GridView]], add it to the [[yii\grid\G ...@@ -152,14 +152,14 @@ To add a CheckboxColumn to the [[yii\grid\GridView]], add it to the [[yii\grid\G
```php ```php
echo GridView::widget([ echo GridView::widget([
'dataProvider' => $dataProvider, 'dataProvider' => $dataProvider,
'columns' => [ 'columns' => [
// ... // ...
[ [
'class' => 'yii\grid\CheckboxColumn', 'class' => 'yii\grid\CheckboxColumn',
// you may configure additional properties here // you may configure additional properties here
], ],
], ],
``` ```
Users may click on the checkboxes to select rows of the grid. The selected rows may be obtained by calling the following Users may click on the checkboxes to select rows of the grid. The selected rows may be obtained by calling the following
...@@ -178,9 +178,9 @@ Usage is as simple as the following: ...@@ -178,9 +178,9 @@ Usage is as simple as the following:
```php ```php
echo GridView::widget([ echo GridView::widget([
'dataProvider' => $dataProvider, 'dataProvider' => $dataProvider,
'columns' => [ 'columns' => [
['class' => 'yii\grid\SerialColumn'], // <-- here ['class' => 'yii\grid\SerialColumn'], // <-- here
``` ```
Sorting data Sorting data
......
...@@ -16,10 +16,10 @@ The following is an example of using it to provide ActiveRecord instances: ...@@ -16,10 +16,10 @@ The following is an example of using it to provide ActiveRecord instances:
```php ```php
$provider = new ActiveDataProvider([ $provider = new ActiveDataProvider([
'query' => Post::find(), 'query' => Post::find(),
'pagination' => [ 'pagination' => [
'pageSize' => 20, 'pageSize' => 20,
], ],
]); ]);
// get the posts in the current page // get the posts in the current page
...@@ -31,10 +31,10 @@ And the following example shows how to use ActiveDataProvider without ActiveReco ...@@ -31,10 +31,10 @@ And the following example shows how to use ActiveDataProvider without ActiveReco
```php ```php
$query = new Query(); $query = new Query();
$provider = new ActiveDataProvider([ $provider = new ActiveDataProvider([
'query' => $query->from('tbl_post'), 'query' => $query->from('tbl_post'),
'pagination' => [ 'pagination' => [
'pageSize' => 20, 'pageSize' => 20,
], ],
]); ]);
// get the posts in the current page // get the posts in the current page
...@@ -130,4 +130,4 @@ be sorted. ...@@ -130,4 +130,4 @@ be sorted.
Implementing your own custom data provider Implementing your own custom data provider
------------------------------------------ ------------------------------------------
TBD TBD
\ No newline at end of file
...@@ -21,14 +21,14 @@ A typical usage of DetailView is as follows: ...@@ -21,14 +21,14 @@ A typical usage of DetailView is as follows:
```php ```php
echo DetailView::widget([ echo DetailView::widget([
'model' => $model, 'model' => $model,
'attributes' => [ 'attributes' => [
'title', // title attribute (in plain text) 'title', // title attribute (in plain text)
'description:html', // description attribute in HTML 'description:html', // description attribute in HTML
[ // the owner name of the model [ // the owner name of the model
'label' => 'Owner', 'label' => 'Owner',
'value' => $model->owner->name, 'value' => $model->owner->name,
], ],
], ],
]); ]);
``` ```
...@@ -22,25 +22,25 @@ to application configuration (for "basic" web application it's `config/web.php`) ...@@ -22,25 +22,25 @@ to application configuration (for "basic" web application it's `config/web.php`)
```php ```php
return [ return [
// ... // ...
'components' => [ 'components' => [
// ... // ...
'db' => [ 'db' => [
'class' => 'yii\db\Connection', 'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=mydatabase', // MySQL, MariaDB 'dsn' => 'mysql:host=localhost;dbname=mydatabase', // MySQL, MariaDB
//'dsn' => 'sqlite:/path/to/database/file', // SQLite //'dsn' => 'sqlite:/path/to/database/file', // SQLite
//'dsn' => 'pgsql:host=localhost;port=5432;dbname=mydatabase', // PostgreSQL //'dsn' => 'pgsql:host=localhost;port=5432;dbname=mydatabase', // PostgreSQL
//'dsn' => 'cubrid:dbname=demodb;host=localhost;port=33000', // CUBRID //'dsn' => 'cubrid:dbname=demodb;host=localhost;port=33000', // CUBRID
//'dsn' => 'sqlsrv:Server=localhost;Database=mydatabase', // MS SQL Server, sqlsrv driver //'dsn' => 'sqlsrv:Server=localhost;Database=mydatabase', // MS SQL Server, sqlsrv driver
//'dsn' => 'dblib:host=localhost;dbname=mydatabase', // MS SQL Server, dblib driver //'dsn' => 'dblib:host=localhost;dbname=mydatabase', // MS SQL Server, dblib driver
//'dsn' => 'mssql:host=localhost;dbname=mydatabase', // MS SQL Server, mssql driver //'dsn' => 'mssql:host=localhost;dbname=mydatabase', // MS SQL Server, mssql driver
//'dsn' => 'oci:dbname=//localhost:1521/mydatabase', // Oracle //'dsn' => 'oci:dbname=//localhost:1521/mydatabase', // Oracle
'username' => 'root', 'username' => 'root',
'password' => '', 'password' => '',
'charset' => 'utf8', 'charset' => 'utf8',
], ],
], ],
// ... // ...
]; ];
``` ```
...@@ -65,9 +65,9 @@ If you don't want to define the connection as an application component you can i ...@@ -65,9 +65,9 @@ If you don't want to define the connection as an application component you can i
```php ```php
$connection = new \yii\db\Connection([ $connection = new \yii\db\Connection([
'dsn' => $dsn, 'dsn' => $dsn,
'username' => $username, 'username' => $username,
'password' => $password, 'password' => $password,
]); ]);
$connection->open(); $connection->open();
``` ```
...@@ -78,18 +78,18 @@ $connection->open(); ...@@ -78,18 +78,18 @@ $connection->open();
> >
```php ```php
return [ return [
// ... // ...
'components' => [ 'components' => [
// ... // ...
'db' => [ 'db' => [
'class' => 'yii\db\Connection', 'class' => 'yii\db\Connection',
// ... // ...
'on afterOpen' => function($event) { 'on afterOpen' => function($event) {
$event->sender->createCommand("SET time_zone = 'UTC'")->execute(); $event->sender->createCommand("SET time_zone = 'UTC'")->execute();
} }
], ],
], ],
// ... // ...
]; ];
``` ```
...@@ -142,15 +142,15 @@ Alternatively the following syntax that takes care of proper table and column na ...@@ -142,15 +142,15 @@ Alternatively the following syntax that takes care of proper table and column na
```php ```php
// INSERT // INSERT
$connection->createCommand()->insert('tbl_user', [ $connection->createCommand()->insert('tbl_user', [
'name' => 'Sam', 'name' => 'Sam',
'age' => 30, 'age' => 30,
])->execute(); ])->execute();
// INSERT multiple rows at once // INSERT multiple rows at once
$connection->createCommand()->batchInsert('tbl_user', ['name', 'age'], [ $connection->createCommand()->batchInsert('tbl_user', ['name', 'age'], [
['Tom', 30], ['Tom', 30],
['Jane', 20], ['Jane', 20],
['Linda', 25], ['Linda', 25],
])->execute(); ])->execute();
// UPDATE // UPDATE
...@@ -215,12 +215,12 @@ You can perform transactional SQL queries like the following: ...@@ -215,12 +215,12 @@ You can perform transactional SQL queries like the following:
```php ```php
$transaction = $connection->beginTransaction(); $transaction = $connection->beginTransaction();
try { try {
$connection->createCommand($sql1)->execute(); $connection->createCommand($sql1)->execute();
$connection->createCommand($sql2)->execute(); $connection->createCommand($sql2)->execute();
// ... executing other SQL statements ... // ... executing other SQL statements ...
$transaction->commit(); $transaction->commit();
} catch(Exception $e) { } catch(Exception $e) {
$transaction->rollBack(); $transaction->rollBack();
} }
``` ```
...@@ -230,20 +230,20 @@ You can also nest multiple transactions, if needed: ...@@ -230,20 +230,20 @@ You can also nest multiple transactions, if needed:
// outer transaction // outer transaction
$transaction1 = $connection->beginTransaction(); $transaction1 = $connection->beginTransaction();
try { try {
$connection->createCommand($sql1)->execute(); $connection->createCommand($sql1)->execute();
// inner transaction // inner transaction
$transaction2 = $connection->beginTransaction(); $transaction2 = $connection->beginTransaction();
try { try {
$connection->createCommand($sql2)->execute(); $connection->createCommand($sql2)->execute();
$transaction2->commit(); $transaction2->commit();
} catch (Exception $e) { } catch (Exception $e) {
$transaction2->rollBack(); $transaction2->rollBack();
} }
$transaction1->commit(); $transaction1->commit();
} catch (Exception $e) { } catch (Exception $e) {
$transaction1->rollBack(); $transaction1->rollBack();
} }
``` ```
...@@ -282,9 +282,9 @@ These can be used as follows: ...@@ -282,9 +282,9 @@ These can be used as follows:
```php ```php
// CREATE TABLE // CREATE TABLE
$connection->createCommand()->createTable('tbl_post', [ $connection->createCommand()->createTable('tbl_post', [
'id' => 'pk', 'id' => 'pk',
'title' => 'string', 'title' => 'string',
'text' => 'text', 'text' => 'text',
]); ]);
``` ```
......
...@@ -9,9 +9,9 @@ use yii\base\ErrorException; ...@@ -9,9 +9,9 @@ use yii\base\ErrorException;
use Yii; use Yii;
try { try {
10/0; 10/0;
} catch (ErrorException) { } catch (ErrorException) {
Yii::warning("Tried dividing by zero."); Yii::warning("Tried dividing by zero.");
} }
// execution may continue // execution may continue
......
...@@ -28,13 +28,13 @@ to define event names using class constants: ...@@ -28,13 +28,13 @@ to define event names using class constants:
```php ```php
class Mailer extends Component class Mailer extends Component
{ {
const EVENT_SEND_EMAIL = 'sendEmail'; const EVENT_SEND_EMAIL = 'sendEmail';
public function send() public function send()
{ {
// ... // ...
$this->trigger(self::EVENT_SEND_EMAIL); $this->trigger(self::EVENT_SEND_EMAIL);
} }
} }
``` ```
...@@ -76,7 +76,7 @@ $component->on($eventName, [$obj, 'functionName']); ...@@ -76,7 +76,7 @@ $component->on($eventName, [$obj, 'functionName']);
// Anonymous function: // Anonymous function:
$component->on($eventName, function ($event) { $component->on($eventName, function ($event) {
// Use $event. // Use $event.
}); });
``` ```
...@@ -87,7 +87,7 @@ In order to pass extra data supply it via third argument: ...@@ -87,7 +87,7 @@ In order to pass extra data supply it via third argument:
```php ```php
$component->on($eventName, function ($event) { $component->on($eventName, function ($event) {
// the extra data can be accessed via $event->data // the extra data can be accessed via $event->data
}, $extraData); }, $extraData);
``` ```
...@@ -97,15 +97,15 @@ It is possible to use application config to attach event hanelers: ...@@ -97,15 +97,15 @@ It is possible to use application config to attach event hanelers:
```php ```php
return [ return [
// ... // ...
'components' => [ 'components' => [
'db' => [ 'db' => [
// ... // ...
'on afterOpen' => function ($event) { 'on afterOpen' => function ($event) {
// do something right after connected to database // do something right after connected to database
} }
], ],
], ],
]; ];
``` ```
...@@ -151,7 +151,7 @@ the static `Event::on` method: ...@@ -151,7 +151,7 @@ the static `Event::on` method:
```php ```php
Event::on(ActiveRecord::className(), ActiveRecord::EVENT_AFTER_INSERT, function ($event) { Event::on(ActiveRecord::className(), ActiveRecord::EVENT_AFTER_INSERT, function ($event) {
Yii::trace(get_class($event->sender) . ' is inserted.'); Yii::trace(get_class($event->sender) . ' is inserted.');
}); });
``` ```
......
...@@ -13,47 +13,47 @@ use yii\base\Model; ...@@ -13,47 +13,47 @@ use yii\base\Model;
class LoginForm extends Model class LoginForm extends Model
{ {
public $username; public $username;
public $password; public $password;
/** /**
* @return array the validation rules. * @return array the validation rules.
*/ */
public function rules() public function rules()
{ {
return [ return [
// username and password are both required // username and password are both required
[['username', 'password'], 'required'], [['username', 'password'], 'required'],
// password is validated by validatePassword() // password is validated by validatePassword()
['password', 'validatePassword'], ['password', 'validatePassword'],
]; ];
} }
/** /**
* Validates the password. * Validates the password.
* This method serves as the inline validation for password. * This method serves as the inline validation for password.
*/ */
public function validatePassword() public function validatePassword()
{ {
$user = User::findByUsername($this->username); $user = User::findByUsername($this->username);
if (!$user || !$user->validatePassword($this->password)) { if (!$user || !$user->validatePassword($this->password)) {
$this->addError('password', 'Incorrect username or password.'); $this->addError('password', 'Incorrect username or password.');
} }
} }
/** /**
* Logs in a user using the provided username and password. * Logs in a user using the provided username and password.
* @return boolean whether the user is logged in successfully * @return boolean whether the user is logged in successfully
*/ */
public function login() public function login()
{ {
if ($this->validate()) { if ($this->validate()) {
$user = User::findByUsername($this->username); $user = User::findByUsername($this->username);
return true; return true;
} else { } else {
return false; return false;
} }
} }
} }
``` ```
...@@ -64,17 +64,17 @@ use yii\helpers\Html; ...@@ -64,17 +64,17 @@ use yii\helpers\Html;
use yii\widgets\ActiveForm; use yii\widgets\ActiveForm;
<?php $form = ActiveForm::begin([ <?php $form = ActiveForm::begin([
'id' => 'login-form', 'id' => 'login-form',
'options' => ['class' => 'form-horizontal'], 'options' => ['class' => 'form-horizontal'],
]) ?> ]) ?>
<?= $form->field($model, 'username') ?> <?= $form->field($model, 'username') ?>
<?= $form->field($model, 'password')->passwordInput() ?> <?= $form->field($model, 'password')->passwordInput() ?>
<div class="form-group"> <div class="form-group">
<div class="col-lg-offset-1 col-lg-11"> <div class="col-lg-offset-1 col-lg-11">
<?= Html::submitButton('Login', ['class' => 'btn btn-primary']) ?> <?= Html::submitButton('Login', ['class' => 'btn btn-primary']) ?>
</div> </div>
</div> </div>
<?php ActiveForm::end() ?> <?php ActiveForm::end() ?>
``` ```
...@@ -147,22 +147,22 @@ use app\models\Setting; ...@@ -147,22 +147,22 @@ use app\models\Setting;
class SettingsController extends Controller class SettingsController extends Controller
{ {
// ... // ...
public function actionUpdate() public function actionUpdate()
{ {
$settings = Setting::find()->indexBy('id')->all(); $settings = Setting::find()->indexBy('id')->all();
if (Model::loadMultiple($settings, Yii::$app->request->post()) && Model::validateMultiple($settings)) { if (Model::loadMultiple($settings, Yii::$app->request->post()) && Model::validateMultiple($settings)) {
foreach ($settings as $setting) { foreach ($settings as $setting) {
$setting->save(false); $setting->save(false);
} }
return $this->redirect('index'); return $this->redirect('index');
} }
return $this->render('update', ['settings' => $settings]); return $this->render('update', ['settings' => $settings]);
} }
} }
``` ```
...@@ -181,7 +181,7 @@ use yii\widgets\ActiveForm; ...@@ -181,7 +181,7 @@ use yii\widgets\ActiveForm;
$form = ActiveForm::begin(); $form = ActiveForm::begin();
foreach ($settings as $index => $setting) { foreach ($settings as $index => $setting) {
echo Html::encode($setting->name) . ': ' . $form->field($setting, "[$index]value"); echo Html::encode($setting->name) . ': ' . $form->field($setting, "[$index]value");
} }
ActiveForm::end(); ActiveForm::end();
......
...@@ -27,9 +27,9 @@ Once the Gii extension has been installed, you enable it by adding these lines t ...@@ -27,9 +27,9 @@ Once the Gii extension has been installed, you enable it by adding these lines t
```php ```php
'modules' => [ 'modules' => [
'gii' => [ 'gii' => [
'class' => 'yii\gii\Module', 'class' => 'yii\gii\Module',
], ],
] ]
``` ```
...@@ -43,8 +43,8 @@ http://localhost/path/to/index.php?r=gii ...@@ -43,8 +43,8 @@ http://localhost/path/to/index.php?r=gii
> >
```php ```php
'gii' => [ 'gii' => [
'class' => 'yii\gii\Module', 'class' => 'yii\gii\Module',
'allowedIPs' => ['127.0.0.1', '::1', '192.168.0.*', '192.168.178.20'] // adjust this to your needs 'allowedIPs' => ['127.0.0.1', '::1', '192.168.0.*', '192.168.178.20'] // adjust this to your needs
], ],
``` ```
...@@ -57,10 +57,10 @@ In basic application template configuration structure is a bit different so Gii ...@@ -57,10 +57,10 @@ In basic application template configuration structure is a bit different so Gii
// ... // ...
if (YII_ENV_DEV) if (YII_ENV_DEV)
{ {
// configuration adjustments for 'dev' environment // configuration adjustments for 'dev' environment
$config['preload'][] = 'debug'; $config['preload'][] = 'debug';
$config['modules']['debug'] = 'yii\debug\Module'; $config['modules']['debug'] = 'yii\debug\Module';
$config['modules']['gii'] = 'yii\gii\Module'; // <--- here $config['modules']['gii'] = 'yii\gii\Module'; // <--- here
} }
``` ```
...@@ -69,13 +69,13 @@ So in order to adjust IP address you need to do it like the following: ...@@ -69,13 +69,13 @@ So in order to adjust IP address you need to do it like the following:
```php ```php
if (YII_ENV_DEV) if (YII_ENV_DEV)
{ {
// configuration adjustments for 'dev' environment // configuration adjustments for 'dev' environment
$config['preload'][] = 'debug'; $config['preload'][] = 'debug';
$config['modules']['debug'] = 'yii\debug\Module'; $config['modules']['debug'] = 'yii\debug\Module';
$config['modules']['gii'] = [ $config['modules']['gii'] = [
'class' => 'yii\gii\Module', 'class' => 'yii\gii\Module',
'allowedIPs' => ['127.0.0.1', '::1', '192.168.0.*', '192.168.178.20'], 'allowedIPs' => ['127.0.0.1', '::1', '192.168.0.*', '192.168.178.20'],
]; ];
} }
``` ```
......
...@@ -25,9 +25,9 @@ Target language is what's currently used. It's defined in application configurat ...@@ -25,9 +25,9 @@ Target language is what's currently used. It's defined in application configurat
```php ```php
// ... // ...
return [ return [
'id' => 'applicationID', 'id' => 'applicationID',
'basePath' => dirname(__DIR__), 'basePath' => dirname(__DIR__),
'language' => 'ru-RU' // ← here! 'language' => 'ru-RU' // ← here!
``` ```
Later you can easily change it in runtime: Later you can easily change it in runtime:
...@@ -62,20 +62,20 @@ Yii tries to load appropriate translation from one of the message sources define ...@@ -62,20 +62,20 @@ Yii tries to load appropriate translation from one of the message sources define
```php ```php
'components' => [ 'components' => [
// ... // ...
'i18n' => [ 'i18n' => [
'translations' => [ 'translations' => [
'app*' => [ 'app*' => [
'class' => 'yii\i18n\PhpMessageSource', 'class' => 'yii\i18n\PhpMessageSource',
//'basePath' => '@app/messages', //'basePath' => '@app/messages',
//'sourceLanguage' => 'en', //'sourceLanguage' => 'en',
'fileMap' => [ 'fileMap' => [
'app' => 'app.php', 'app' => 'app.php',
'app/error' => 'error.php', 'app/error' => 'error.php',
], ],
], ],
], ],
], ],
], ],
``` ```
...@@ -107,7 +107,7 @@ The format for this is to use curly brackets around the parameter name as you ca ...@@ -107,7 +107,7 @@ The format for this is to use curly brackets around the parameter name as you ca
```php ```php
$username = 'Alexander'; $username = 'Alexander';
echo \Yii::t('app', 'Hello, {username}!', [ echo \Yii::t('app', 'Hello, {username}!', [
'username' => $username, 'username' => $username,
]); ]);
``` ```
...@@ -260,8 +260,8 @@ provides a default phrase. ...@@ -260,8 +260,8 @@ provides a default phrase.
```php ```php
echo \Yii::t('app', '{name} is {gender} and {gender, select, female{she} male{he} other{it}} loves Yii!', [ echo \Yii::t('app', '{name} is {gender} and {gender, select, female{she} male{he} other{it}} loves Yii!', [
'name' => 'Snoopy', 'name' => 'Snoopy',
'gender' => 'dog', 'gender' => 'dog',
]); ]);
``` ```
...@@ -279,11 +279,11 @@ This translation should be marked with `*`. In order to do it add the following ...@@ -279,11 +279,11 @@ This translation should be marked with `*`. In order to do it add the following
//configure i18n component //configure i18n component
'i18n' => [ 'i18n' => [
'translations' => [ 'translations' => [
'*' => [ '*' => [
'class' => 'yii\i18n\PhpMessageSource' 'class' => 'yii\i18n\PhpMessageSource'
], ],
], ],
], ],
``` ```
...@@ -309,32 +309,32 @@ use Yii; ...@@ -309,32 +309,32 @@ use Yii;
class Module extends \yii\base\Module class Module extends \yii\base\Module
{ {
public $controllerNamespace = 'app\modules\users\controllers'; public $controllerNamespace = 'app\modules\users\controllers';
public function init() public function init()
{ {
parent::init(); parent::init();
$this->registerTranslations(); $this->registerTranslations();
} }
public function registerTranslations() public function registerTranslations()
{ {
Yii::$app->i18n->translations['modules/users/*'] = [ Yii::$app->i18n->translations['modules/users/*'] = [
'class' => 'yii\i18n\PhpMessageSource', 'class' => 'yii\i18n\PhpMessageSource',
'sourceLanguage' => 'en', 'sourceLanguage' => 'en',
'basePath' => '@app/modules/users/messages', 'basePath' => '@app/modules/users/messages',
'fileMap' => [ 'fileMap' => [
'modules/users/validation' => 'validation.php', 'modules/users/validation' => 'validation.php',
'modules/users/form' => 'form.php', 'modules/users/form' => 'form.php',
... ...
], ],
]; ];
} }
public static function t($category, $message, $params = [], $language = null) public static function t($category, $message, $params = [], $language = null)
{ {
return Yii::t('modules/users/' . $category, $message, $params, $language); return Yii::t('modules/users/' . $category, $message, $params, $language);
} }
} }
``` ```
...@@ -357,34 +357,34 @@ use Yii; ...@@ -357,34 +357,34 @@ use Yii;
class Menu extends Widget class Menu extends Widget
{ {
public function init() public function init()
{ {
parent::init(); parent::init();
$this->registerTranslations(); $this->registerTranslations();
} }
public function registerTranslations() public function registerTranslations()
{ {
$i18n = Yii::$app->i18n; $i18n = Yii::$app->i18n;
$i18n->translations['widgets/menu/*'] = [ $i18n->translations['widgets/menu/*'] = [
'class' => 'yii\i18n\PhpMessageSource', 'class' => 'yii\i18n\PhpMessageSource',
'sourceLanguage' => 'en', 'sourceLanguage' => 'en',
'basePath' => '@app/widgets/menu/messages', 'basePath' => '@app/widgets/menu/messages',
'fileMap' => [ 'fileMap' => [
'widgets/menu/messages' => 'messages.php', 'widgets/menu/messages' => 'messages.php',
], ],
]; ];
} }
public function run() public function run()
{ {
echo $this->render('index'); echo $this->render('index');
} }
public static function t($category, $message, $params = [], $language = null) public static function t($category, $message, $params = [], $language = null)
{ {
return Yii::t('widgets/menu/' . $category, $message, $params, $language); return Yii::t('widgets/menu/' . $category, $message, $params, $language);
} }
} }
``` ```
...@@ -411,12 +411,12 @@ on current locale. In order to use it you need to configure formatter applicatio ...@@ -411,12 +411,12 @@ on current locale. In order to use it you need to configure formatter applicatio
```php ```php
return [ return [
// ... // ...
'components' => [ 'components' => [
'formatter' => [ 'formatter' => [
'class' => 'yii\i18n\Formatter', 'class' => 'yii\i18n\Formatter',
], ],
], ],
]; ];
``` ```
......
...@@ -40,25 +40,25 @@ You may configure the targets in application configuration, like the following: ...@@ -40,25 +40,25 @@ You may configure the targets in application configuration, like the following:
```php ```php
[ [
'components' => [ 'components' => [
'log' => [ 'log' => [
'targets' => [ 'targets' => [
'file' => [ 'file' => [
'class' => 'yii\log\FileTarget', 'class' => 'yii\log\FileTarget',
'levels' => ['trace', 'info'], 'levels' => ['trace', 'info'],
'categories' => ['yii\*'], 'categories' => ['yii\*'],
], ],
'email' => [ 'email' => [
'class' => 'yii\log\EmailTarget', 'class' => 'yii\log\EmailTarget',
'levels' => ['error', 'warning'], 'levels' => ['error', 'warning'],
'message' => [ 'message' => [
'to' => ['admin@example.com', 'developer@example.com'], 'to' => ['admin@example.com', 'developer@example.com'],
'subject' => 'New example.com log message', 'subject' => 'New example.com log message',
], ],
], ],
], ],
], ],
], ],
] ]
``` ```
...@@ -97,10 +97,10 @@ Note, code blocks need to be nested properly such as ...@@ -97,10 +97,10 @@ Note, code blocks need to be nested properly such as
```php ```php
\Yii::beginProfile('block1'); \Yii::beginProfile('block1');
// some code to be profiled // some code to be profiled
\Yii::beginProfile('block2'); \Yii::beginProfile('block2');
// some other code to be profiled // some other code to be profiled
\Yii::endProfile('block2'); \Yii::endProfile('block2');
\Yii::endProfile('block1'); \Yii::endProfile('block1');
``` ```
......
...@@ -25,7 +25,7 @@ Add these lines to your config file: ...@@ -25,7 +25,7 @@ Add these lines to your config file:
```php ```php
'preload' => ['debug'], 'preload' => ['debug'],
'modules' => [ 'modules' => [
'debug' => ['yii\debug\Module'] 'debug' => ['yii\debug\Module']
] ]
``` ```
...@@ -35,10 +35,10 @@ Add these lines to your config file: ...@@ -35,10 +35,10 @@ Add these lines to your config file:
```php ```php
'preload' => ['debug'], 'preload' => ['debug'],
'modules' => [ 'modules' => [
'debug' => [ 'debug' => [
'class' => 'yii\debug\Module', 'class' => 'yii\debug\Module',
'allowedIPs' => ['1.2.3.4', '127.0.0.1', '::1'] 'allowedIPs' => ['1.2.3.4', '127.0.0.1', '::1']
] ]
] ]
``` ```
...@@ -46,11 +46,11 @@ If you are using `enableStrictParsing` URL manager option, add the following to ...@@ -46,11 +46,11 @@ If you are using `enableStrictParsing` URL manager option, add the following to
```php ```php
'urlManager' => [ 'urlManager' => [
'enableStrictParsing' => true, 'enableStrictParsing' => true,
'rules' => [ 'rules' => [
// ... // ...
'debug/<controller>/<action>' => 'debug/<controller>/<action>', 'debug/<controller>/<action>' => 'debug/<controller>/<action>',
], ],
], ],
``` ```
...@@ -67,10 +67,10 @@ trace level in the config: ...@@ -67,10 +67,10 @@ trace level in the config:
```php ```php
return [ return [
// ... // ...
'components' => [ 'components' => [
'log' => [ 'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0, // <-- here 'traceLevel' => YII_DEBUG ? 3 : 0, // <-- here
``` ```
By default it's automatically set to `3` if Yii is run in debug mode i.e. your `index.php` file contains the following: By default it's automatically set to `3` if Yii is run in debug mode i.e. your `index.php` file contains the following:
...@@ -104,50 +104,50 @@ use yii\debug\Panel; ...@@ -104,50 +104,50 @@ use yii\debug\Panel;
class ViewsPanel extends Panel class ViewsPanel extends Panel
{ {
private $_viewFiles = []; private $_viewFiles = [];
public function init() public function init()
{ {
parent::init(); parent::init();
Event::on(View::className(), View::EVENT_BEFORE_RENDER, function (ViewEvent $event) { Event::on(View::className(), View::EVENT_BEFORE_RENDER, function (ViewEvent $event) {
$this->_viewFiles[] = $event->sender->getViewFile(); $this->_viewFiles[] = $event->sender->getViewFile();
}); });
} }
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function getName() public function getName()
{ {
return 'Views'; return 'Views';
} }
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function getSummary() public function getSummary()
{ {
$url = $this->getUrl(); $url = $this->getUrl();
$count = count($this->data); $count = count($this->data);
return "<div class=\"yii-debug-toolbar-block\"><a href=\"$url\">Views <span class=\"label\">$count</span></a></div>"; return "<div class=\"yii-debug-toolbar-block\"><a href=\"$url\">Views <span class=\"label\">$count</span></a></div>";
} }
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function getDetail() public function getDetail()
{ {
return '<ol><li>' . implode('<li>', $this->data) . '</ol>'; return '<ol><li>' . implode('<li>', $this->data) . '</ol>';
} }
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function save() public function save()
{ {
return $this->_viewFiles; return $this->_viewFiles;
} }
} }
``` ```
...@@ -166,14 +166,14 @@ following: ...@@ -166,14 +166,14 @@ following:
```php ```php
if (YII_ENV_DEV) { if (YII_ENV_DEV) {
// configuration adjustments for 'dev' environment // configuration adjustments for 'dev' environment
$config['preload'][] = 'debug'; $config['preload'][] = 'debug';
$config['modules']['debug'] = [ $config['modules']['debug'] = [
'class' => 'yii\debug\Module', 'class' => 'yii\debug\Module',
'panels' => [ 'panels' => [
'views' => ['class' => 'app\panels\ViewsPanel'], 'views' => ['class' => 'app\panels\ViewsPanel'],
], ],
]; ];
// ... // ...
``` ```
......
...@@ -53,26 +53,26 @@ to save the time of parsing database schema. This can be done by setting the ...@@ -53,26 +53,26 @@ to save the time of parsing database schema. This can be done by setting the
```php ```php
return [ return [
// ... // ...
'components' => [ 'components' => [
// ... // ...
'db' => [ 'db' => [
'class' => 'yii\db\Connection', 'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=mydatabase', 'dsn' => 'mysql:host=localhost;dbname=mydatabase',
'username' => 'root', 'username' => 'root',
'password' => '', 'password' => '',
'enableSchemaCache' => true, 'enableSchemaCache' => true,
// Duration of schema cache. // Duration of schema cache.
// 'schemaCacheDuration' => 3600, // 'schemaCacheDuration' => 3600,
// Name of the cache component used. Default is 'cache'. // Name of the cache component used. Default is 'cache'.
//'schemaCache' => 'cache', //'schemaCache' => 'cache',
], ],
'cache' => [ 'cache' => [
'class' => 'yii\caching\FileCache', 'class' => 'yii\caching\FileCache',
], ],
], ],
]; ];
``` ```
...@@ -94,19 +94,19 @@ application via `protected/config/main.php`: ...@@ -94,19 +94,19 @@ application via `protected/config/main.php`:
```php ```php
return [ return [
// ... // ...
'components' => [ 'components' => [
'session' => [ 'session' => [
'class' => 'yii\web\DbSession', 'class' => 'yii\web\DbSession',
// Set the following if want to use DB component other than // Set the following if want to use DB component other than
// default 'db'. // default 'db'.
// 'db' => 'mydb', // 'db' => 'mydb',
// To override default session table set the following // To override default session table set the following
// 'sessionTable' => 'my_session', // 'sessionTable' => 'my_session',
], ],
], ],
]; ];
``` ```
...@@ -143,19 +143,19 @@ the following: ...@@ -143,19 +143,19 @@ the following:
```php ```php
public function behaviors() public function behaviors()
{ {
return [ return [
'httpCache' => [ 'httpCache' => [
'class' => \yii\web\HttpCache::className(), 'class' => \yii\web\HttpCache::className(),
'only' => ['list'], 'only' => ['list'],
'lastModified' => function ($action, $params) { 'lastModified' => function ($action, $params) {
$q = new Query(); $q = new Query();
return strtotime($q->from('users')->max('updated_timestamp')); return strtotime($q->from('users')->max('updated_timestamp'));
}, },
// 'etagSeed' => function ($action, $params) { // 'etagSeed' => function ($action, $params) {
// return // generate etag seed here // return // generate etag seed here
//} //}
], ],
]; ];
} }
``` ```
...@@ -197,11 +197,11 @@ ActiveRecord's `asArray` method. ...@@ -197,11 +197,11 @@ ActiveRecord's `asArray` method.
```php ```php
class PostController extends Controller class PostController extends Controller
{ {
public function actionIndex() public function actionIndex()
{ {
$posts = Post::find()->orderBy('id DESC')->limit(100)->asArray()->all(); $posts = Post::find()->orderBy('id DESC')->limit(100)->asArray()->all();
return $this->render('index', ['posts' => $posts]); return $this->render('index', ['posts' => $posts]);
} }
} }
``` ```
...@@ -209,7 +209,7 @@ In the view you should access fields of each individual record from `$posts` as ...@@ -209,7 +209,7 @@ In the view you should access fields of each individual record from `$posts` as
```php ```php
foreach ($posts as $post) { foreach ($posts as $post) {
echo $post['title']."<br>"; echo $post['title']."<br>";
} }
``` ```
......
...@@ -10,17 +10,17 @@ A typical usage of the query builder looks like the following: ...@@ -10,17 +10,17 @@ A typical usage of the query builder looks like the following:
```php ```php
$rows = (new \yii\db\Query()) $rows = (new \yii\db\Query())
->select('id, name') ->select('id, name')
->from('tbl_user') ->from('tbl_user')
->limit(10) ->limit(10)
->all(); ->all();
// which is equivalent to the following code: // which is equivalent to the following code:
$query = (new \yii\db\Query()) $query = (new \yii\db\Query())
->select('id, name') ->select('id, name')
->from('tbl_user') ->from('tbl_user')
->limit(10); ->limit(10);
// Create a command. You can get the actual SQL using $command->sql // Create a command. You can get the actual SQL using $command->sql
$command = $query->createCommand(); $command = $query->createCommand();
...@@ -62,7 +62,7 @@ In order to form a basic `SELECT` query, you need to specify what columns to sel ...@@ -62,7 +62,7 @@ In order to form a basic `SELECT` query, you need to specify what columns to sel
```php ```php
$query->select('id, name') $query->select('id, name')
->from('tbl_user'); ->from('tbl_user');
``` ```
Select options can be specified as a comma-separated string, as in the above, or as an array. Select options can be specified as a comma-separated string, as in the above, or as an array.
...@@ -70,7 +70,7 @@ The array syntax is especially useful when forming the selection dynamically: ...@@ -70,7 +70,7 @@ The array syntax is especially useful when forming the selection dynamically:
```php ```php
$query->select(['id', 'name']) $query->select(['id', 'name'])
->from('tbl_user'); ->from('tbl_user');
``` ```
> Info: You should always use the array format if your `SELECT` clause contains SQL expressions. > Info: You should always use the array format if your `SELECT` clause contains SQL expressions.
...@@ -148,9 +148,9 @@ Multiple conditions can simultaneously be set in `where` using the *hash format* ...@@ -148,9 +148,9 @@ Multiple conditions can simultaneously be set in `where` using the *hash format*
```php ```php
$query->where([ $query->where([
'status' => 10, 'status' => 10,
'type' => 2, 'type' => 2,
'id' => [4, 8, 15, 16, 23, 42], 'id' => [4, 8, 15, 16, 23, 42],
]); ]);
``` ```
...@@ -222,7 +222,7 @@ $search = 'yii'; ...@@ -222,7 +222,7 @@ $search = 'yii';
$query->where(['status' => $status]); $query->where(['status' => $status]);
if (!empty($search)) { if (!empty($search)) {
$query->andWhere(['like', 'title', $search]); $query->andWhere(['like', 'title', $search]);
} }
``` ```
...@@ -238,8 +238,8 @@ For ordering results `orderBy` and `addOrderBy` could be used: ...@@ -238,8 +238,8 @@ For ordering results `orderBy` and `addOrderBy` could be used:
```php ```php
$query->orderBy([ $query->orderBy([
'id' => SORT_ASC, 'id' => SORT_ASC,
'name' => SORT_DESC, 'name' => SORT_DESC,
]); ]);
``` ```
...@@ -294,8 +294,8 @@ This left join selects data from two related tables in one query: ...@@ -294,8 +294,8 @@ This left join selects data from two related tables in one query:
```php ```php
$query->select(['tbl_user.name AS author', 'tbl_post.title as title']) $query->select(['tbl_user.name AS author', 'tbl_post.title as title'])
->from('tbl_user') ->from('tbl_user')
->leftJoin('tbl_post', 'tbl_post.user_id = tbl_user.id'); ->leftJoin('tbl_post', 'tbl_post.user_id = tbl_user.id');
``` ```
In the code, the `leftJoin()` method's first parameter In the code, the `leftJoin()` method's first parameter
...@@ -348,16 +348,16 @@ Batch query can be used like the following: ...@@ -348,16 +348,16 @@ Batch query can be used like the following:
use yii\db\Query; use yii\db\Query;
$query = (new Query()) $query = (new Query())
->from('tbl_user') ->from('tbl_user')
->orderBy('id'); ->orderBy('id');
foreach ($query->batch() as $users) { foreach ($query->batch() as $users) {
// $users is an array of 100 or fewer rows from the user table // $users is an array of 100 or fewer rows from the user table
} }
// or if you want to iterate the row one by one // or if you want to iterate the row one by one
foreach ($query->each() as $user) { foreach ($query->each() as $user) {
// $user represents one row of data from the user table // $user represents one row of data from the user table
} }
``` ```
...@@ -377,11 +377,11 @@ will still keep the proper index. For example, ...@@ -377,11 +377,11 @@ will still keep the proper index. For example,
use yii\db\Query; use yii\db\Query;
$query = (new Query()) $query = (new Query())
->from('tbl_user') ->from('tbl_user')
->indexBy('username'); ->indexBy('username');
foreach ($query->batch() as $users) { foreach ($query->batch() as $users) {
// $users is indexed by the "username" column // $users is indexed by the "username" column
} }
foreach ($query->each() as $username => $user) { foreach ($query->each() as $username => $user) {
......
...@@ -25,9 +25,9 @@ When a user attempts to log in, the submitted password must be verified against ...@@ -25,9 +25,9 @@ When a user attempts to log in, the submitted password must be verified against
```php ```php
use yii\helpers\Security; use yii\helpers\Security;
if (Security::validatePassword($password, $hash)) { if (Security::validatePassword($password, $hash)) {
// all good, logging user in // all good, logging user in
} else { } else {
// wrong password // wrong password
} }
``` ```
......
...@@ -9,24 +9,24 @@ component's behavior: ...@@ -9,24 +9,24 @@ component's behavior:
```php ```php
[ [
'components' => [ 'components' => [
'view' => [ 'view' => [
'class' => 'yii\web\View', 'class' => 'yii\web\View',
'renderers' => [ 'renderers' => [
'tpl' => [ 'tpl' => [
'class' => 'yii\smarty\ViewRenderer', 'class' => 'yii\smarty\ViewRenderer',
//'cachePath' => '@runtime/Smarty/cache', //'cachePath' => '@runtime/Smarty/cache',
], ],
'twig' => [ 'twig' => [
'class' => 'yii\twig\ViewRenderer', 'class' => 'yii\twig\ViewRenderer',
//'cachePath' => '@runtime/Twig/cache', //'cachePath' => '@runtime/Twig/cache',
//'options' => [], /* Array of twig options */ //'options' => [], /* Array of twig options */
'globals' => ['html' => '\yii\helpers\Html'], 'globals' => ['html' => '\yii\helpers\Html'],
], ],
// ... // ...
], ],
], ],
], ],
] ]
``` ```
...@@ -74,8 +74,8 @@ variables there: ...@@ -74,8 +74,8 @@ variables there:
```php ```php
'globals' => [ 'globals' => [
'html' => '\yii\helpers\Html', 'html' => '\yii\helpers\Html',
'name' => 'Carsten', 'name' => 'Carsten',
], ],
``` ```
...@@ -91,7 +91,7 @@ Additional filters may be added via the application configuration's `filters` op ...@@ -91,7 +91,7 @@ Additional filters may be added via the application configuration's `filters` op
```php ```php
'filters' => [ 'filters' => [
'jsonEncode' => '\yii\helpers\Json::encode', 'jsonEncode' => '\yii\helpers\Json::encode',
], ],
``` ```
......
...@@ -32,7 +32,7 @@ use yii\test\ActiveFixture; ...@@ -32,7 +32,7 @@ use yii\test\ActiveFixture;
class UserFixture extends ActiveFixture class UserFixture extends ActiveFixture
{ {
public $modelClass = 'app\models\User'; public $modelClass = 'app\models\User';
} }
``` ```
...@@ -50,18 +50,18 @@ to be inserted into the user table. For example, ...@@ -50,18 +50,18 @@ to be inserted into the user table. For example,
```php ```php
<?php <?php
return [ return [
'user1' => [ 'user1' => [
'username' => 'lmayert', 'username' => 'lmayert',
'email' => 'strosin.vernice@jerde.com', 'email' => 'strosin.vernice@jerde.com',
'auth_key' => 'K3nF70it7tzNsHddEiq0BZ0i-OU8S3xV', 'auth_key' => 'K3nF70it7tzNsHddEiq0BZ0i-OU8S3xV',
'password' => '$2y$13$WSyE5hHsG1rWN2jV8LRHzubilrCLI5Ev/iK0r3jRuwQEs2ldRu.a2', 'password' => '$2y$13$WSyE5hHsG1rWN2jV8LRHzubilrCLI5Ev/iK0r3jRuwQEs2ldRu.a2',
], ],
'user2' => [ 'user2' => [
'username' => 'napoleon69', 'username' => 'napoleon69',
'email' => 'aileen.barton@heaneyschumm.com', 'email' => 'aileen.barton@heaneyschumm.com',
'auth_key' => 'dZlXsVnIDgIzFgX4EduAqkEPuphhOh9q', 'auth_key' => 'dZlXsVnIDgIzFgX4EduAqkEPuphhOh9q',
'password' => '$2y$13$kkgpvJ8lnjKo8RuoR30ay.RjDf15bMcHIF7Vz1zz/6viYG5xJExU6', 'password' => '$2y$13$kkgpvJ8lnjKo8RuoR30ay.RjDf15bMcHIF7Vz1zz/6viYG5xJExU6',
], ],
]; ];
``` ```
...@@ -85,8 +85,8 @@ use yii\test\ActiveFixture; ...@@ -85,8 +85,8 @@ use yii\test\ActiveFixture;
class UserProfileFixture extends ActiveFixture class UserProfileFixture extends ActiveFixture
{ {
public $modelClass = 'app\models\UserProfile'; public $modelClass = 'app\models\UserProfile';
public $depends = ['app\tests\fixtures\UserFixture']; public $depends = ['app\tests\fixtures\UserFixture'];
} }
``` ```
...@@ -116,14 +116,14 @@ use app\tests\fixtures\UserProfileFixture; ...@@ -116,14 +116,14 @@ use app\tests\fixtures\UserProfileFixture;
class UserProfileTest extends DbTestCase class UserProfileTest extends DbTestCase
{ {
public function fixtures() public function fixtures()
{ {
return [ return [
'profiles' => UserProfileFixture::className(), 'profiles' => UserProfileFixture::className(),
]; ];
} }
// ...test methods... // ...test methods...
} }
``` ```
...@@ -188,16 +188,16 @@ your class namespaces. For example, ...@@ -188,16 +188,16 @@ your class namespaces. For example,
# under folder tests\unit\fixtures # under folder tests\unit\fixtures
data\ data\
components\ components\
fixture_data_file1.php fixture_data_file1.php
fixture_data_file2.php fixture_data_file2.php
... ...
fixture_data_fileN.php fixture_data_fileN.php
models\ models\
fixture_data_file1.php fixture_data_file1.php
fixture_data_file2.php fixture_data_file2.php
... ...
fixture_data_fileN.php fixture_data_fileN.php
# and so on # and so on
``` ```
......
...@@ -16,12 +16,12 @@ be in your application config file: ...@@ -16,12 +16,12 @@ be in your application config file:
```php ```php
'components' => [ 'components' => [
'view' => [ 'view' => [
'theme' => [ 'theme' => [
'pathMap' => ['@app/views' => '@webroot/themes/basic'], 'pathMap' => ['@app/views' => '@webroot/themes/basic'],
'baseUrl' => '@web/themes/basic', 'baseUrl' => '@web/themes/basic',
], ],
], ],
], ],
``` ```
...@@ -36,10 +36,10 @@ It is possible to map a single path to multiple paths. For example, ...@@ -36,10 +36,10 @@ It is possible to map a single path to multiple paths. For example,
```php ```php
'pathMap' => [ 'pathMap' => [
'/web/views' => [ '/web/views' => [
'/web/themes/christmas', '/web/themes/christmas',
'/web/themes/basic', '/web/themes/basic',
], ],
] ]
``` ```
......
...@@ -113,7 +113,7 @@ If you need to handle all instances of a class instead of the object you can att ...@@ -113,7 +113,7 @@ If you need to handle all instances of a class instead of the object you can att
```php ```php
Event::on(ActiveRecord::className(), ActiveRecord::EVENT_AFTER_INSERT, function ($event) { Event::on(ActiveRecord::className(), ActiveRecord::EVENT_AFTER_INSERT, function ($event) {
Yii::trace(get_class($event->sender) . ' is inserted.'); Yii::trace(get_class($event->sender) . ' is inserted.');
}); });
``` ```
...@@ -256,8 +256,8 @@ echo \yii\widgets\Menu::widget(['items' => $items]); ...@@ -256,8 +256,8 @@ echo \yii\widgets\Menu::widget(['items' => $items]);
// Passing an array to initialize the object properties // Passing an array to initialize the object properties
$form = \yii\widgets\ActiveForm::begin([ $form = \yii\widgets\ActiveForm::begin([
'options' => ['class' => 'form-horizontal'], 'options' => ['class' => 'form-horizontal'],
'fieldConfig' => ['inputOptions' => ['class' => 'input-xlarge']], 'fieldConfig' => ['inputOptions' => ['class' => 'input-xlarge']],
]); ]);
... form inputs here ... ... form inputs here ...
\yii\widgets\ActiveForm::end(); \yii\widgets\ActiveForm::end();
...@@ -377,11 +377,11 @@ Using fields, you can build a form more cleanly than before: ...@@ -377,11 +377,11 @@ Using fields, you can build a form more cleanly than before:
```php ```php
<?php $form = yii\widgets\ActiveForm::begin(); ?> <?php $form = yii\widgets\ActiveForm::begin(); ?>
<?= $form->field($model, 'username') ?> <?= $form->field($model, 'username') ?>
<?= $form->field($model, 'password')->passwordInput() ?> <?= $form->field($model, 'password')->passwordInput() ?>
<div class="form-group"> <div class="form-group">
<?= Html::submitButton('Login') ?> <?= Html::submitButton('Login') ?>
</div> </div>
<?php yii\widgets\ActiveForm::end(); ?> <?php yii\widgets\ActiveForm::end(); ?>
``` ```
...@@ -419,10 +419,10 @@ an [[yii\db\ActiveQuery|ActiveQuery]] object. For example, the following method ...@@ -419,10 +419,10 @@ an [[yii\db\ActiveQuery|ActiveQuery]] object. For example, the following method
```php ```php
class Customer extends \yii\db\ActiveRecord class Customer extends \yii\db\ActiveRecord
{ {
public function getOrders() public function getOrders()
{ {
return $this->hasMany('Order', ['customer_id' => 'id']); return $this->hasMany('Order', ['customer_id' => 'id']);
} }
} }
``` ```
...@@ -443,9 +443,9 @@ use the [[yii\db\ActiveRecord::find()|find()]] method: ...@@ -443,9 +443,9 @@ use the [[yii\db\ActiveRecord::find()|find()]] method:
```php ```php
// to retrieve all *active* customers and order them by their ID: // to retrieve all *active* customers and order them by their ID:
$customers = Customer::find() $customers = Customer::find()
->where(['status' => $active]) ->where(['status' => $active])
->orderBy('id') ->orderBy('id')
->all(); ->all();
// return the customer whose PK is 1 // return the customer whose PK is 1
$customer = Customer::find(1); $customer = Customer::find(1);
``` ```
...@@ -506,9 +506,9 @@ the same goal. ...@@ -506,9 +506,9 @@ the same goal.
```php ```php
[ [
'pattern' => 'post/<page:\d+>/<tag>', 'pattern' => 'post/<page:\d+>/<tag>',
'route' => 'post/index', 'route' => 'post/index',
'defaults' => ['page' => 1], 'defaults' => ['page' => 1],
] ]
``` ```
......
...@@ -114,13 +114,13 @@ the application's configuration file: ...@@ -114,13 +114,13 @@ the application's configuration file:
```php ```php
<?php <?php
return [ return [
// ... // ...
'components' => [ 'components' => [
'urlManager' => [ 'urlManager' => [
'enablePrettyUrl' => true, 'enablePrettyUrl' => true,
'showScriptName' => false, 'showScriptName' => false,
], ],
], ],
]; ];
``` ```
...@@ -144,9 +144,9 @@ Let's use some examples to explain how URL rules work. We assume that our rule s ...@@ -144,9 +144,9 @@ Let's use some examples to explain how URL rules work. We assume that our rule s
```php ```php
[ [
'posts'=>'post/list', 'posts'=>'post/list',
'post/<id:\d+>'=>'post/read', 'post/<id:\d+>'=>'post/read',
'post/<year:\d{4}>/<title>'=>'post/read', 'post/<year:\d{4}>/<title>'=>'post/read',
] ]
``` ```
...@@ -180,9 +180,9 @@ We use the following example rules to illustrate how to parameterize routes with ...@@ -180,9 +180,9 @@ We use the following example rules to illustrate how to parameterize routes with
```php ```php
[ [
'<controller:(post|comment)>/<id:\d+>/<action:(create|update|delete)>' => '<controller>/<action>', '<controller:(post|comment)>/<id:\d+>/<action:(create|update|delete)>' => '<controller>/<action>',
'<controller:(post|comment)>/<id:\d+>' => '<controller>/read', '<controller:(post|comment)>/<id:\d+>' => '<controller>/read',
'<controller:(post|comment)>s' => '<controller>/list', '<controller:(post|comment)>s' => '<controller>/list',
] ]
``` ```
...@@ -202,7 +202,7 @@ In order to use parameterized hostnames, simply declare URL rules with host info ...@@ -202,7 +202,7 @@ In order to use parameterized hostnames, simply declare URL rules with host info
```php ```php
[ [
'http://<user:\w+>.example.com/<lang:\w+>/profile' => 'user/profile', 'http://<user:\w+>.example.com/<lang:\w+>/profile' => 'user/profile',
] ]
``` ```
...@@ -220,12 +220,12 @@ should still use the same URL rule as described above without the subfolder `san ...@@ -220,12 +220,12 @@ should still use the same URL rule as described above without the subfolder `san
```php ```php
<?php <?php
return [ return [
// ... // ...
'components' => [ 'components' => [
'urlManager' => [ 'urlManager' => [
'suffix' => '.html', 'suffix' => '.html',
], ],
], ],
]; ];
``` ```
...@@ -250,12 +250,12 @@ By default if there's no custom rule for a URL and the URL matches the default f ...@@ -250,12 +250,12 @@ By default if there's no custom rule for a URL and the URL matches the default f
```php ```php
<?php <?php
return [ return [
// ... // ...
'components' => [ 'components' => [
'urlManager' => [ 'urlManager' => [
'enableStrictParsing' => true, 'enableStrictParsing' => true,
], ],
], ],
]; ];
``` ```
...@@ -274,15 +274,15 @@ the above car dealer website as an example, we may declare the following URL rul ...@@ -274,15 +274,15 @@ the above car dealer website as an example, we may declare the following URL rul
```php ```php
// ... // ...
'components' => [ 'components' => [
'urlManager' => [ 'urlManager' => [
'rules' => [ 'rules' => [
'<action:(login|logout|about)>' => 'site/<action>', '<action:(login|logout|about)>' => 'site/<action>',
// ... // ...
['class' => 'app\components\CarUrlRule', 'connectionID' => 'db', /* ... */], ['class' => 'app\components\CarUrlRule', 'connectionID' => 'db', /* ... */],
], ],
], ],
], ],
``` ```
...@@ -296,31 +296,31 @@ use yii\web\UrlRule; ...@@ -296,31 +296,31 @@ use yii\web\UrlRule;
class CarUrlRule extends UrlRule class CarUrlRule extends UrlRule
{ {
public $connectionID = 'db'; public $connectionID = 'db';
public function createUrl($manager, $route, $params) public function createUrl($manager, $route, $params)
{ {
if ($route === 'car/index') { if ($route === 'car/index') {
if (isset($params['manufacturer'], $params['model'])) { if (isset($params['manufacturer'], $params['model'])) {
return $params['manufacturer'] . '/' . $params['model']; return $params['manufacturer'] . '/' . $params['model'];
} elseif (isset($params['manufacturer'])) { } elseif (isset($params['manufacturer'])) {
return $params['manufacturer']; return $params['manufacturer'];
} }
} }
return false; // this rule does not apply return false; // this rule does not apply
} }
public function parseRequest($manager, $request) public function parseRequest($manager, $request)
{ {
$pathInfo = $request->getPathInfo(); $pathInfo = $request->getPathInfo();
if (preg_match('%^(\w+)(/(\w+))?$%', $pathInfo, $matches)) { if (preg_match('%^(\w+)(/(\w+))?$%', $pathInfo, $matches)) {
// check $matches[1] and $matches[3] to see // check $matches[1] and $matches[3] to see
// if they match a manufacturer and a model in the database // if they match a manufacturer and a model in the database
// If so, set $params['manufacturer'] and/or $params['model'] // If so, set $params['manufacturer'] and/or $params['model']
// and return ['car/index', $params] // and return ['car/index', $params]
} }
return false; // this rule does not apply return false; // this rule does not apply
} }
} }
``` ```
......
...@@ -87,31 +87,31 @@ require($yii1path . '/YiiBase.php'); ...@@ -87,31 +87,31 @@ require($yii1path . '/YiiBase.php');
class Yii extends \yii\BaseYii class Yii extends \yii\BaseYii
{ {
public static $classMap = []; public static $classMap = [];
public static $enableIncludePath = true; public static $enableIncludePath = true;
private static $_aliases = ['system'=>YII_PATH,'zii'=>YII_ZII_PATH]; private static $_aliases = ['system'=>YII_PATH,'zii'=>YII_ZII_PATH];
private static $_imports = []; private static $_imports = [];
private static $_includePaths; private static $_includePaths;
private static $_app; private static $_app;
private static $_logger; private static $_logger;
public static function getVersion() public static function getVersion()
{ {
return '1.1.15-dev'; return '1.1.15-dev';
} }
public static function createWebApplication($config=null) public static function createWebApplication($config=null)
{ {
return self::createApplication('CWebApplication',$config); return self::createApplication('CWebApplication',$config);
} }
public static function app() public static function app()
{ {
return self::$_app; return self::$_app;
} }
// Rest of \YiiBase internal code placed here // Rest of \YiiBase internal code placed here
... ...
} }
Yii::$classMap = include($yii2path . '/classes.php'); Yii::$classMap = include($yii2path . '/classes.php');
...@@ -141,4 +141,4 @@ while ```Yii::app()``` refers to Yii 1.x application: ...@@ -141,4 +141,4 @@ while ```Yii::app()``` refers to Yii 1.x application:
```php ```php
echo get_class(Yii::app()); // outputs 'CWebApplication' echo get_class(Yii::app()); // outputs 'CWebApplication'
echo get_class(Yii::$app); // outputs 'yii\web\Application' echo get_class(Yii::$app); // outputs 'yii\web\Application'
``` ```
\ No newline at end of file
...@@ -98,8 +98,8 @@ Or an anonymous function: ...@@ -98,8 +98,8 @@ Or an anonymous function:
```php ```php
['text', 'filter', 'filter' => function ($value) { ['text', 'filter', 'filter' => function ($value) {
// here we are removing all swear words from text // here we are removing all swear words from text
return $newValue; return $newValue;
}], }],
``` ```
...@@ -197,9 +197,9 @@ operate without model do. In our case to validate an email we can do the followi ...@@ -197,9 +197,9 @@ operate without model do. In our case to validate an email we can do the followi
$email = 'test@example.com'; $email = 'test@example.com';
$validator = new yii\validators\EmailValidator(); $validator = new yii\validators\EmailValidator();
if ($validator->validate($email, $error)) { if ($validator->validate($email, $error)) {
echo 'Email is valid.'; echo 'Email is valid.';
} else { } else {
echo $error; echo $error;
} }
``` ```
......
...@@ -18,7 +18,7 @@ The view is typically called from controller action using the [[yii\base\Control ...@@ -18,7 +18,7 @@ The view is typically called from controller action using the [[yii\base\Control
```php ```php
public function actionIndex() public function actionIndex()
{ {
return $this->render('index', ['username' => 'samdark']); return $this->render('index', ['username' => 'samdark']);
} }
``` ```
...@@ -74,8 +74,8 @@ echo \yii\widgets\Menu::widget(['items' => $items]); ...@@ -74,8 +74,8 @@ echo \yii\widgets\Menu::widget(['items' => $items]);
// Passing an array to initialize the object properties // Passing an array to initialize the object properties
$form = \yii\widgets\ActiveForm::begin([ $form = \yii\widgets\ActiveForm::begin([
'options' => ['class' => 'form-horizontal'], 'options' => ['class' => 'form-horizontal'],
'fieldConfig' => ['inputOptions' => ['class' => 'input-xlarge']], 'fieldConfig' => ['inputOptions' => ['class' => 'input-xlarge']],
]); ]);
... form inputs here ... ... form inputs here ...
\yii\widgets\ActiveForm::end(); \yii\widgets\ActiveForm::end();
...@@ -104,7 +104,7 @@ use yii\helpers\Html; ...@@ -104,7 +104,7 @@ use yii\helpers\Html;
?> ?>
<div class="username"> <div class="username">
<?= Html::encode($user->name) ?> <?= Html::encode($user->name) ?>
</div> </div>
``` ```
...@@ -117,7 +117,7 @@ use yii\helpers\HtmlPurifier; ...@@ -117,7 +117,7 @@ use yii\helpers\HtmlPurifier;
?> ?>
<div class="post"> <div class="post">
<?= HtmlPurifier::process($post->text) ?> <?= HtmlPurifier::process($post->text) ?>
</div> </div>
``` ```
...@@ -180,10 +180,10 @@ server. Yii view object has a method to work with these: ...@@ -180,10 +180,10 @@ server. Yii view object has a method to work with these:
```php ```php
$this->registerLinkTag([ $this->registerLinkTag([
'title' => 'Lives News for Yii Framework', 'title' => 'Lives News for Yii Framework',
'rel' => 'alternate', 'rel' => 'alternate',
'type' => 'application/rss+xml', 'type' => 'application/rss+xml',
'href' => 'http://www.yiiframework.com/rss.xml/', 'href' => 'http://www.yiiframework.com/rss.xml/',
]); ]);
``` ```
...@@ -300,16 +300,16 @@ use yii\helpers\Html; ...@@ -300,16 +300,16 @@ use yii\helpers\Html;
<!DOCTYPE html> <!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>"> <html lang="<?= Yii::$app->language ?>">
<head> <head>
<meta charset="<?= Yii::$app->charset ?>"/> <meta charset="<?= Yii::$app->charset ?>"/>
<title><?= Html::encode($this->title) ?></title> <title><?= Html::encode($this->title) ?></title>
<?php $this->head() ?> <?php $this->head() ?>
</head> </head>
<body> <body>
<?php $this->beginBody() ?> <?php $this->beginBody() ?>
<div class="container"> <div class="container">
<?= $content ?> <?= $content ?>
</div> </div>
<footer class="footer">© 2013 me :)</footer> <footer class="footer">© 2013 me :)</footer>
<?php $this->endBody() ?> <?php $this->endBody() ?>
</body> </body>
</html> </html>
...@@ -343,8 +343,8 @@ use yii\helpers\Html; ...@@ -343,8 +343,8 @@ use yii\helpers\Html;
?> ?>
<div class="profile"> <div class="profile">
<h2><?= Html::encode($username) ?></h2> <h2><?= Html::encode($username) ?></h2>
<p><?= Html::encode($tagline) ?></p> <p><?= Html::encode($tagline) ?></p>
</div> </div>
``` ```
...@@ -352,14 +352,14 @@ Then we're using it in `index.php` view where we display a list of users: ...@@ -352,14 +352,14 @@ Then we're using it in `index.php` view where we display a list of users:
```php ```php
<div class="user-index"> <div class="user-index">
<?php <?php
foreach ($users as $user) { foreach ($users as $user) {
echo $this->render('_profile', [ echo $this->render('_profile', [
'username' => $user->name, 'username' => $user->name,
'tagline' => $user->tagline, 'tagline' => $user->tagline,
]); ]);
} }
?> ?>
</div> </div>
``` ```
...@@ -367,8 +367,8 @@ Same way we can reuse it in another view displaying a single user profile: ...@@ -367,8 +367,8 @@ Same way we can reuse it in another view displaying a single user profile:
```php ```php
echo $this->render('_profile', [ echo $this->render('_profile', [
'username' => $user->name, 'username' => $user->name,
'tagline' => $user->tagline, 'tagline' => $user->tagline,
]); ]);
``` ```
...@@ -394,12 +394,12 @@ from [[yii\base\View]] or [[yii\web\View]]. It can be done via application confi ...@@ -394,12 +394,12 @@ from [[yii\base\View]] or [[yii\web\View]]. It can be done via application confi
```php ```php
return [ return [
// ... // ...
'components' => [ 'components' => [
'view' => [ 'view' => [
'class' => 'app\components\View', 'class' => 'app\components\View',
], ],
// ... // ...
], ],
]; ];
``` ```
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