Commit eaaf5f02 by Qiang Xue

replaced tabs with spaces in docs.

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