diff --git a/docs/guide/active-record.md b/docs/guide/active-record.md index 398ae1c..4faa170 100644 --- a/docs/guide/active-record.md +++ b/docs/guide/active-record.md @@ -29,13 +29,13 @@ use yii\db\ActiveRecord; class Customer extends ActiveRecord { - /** - * @return string the name of the table associated with this ActiveRecord class. - */ - public static function tableName() - { - return 'tbl_customer'; - } + /** + * @return string the name of the table associated with this ActiveRecord class. + */ + public static function tableName() + { + return 'tbl_customer'; + } } ``` @@ -55,14 +55,14 @@ By default, ActiveRecord assumes that there is an application component named `d ```php return [ - 'components' => [ - 'db' => [ - 'class' => 'yii\db\Connection', - 'dsn' => 'mysql:host=localhost;dbname=testdb', - 'username' => 'demo', - 'password' => 'demo', - ], - ], + 'components' => [ + 'db' => [ + 'class' => 'yii\db\Connection', + 'dsn' => 'mysql:host=localhost;dbname=testdb', + 'username' => 'demo', + 'password' => 'demo', + ], + ], ]; ``` @@ -82,17 +82,17 @@ of flexible and powerful DB query methods. The following examples demonstrate so ```php // to retrieve all *active* customers and order them by their ID: $customers = Customer::find() - ->where(['status' => Customer::STATUS_ACTIVE]) - ->orderBy('id') - ->all(); + ->where(['status' => Customer::STATUS_ACTIVE]) + ->orderBy('id') + ->all(); // to return a single customer whose ID is 1: $customer = Customer::find(1); // the above code is equivalent to the following: $customer = Customer::find() - ->where(['id' => 1]) - ->one(); + ->where(['id' => 1]) + ->one(); // to retrieve customers using a raw SQL statement: $sql = 'SELECT * FROM tbl_customer'; @@ -100,13 +100,13 @@ $customers = Customer::findBySql($sql)->all(); // to return the number of *active* customers: $count = Customer::find() - ->where(['status' => Customer::STATUS_ACTIVE]) - ->count(); + ->where(['status' => Customer::STATUS_ACTIVE]) + ->count(); // to return customers in terms of arrays rather than `Customer` objects: $customers = Customer::find() - ->asArray() - ->all(); + ->asArray() + ->all(); // each element of $customers is an array of name-value pairs // to index the result by customer IDs: @@ -123,11 +123,11 @@ Batch query is also supported when working with Active Record. For example, ```php // fetch 10 customers at a time foreach (Customer::find()->batch(10) as $customers) { - // $customers is an array of 10 or fewer Customer objects + // $customers is an array of 10 or fewer Customer objects } // fetch 10 customers at a time and iterate them one by one foreach (Customer::find()->each(10) as $customer) { - // $customer is a Customer object + // $customer is a Customer object } // batch query with eager loading foreach (Customer::find()->with('orders')->each() as $customer) { @@ -232,20 +232,20 @@ information about the relation context and thus will only query for related reco ```php class Customer extends \yii\db\ActiveRecord { - public function getOrders() - { - // Customer has_many Order via Order.customer_id -> id - return $this->hasMany(Order::className(), ['customer_id' => 'id']); - } + public function getOrders() + { + // Customer has_many Order via Order.customer_id -> id + return $this->hasMany(Order::className(), ['customer_id' => 'id']); + } } class Order extends \yii\db\ActiveRecord { - // Order has_one Customer via Customer.id -> customer_id - public function getCustomer() - { - return $this->hasOne(Customer::className(), ['id' => 'customer_id']); - } + // Order has_one Customer via Customer.id -> customer_id + public function getCustomer() + { + return $this->hasOne(Customer::className(), ['id' => 'customer_id']); + } } ``` @@ -288,12 +288,12 @@ To do so, declare a `bigOrders` relation with the following getter method: ```php class Customer extends \yii\db\ActiveRecord { - public function getBigOrders($threshold = 100) - { - return $this->hasMany(Order::className(), ['customer_id' => 'id']) - ->where('subtotal > :threshold', [':threshold' => $threshold]) - ->orderBy('id'); - } + public function getBigOrders($threshold = 100) + { + return $this->hasMany(Order::className(), ['customer_id' => 'id']) + ->where('subtotal > :threshold', [':threshold' => $threshold]) + ->orderBy('id'); + } } ``` @@ -327,11 +327,11 @@ we can declare the `items` relation in the `Order` class like the following: ```php class Order extends \yii\db\ActiveRecord { - public function getItems() - { - return $this->hasMany(Item::className(), ['id' => 'item_id']) - ->viaTable('tbl_order_item', ['order_id' => 'id']); - } + public function getItems() + { + return $this->hasMany(Item::className(), ['id' => 'item_id']) + ->viaTable('tbl_order_item', ['order_id' => 'id']); + } } ``` @@ -342,16 +342,16 @@ instead of the pivot table name. For example, the above `items` relation can be ```php class Order extends \yii\db\ActiveRecord { - public function getOrderItems() - { - return $this->hasMany(OrderItem::className(), ['order_id' => 'id']); - } - - public function getItems() - { - return $this->hasMany(Item::className(), ['id' => 'item_id']) - ->via('orderItems'); - } + public function getOrderItems() + { + return $this->hasMany(OrderItem::className(), ['order_id' => 'id']); + } + + public function getItems() + { + return $this->hasMany(Item::className(), ['id' => 'item_id']) + ->via('orderItems'); + } } ``` @@ -381,9 +381,9 @@ Lazy loading is very convenient to use. However, it may suffer from a performanc $customers = Customer::find()->limit(100)->all(); foreach ($customers as $customer) { - // SQL executed: SELECT * FROM tbl_order WHERE customer_id=... - $orders = $customer->orders; - // ...handle $orders... + // SQL executed: SELECT * FROM tbl_order WHERE customer_id=... + $orders = $customer->orders; + // ...handle $orders... } ``` @@ -397,12 +397,12 @@ To solve the above performance problem, you can use the so-called *eager loading // SQL executed: SELECT * FROM tbl_customer LIMIT 100; // SELECT * FROM tbl_orders WHERE customer_id IN (1,2,...) $customers = Customer::find()->limit(100) - ->with('orders')->all(); + ->with('orders')->all(); foreach ($customers as $customer) { - // no SQL executed - $orders = $customer->orders; - // ...handle $orders... + // no SQL executed + $orders = $customer->orders; + // ...handle $orders... } ``` @@ -432,9 +432,9 @@ $orders = $customer->getOrders()->where('subtotal>100')->all(); // eager loading: SELECT * FROM tbl_customer LIMIT 100 // SELECT * FROM tbl_order WHERE customer_id IN (1,2,...) AND subtotal>100 $customers = Customer::find()->limit(100)->with([ - 'orders' => function($query) { - $query->andWhere('subtotal>100'); - }, + 'orders' => function($query) { + $query->andWhere('subtotal>100'); + }, ])->all(); ``` @@ -448,20 +448,20 @@ named `customer`: ```php class Customer extends ActiveRecord { - .... - public function getOrders() - { - return $this->hasMany(Order::className(), ['customer_id' => 'id']); - } + .... + public function getOrders() + { + return $this->hasMany(Order::className(), ['customer_id' => 'id']); + } } class Order extends ActiveRecord { - .... - public function getCustomer() - { - return $this->hasOne(Customer::className(), ['id' => 'customer_id']); - } + .... + public function getCustomer() + { + return $this->hasOne(Customer::className(), ['id' => 'customer_id']); + } } ``` @@ -476,9 +476,9 @@ $customer = Customer::find(1); // SELECT * FROM tbl_order WHERE customer_id=1 // SELECT * FROM tbl_customer WHERE id=1 if ($customer->orders[0]->customer === $customer) { - echo 'equal'; + echo 'equal'; } else { - echo 'not equal'; + echo 'not equal'; } ``` @@ -488,11 +488,11 @@ and the `orders` relations by calling the [[yii\db\ActiveQuery::inverseOf()|inve ```php class Customer extends ActiveRecord { - .... - public function getOrders() - { - return $this->hasMany(Order::className(), ['customer_id' => 'id'])->inverseOf('customer'); - } + .... + public function getOrders() + { + return $this->hasMany(Order::className(), ['customer_id' => 'id'])->inverseOf('customer'); + } } ``` @@ -504,9 +504,9 @@ $customer = Customer::find(1); // echoes "equal" // SELECT * FROM tbl_order WHERE customer_id=1 if ($customer->orders[0]->customer === $customer) { - echo 'equal'; + echo 'equal'; } else { - echo 'not equal'; + echo 'not equal'; } ``` @@ -519,9 +519,9 @@ eager loading: $customers = Customer::find()->with('orders')->all(); // echoes "equal" if ($customers[0]->orders[0]->customer === $customers[0]) { - echo 'equal'; + echo 'equal'; } else { - echo 'not equal'; + echo 'not equal'; } ``` @@ -555,10 +555,10 @@ and you may also join with sub-relations. For example, // join with multiple relations // find out the orders that contain books and are placed by customers who registered within the past 24 hours $orders = Order::find()->innerJoinWith([ - 'books', - 'customer' => function ($query) { - $query->where('tbl_customer.created_at > ' . (time() - 24 * 3600)); - } + 'books', + 'customer' => function ($query) { + $query->where('tbl_customer.created_at > ' . (time() - 24 * 3600)); + } ])->all(); // join with sub-relations: join with books and books' authors $orders = Order::find()->joinWith('books.author')->all(); @@ -603,10 +603,10 @@ This can be done by calling the [[yii\db\ActiveQuery::onCondition()]] method lik ```php class User extends ActiveRecord { - public function getBooks() - { - return $this->hasMany(Item::className(), ['owner_id' => 'id'])->onCondition(['category_id' => 1]); - } + public function getBooks() + { + return $this->hasMany(Item::className(), ['owner_id' => 'id'])->onCondition(['category_id' => 1]); + } } ``` @@ -713,11 +713,11 @@ use yii\db\ActiveQuery; class CommentQuery extends ActiveQuery { - public function active($state = true) - { - $this->andWhere(['active' => $state]); - return $this; - } + public function active($state = true) + { + $this->andWhere(['active' => $state]); + return $this; + } } ``` @@ -737,11 +737,11 @@ use yii\db\ActiveRecord; class Comment extends ActiveRecord { - public static function createQuery($config = []) - { - $config['modelClass'] = get_called_class(); - return new CommentQuery($config); - } + public static function createQuery($config = []) + { + $config['modelClass'] = get_called_class(); + return new CommentQuery($config); + } } ``` @@ -757,11 +757,11 @@ You can also use scopes when defining relations. For example, ```php class Post extends \yii\db\ActiveRecord { - public function getActiveComments() - { - return $this->hasMany(Comment::className(), ['post_id' => 'id'])->active(); + public function getActiveComments() + { + return $this->hasMany(Comment::className(), ['post_id' => 'id'])->active(); - } + } } ``` @@ -769,9 +769,9 @@ Or use the scopes on-the-fly when performing relational query: ```php $posts = Post::find()->with([ - 'comments' => function($q) { - $q->active(); - } + 'comments' => function($q) { + $q->active(); + } ])->all(); ``` @@ -788,7 +788,7 @@ and query like the following: */ class Comment extends ActiveRecord { - // ... + // ... } ``` @@ -799,7 +799,7 @@ class Comment extends ActiveRecord */ class CommentQuery extends ActiveQuery { - // ... + // ... } ``` @@ -811,8 +811,8 @@ applies to ALL queries. You can define a default scope easily by overriding [[yi ```php public static function createQuery($config = []) { - $config['modelClass'] = get_called_class(); - return (new ActiveQuery($config))->where(['deleted' => false]); + $config['modelClass'] = get_called_class(); + return (new ActiveQuery($config))->where(['deleted' => false]); } ``` @@ -839,22 +839,22 @@ Here these ways are (**DO NOT** use them unless you're sure what you are actuall ```php class Feature extends \yii\db\ActiveRecord { - // ... + // ... - public function getProduct() - { - return $this->hasOne(Product::className(), ['product_id' => 'id']); - } + public function getProduct() + { + return $this->hasOne(Product::className(), ['product_id' => 'id']); + } } class Product extends \yii\db\ActiveRecord { - // ... + // ... - public function getFeatures() - { - return $this->hasMany(Feature::className(), ['id' => 'product_id']); - } + public function getFeatures() + { + return $this->hasMany(Feature::className(), ['id' => 'product_id']); + } } ``` @@ -864,10 +864,10 @@ Overriding [[yii\db\ActiveRecord::save()|save()]] method: class ProductController extends \yii\web\Controller { - public function actionCreate() - { - // FIXME: TODO: WIP, TBD - } + public function actionCreate() + { + // FIXME: TODO: WIP, TBD + } } ``` @@ -876,10 +876,10 @@ Using transactions within controller layer: ```php class ProductController extends \yii\web\Controller { - public function actionCreate() - { - // FIXME: TODO: WIP, TBD - } + public function actionCreate() + { + // FIXME: TODO: WIP, TBD + } } ``` @@ -888,56 +888,56 @@ Instead of using these fragile methods you should consider using atomic scenario ```php class Feature extends \yii\db\ActiveRecord { - // ... - - public function getProduct() - { - return $this->hasOne(Product::className(), ['product_id' => 'id']); - } - - public function scenarios() - { - return [ - 'userCreates' => [ - 'attributes' => ['name', 'value'], - 'atomic' => [self::OP_INSERT], - ], - ]; - } + // ... + + public function getProduct() + { + return $this->hasOne(Product::className(), ['product_id' => 'id']); + } + + public function scenarios() + { + return [ + 'userCreates' => [ + 'attributes' => ['name', 'value'], + 'atomic' => [self::OP_INSERT], + ], + ]; + } } class Product extends \yii\db\ActiveRecord { - // ... - - public function getFeatures() - { - return $this->hasMany(Feature::className(), ['id' => 'product_id']); - } - - public function scenarios() - { - return [ - 'userCreates' => [ - 'attributes' => ['title', 'price'], - 'atomic' => [self::OP_INSERT], - ], - ]; - } - - public function afterValidate() - { - parent::afterValidate(); - // FIXME: TODO: WIP, TBD - } - - public function afterSave($insert) - { - parent::afterSave($insert); - if ($this->getScenario() === 'userCreates') { - // FIXME: TODO: WIP, TBD - } - } + // ... + + public function getFeatures() + { + return $this->hasMany(Feature::className(), ['id' => 'product_id']); + } + + public function scenarios() + { + return [ + 'userCreates' => [ + 'attributes' => ['title', 'price'], + 'atomic' => [self::OP_INSERT], + ], + ]; + } + + public function afterValidate() + { + parent::afterValidate(); + // FIXME: TODO: WIP, TBD + } + + public function afterSave($insert) + { + parent::afterSave($insert); + if ($this->getScenario() === 'userCreates') { + // FIXME: TODO: WIP, TBD + } + } } ``` @@ -946,10 +946,10 @@ Controller is very thin and neat: ```php class ProductController extends \yii\web\Controller { - public function actionCreate() - { - // FIXME: TODO: WIP, TBD - } + public function actionCreate() + { + // FIXME: TODO: WIP, TBD + } } ``` diff --git a/docs/guide/apps-advanced.md b/docs/guide/apps-advanced.md index 559a5e1..8e5907f 100644 --- a/docs/guide/apps-advanced.md +++ b/docs/guide/apps-advanced.md @@ -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 + ], + + ], ]; ``` diff --git a/docs/guide/apps-basic.md b/docs/guide/apps-basic.md index f7e4061..809e5a2 100644 --- a/docs/guide/apps-basic.md +++ b/docs/guide/apps-basic.md @@ -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" + ] + } } ``` diff --git a/docs/guide/assets.md b/docs/guide/assets.md index ca3b07c..4f2c784 100644 --- a/docs/guide/assets.md +++ b/docs/guide/assets.md @@ -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}'], + ], + ], + ], ], ``` diff --git a/docs/guide/authentication.md b/docs/guide/authentication.md index f43ff0d..df2ea7b 100644 --- a/docs/guide/authentication.md +++ b/docs/guide/authentication.md @@ -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; } ``` diff --git a/docs/guide/authorization.md b/docs/guide/authorization.md index 927a5d8..4f7261d 100644 --- a/docs/guide/authorization.md +++ b/docs/guide/authorization.md @@ -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`. diff --git a/docs/guide/behaviors.md b/docs/guide/behaviors.md index 73e187d..48b7691 100644 --- a/docs/guide/behaviors.md +++ b/docs/guide/behaviors.md @@ -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 + } } ``` diff --git a/docs/guide/bootstrap-widgets.md b/docs/guide/bootstrap-widgets.md index d1cecba..85cefa4 100644 --- a/docs/guide/bootstrap-widgets.md +++ b/docs/guide/bootstrap-widgets.md @@ -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 ]; ``` diff --git a/docs/guide/caching.md b/docs/guide/caching.md index b7ee784..a28da1a 100644 --- a/docs/guide/caching.md +++ b/docs/guide/caching.md @@ -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; } ``` diff --git a/docs/guide/configuration.md b/docs/guide/configuration.md index 9e57354..17ddf5c 100644 --- a/docs/guide/configuration.md +++ b/docs/guide/configuration.md @@ -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'], + ], + ], + ], + ], + // ... ]; ``` diff --git a/docs/guide/console-fixture.md b/docs/guide/console-fixture.md index 1ddf7a3..0c3e456 100644 --- a/docs/guide/console-fixture.md +++ b/docs/guide/console-fixture.md @@ -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' + ], ], ] ``` diff --git a/docs/guide/console-migrate.md b/docs/guide/console-migrate.md index 5eba6c5..6c80cad 100644 --- a/docs/guide/console-migrate.md +++ b/docs/guide/console-migrate.md @@ -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'); + } } ``` diff --git a/docs/guide/console.md b/docs/guide/console.md index 9be0bd2..d0841fd 100644 --- a/docs/guide/console.md +++ b/docs/guide/console.md @@ -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; } ``` diff --git a/docs/guide/controller.md b/docs/guide/controller.md index d6ff852..5be113a 100644 --- a/docs/guide/controller.md +++ b/docs/guide/controller.md @@ -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]); + } } ``` diff --git a/docs/guide/data-grid.md b/docs/guide/data-grid.md index 36c11af..33281b4 100644 --- a/docs/guide/data-grid.md +++ b/docs/guide/data-grid.md @@ -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 diff --git a/docs/guide/data-providers.md b/docs/guide/data-providers.md index 5977450..5352ac2 100644 --- a/docs/guide/data-providers.md +++ b/docs/guide/data-providers.md @@ -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 diff --git a/docs/guide/data-widgets.md b/docs/guide/data-widgets.md index 346aff6..b6876e4 100644 --- a/docs/guide/data-widgets.md +++ b/docs/guide/data-widgets.md @@ -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, + ], + ], ]); ``` diff --git a/docs/guide/database-basics.md b/docs/guide/database-basics.md index 9e0659e..d960782 100644 --- a/docs/guide/database-basics.md +++ b/docs/guide/database-basics.md @@ -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', ]); ``` diff --git a/docs/guide/error.md b/docs/guide/error.md index c27af96..d8e71fd 100644 --- a/docs/guide/error.md +++ b/docs/guide/error.md @@ -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 diff --git a/docs/guide/events.md b/docs/guide/events.md index 94c5e9a..1d240e6 100644 --- a/docs/guide/events.md +++ b/docs/guide/events.md @@ -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.'); }); ``` diff --git a/docs/guide/form.md b/docs/guide/form.md index 05e28b8..fef4719 100644 --- a/docs/guide/form.md +++ b/docs/guide/form.md @@ -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(); diff --git a/docs/guide/gii.md b/docs/guide/gii.md index 1b6a5c4..916a134 100644 --- a/docs/guide/gii.md +++ b/docs/guide/gii.md @@ -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'], + ]; } ``` diff --git a/docs/guide/i18n.md b/docs/guide/i18n.md index 6b0bc92..02ef142 100644 --- a/docs/guide/i18n.md +++ b/docs/guide/i18n.md @@ -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', + ], + ], ]; ``` diff --git a/docs/guide/logging.md b/docs/guide/logging.md index 81da17a..ad55cc4 100644 --- a/docs/guide/logging.md +++ b/docs/guide/logging.md @@ -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'); ``` diff --git a/docs/guide/model.md b/docs/guide/model.md index e2302b3..7608acf 100644 --- a/docs/guide/model.md +++ b/docs/guide/model.md @@ -50,8 +50,8 @@ class member variables. In the following example, the `LoginForm` model class de // LoginForm has two attributes: username and password class LoginForm extends \yii\base\Model { - public $username; - public $password; + public $username; + public $password; } ``` @@ -77,16 +77,16 @@ In many cases, [[yii\base\Model::generateAttributeLabel()]] will generate reason // LoginForm has two attributes: username and password class LoginForm extends \yii\base\Model { - public $username; - public $password; - - public function attributeLabels() - { - return [ - 'username' => 'Your name', - 'password' => 'Your password', - ]; - } + public $username; + public $password; + + public function attributeLabels() + { + return [ + 'username' => 'Your name', + 'password' => 'Your password', + ]; + } } ``` @@ -111,13 +111,13 @@ names and whose values are lists of attributes that should be active in that sce ```php class User extends \yii\db\ActiveRecord { - public function scenarios() - { - return [ - 'login' => ['username', 'password'], - 'register' => ['username', 'email', 'password'], - ]; - } + public function scenarios() + { + return [ + 'login' => ['username', 'password'], + 'register' => ['username', 'email', 'password'], + ]; + } } ``` @@ -128,13 +128,13 @@ If you want to keep the default scenario available besides your own scenarios, u ```php class User extends \yii\db\ActiveRecord { - public function scenarios() - { - $scenarios = parent::scenarios(); - $scenarios['login'] = ['username', 'password']; - $scenarios['register'] = ['username', 'email', 'password']; - return $scenarios; - } + public function scenarios() + { + $scenarios = parent::scenarios(); + $scenarios['login'] = ['username', 'password']; + $scenarios['register'] = ['username', 'email', 'password']; + return $scenarios; + } } ``` @@ -154,21 +154,21 @@ Identifying the active model scenario can be done using one of the following app ```php class EmployeeController extends \yii\web\Controller { - public function actionCreate($id = null) - { - // first way - $employee = new Employee(['scenario' => 'managementPanel']); - - // second way - $employee = new Employee(); - $employee->scenario = 'managementPanel'; - - // third way - $employee = Employee::find()->where('id = :id', [':id' => $id])->one(); - if ($employee !== null) { - $employee->scenario = 'managementPanel'; - } - } + public function actionCreate($id = null) + { + // first way + $employee = new Employee(['scenario' => 'managementPanel']); + + // second way + $employee = new Employee(); + $employee->scenario = 'managementPanel'; + + // third way + $employee = Employee::find()->where('id = :id', [':id' => $id])->one(); + if ($employee !== null) { + $employee->scenario = 'managementPanel'; + } + } } ``` @@ -191,10 +191,10 @@ $model = new LoginForm(); $model->username = $_POST['username']; $model->password = $_POST['password']; if ($model->validate()) { - // ... login the user ... + // ... login the user ... } else { - $errors = $model->getErrors(); - // ... display the errors to the end user ... + $errors = $model->getErrors(); + // ... display the errors to the end user ... } ``` @@ -204,16 +204,16 @@ instance of a [[yii\validators\Validator]] child class, or an array with the fol ```php [ - ['attribute1', 'attribute2', ...], - 'validator class or alias', - // specifies in which scenario(s) this rule is active. - // if not given, it means it is active in all scenarios - 'on' => ['scenario1', 'scenario2', ...], - // the following name-value pairs will be used - // to initialize the validator properties - 'property1' => 'value1', - 'property2' => 'value2', - // ... + ['attribute1', 'attribute2', ...], + 'validator class or alias', + // specifies in which scenario(s) this rule is active. + // if not given, it means it is active in all scenarios + 'on' => ['scenario1', 'scenario2', ...], + // the following name-value pairs will be used + // to initialize the validator properties + 'property1' => 'value1', + 'property2' => 'value2', + // ... ] ``` @@ -236,18 +236,18 @@ Here is an example implementation of a validator validating the age of a user: ```php public function validateAge($attribute, $params) { - $value = $this->$attribute; - if (strtotime($value) > strtotime('now - ' . $params['min'] . ' years')) { - $this->addError($attribute, 'You must be at least ' . $params['min'] . ' years old to register for this service.'); - } + $value = $this->$attribute; + if (strtotime($value) > strtotime('now - ' . $params['min'] . ' years')) { + $this->addError($attribute, 'You must be at least ' . $params['min'] . ' years old to register for this service.'); + } } public function rules() { - return [ - // ... - [['birthdate'], 'validateAge', 'params' => ['min' => '12']], - ]; + return [ + // ... + [['birthdate'], 'validateAge', 'params' => ['min' => '12']], + ]; } ``` @@ -258,7 +258,7 @@ for example the [[yii\validators\InlineValidator::$skipOnEmpty|skipOnEmpty]] pro [['birthdate'], 'validateAge', 'params' => ['min' => '12'], 'skipOnEmpty' => false], ``` -### conditional validation +### Conditional validation To validate attributes only when certain conditions apply, e.g. the validation of one field depends on the value of another field you can use [[yii\validators\Validator::when|the `when` property]] @@ -297,8 +297,8 @@ as an array of name-value pairs. ```php $post = Post::find(42); if ($post) { - $attributes = $post->attributes; - var_dump($attributes); + $attributes = $post->attributes; + var_dump($attributes); } ``` @@ -307,8 +307,8 @@ Using the same `attributes` property you can massively assign data from associat ```php $post = new Post(); $attributes = [ - 'title' => 'Massive assignment example', - 'content' => 'Never allow assigning attributes that are not meant to be assigned.', + 'title' => 'Massive assignment example', + 'content' => 'Never allow assigning attributes that are not meant to be assigned.', ]; $post->attributes = $attributes; var_dump($attributes); @@ -329,31 +329,31 @@ assignment is described in `scenarios` method: ```php class User extends ActiveRecord { - public function rules() - { - return [ - // rule applied when corresponding field is "safe" - ['username', 'string', 'length' => [4, 32]], - ['first_name', 'string', 'max' => 128], - ['password', 'required'], - - // rule applied when scenario is "signup" no matter if field is "safe" or not - ['hashcode', 'check', 'on' => 'signup'], - ]; - } - - public function scenarios() - { - return [ - // on signup allow mass assignment of username - 'signup' => ['username', 'password'], - 'update' => ['username', 'first_name'], - ]; - } + public function rules() + { + return [ + // rule applied when corresponding field is "safe" + ['username', 'string', 'length' => [4, 32]], + ['first_name', 'string', 'max' => 128], + ['password', 'required'], + + // rule applied when scenario is "signup" no matter if field is "safe" or not + ['hashcode', 'check', 'on' => 'signup'], + ]; + } + + public function scenarios() + { + return [ + // on signup allow mass assignment of username + 'signup' => ['username', 'password'], + 'update' => ['username', 'first_name'], + ]; + } } ``` -For the code above mass assignment will be allowed stsrictly according to `scenarios()`: +For the code above mass assignment will be allowed strictly according to `scenarios()`: ```php $user = User::find(42); @@ -368,9 +368,9 @@ Will give you empty array because there's no default scenario defined in our `sc $user = User::find(42); $user->scenario = 'signup'; $data = [ - 'username' => 'samdark', - 'password' => '123', - 'hashcode' => 'test', + 'username' => 'samdark', + 'password' => '123', + 'hashcode' => 'test', ]; $user->attributes = $data; print_r($user->attributes); @@ -380,10 +380,10 @@ Will give you the following: ```php array( - 'username' => 'samdark', - 'first_name' => null, - 'password' => '123', - 'hashcode' => null, // it's not defined in scenarios method + 'username' => 'samdark', + 'first_name' => null, + 'password' => '123', + 'hashcode' => null, // it's not defined in scenarios method ) ``` @@ -392,14 +392,14 @@ In case of not defined `scenarios` method like the following: ```php class User extends ActiveRecord { - public function rules() - { - return [ - ['username', 'string', 'length' => [4, 32]], - ['first_name', 'string', 'max' => 128], - ['password', 'required'], - ]; - } + public function rules() + { + return [ + ['username', 'string', 'length' => [4, 32]], + ['first_name', 'string', 'max' => 128], + ['password', 'required'], + ]; + } } ``` @@ -408,10 +408,10 @@ The code above assumes default scenario so mass assignment will be available for ```php $user = User::find(42); $data = [ - 'username' => 'samdark', - 'first_name' => 'Alexander', - 'last_name' => 'Makarov', - 'password' => '123', + 'username' => 'samdark', + 'first_name' => 'Alexander', + 'last_name' => 'Makarov', + 'password' => '123', ]; $user->attributes = $data; print_r($user->attributes); @@ -421,9 +421,9 @@ Will give you the following: ```php array( - 'username' => 'samdark', - 'first_name' => 'Alexander', - 'password' => '123', + 'username' => 'samdark', + 'first_name' => 'Alexander', + 'password' => '123', ) ``` @@ -432,21 +432,21 @@ If you want some fields to be unsafe for default scenario: ```php class User extends ActiveRecord { - function rules() - { - return [ - ['username', 'string', 'length' => [4, 32]], - ['first_name', 'string', 'max' => 128], - ['password', 'required'], - ]; - } - - public function scenarios() - { - return [ - self::SCENARIO_DEFAULT => ['username', 'first_name', '!password'] - ]; - } + function rules() + { + return [ + ['username', 'string', 'length' => [4, 32]], + ['first_name', 'string', 'max' => 128], + ['password', 'required'], + ]; + } + + public function scenarios() + { + return [ + self::SCENARIO_DEFAULT => ['username', 'first_name', '!password'] + ]; + } } ``` @@ -455,9 +455,9 @@ Mass assignment is still available by default: ```php $user = User::find(42); $data = [ - 'username' => 'samdark', - 'first_name' => 'Alexander', - 'password' => '123', + 'username' => 'samdark', + 'first_name' => 'Alexander', + 'password' => '123', ]; $user->attributes = $data; print_r($user->attributes); @@ -467,9 +467,9 @@ The code above gives you: ```php array( - 'username' => 'samdark', - 'first_name' => 'Alexander', - 'password' => null, // because of ! before field name in scenarios + 'username' => 'samdark', + 'first_name' => 'Alexander', + 'password' => null, // because of ! before field name in scenarios ) ``` diff --git a/docs/guide/module-debug.md b/docs/guide/module-debug.md index 916101c..95202ea 100644 --- a/docs/guide/module-debug.md +++ b/docs/guide/module-debug.md @@ -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'], + ], + ]; // ... ``` diff --git a/docs/guide/performance.md b/docs/guide/performance.md index 9eb8ccf..c659a85 100644 --- a/docs/guide/performance.md +++ b/docs/guide/performance.md @@ -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>"; } ``` diff --git a/docs/guide/query-builder.md b/docs/guide/query-builder.md index a268311..1ee352f 100644 --- a/docs/guide/query-builder.md +++ b/docs/guide/query-builder.md @@ -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) { diff --git a/docs/guide/security.md b/docs/guide/security.md index 6f12e33..4c2433a 100644 --- a/docs/guide/security.md +++ b/docs/guide/security.md @@ -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 } ``` diff --git a/docs/guide/template.md b/docs/guide/template.md index 9d5d372..760c5c9 100644 --- a/docs/guide/template.md +++ b/docs/guide/template.md @@ -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', ], ``` diff --git a/docs/guide/test-fixture.md b/docs/guide/test-fixture.md index 70f391d..e7c1657 100644 --- a/docs/guide/test-fixture.md +++ b/docs/guide/test-fixture.md @@ -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 ``` diff --git a/docs/guide/theming.md b/docs/guide/theming.md index 037e70c..70c7d52 100644 --- a/docs/guide/theming.md +++ b/docs/guide/theming.md @@ -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', + ], ] ``` diff --git a/docs/guide/upgrade-from-v1.md b/docs/guide/upgrade-from-v1.md index a3b7b47..187abc1 100644 --- a/docs/guide/upgrade-from-v1.md +++ b/docs/guide/upgrade-from-v1.md @@ -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], ] ``` diff --git a/docs/guide/url.md b/docs/guide/url.md index a3058b5..f0c8b9d 100644 --- a/docs/guide/url.md +++ b/docs/guide/url.md @@ -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 + } } ``` diff --git a/docs/guide/using-3rd-party-libraries.md b/docs/guide/using-3rd-party-libraries.md index b5e95c0..71fa580 100644 --- a/docs/guide/using-3rd-party-libraries.md +++ b/docs/guide/using-3rd-party-libraries.md @@ -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 +``` diff --git a/docs/guide/validation.md b/docs/guide/validation.md index 1f517b2..cbddd5d 100644 --- a/docs/guide/validation.md +++ b/docs/guide/validation.md @@ -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; } ``` diff --git a/docs/guide/view.md b/docs/guide/view.md index a78e661..ca8be49 100644 --- a/docs/guide/view.md +++ b/docs/guide/view.md @@ -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', + ], + // ... + ], ]; ```