Различия

Показаны различия между двумя версиями страницы.

Ссылка на это сравнение

Предыдущая версия справа и слева Предыдущая версия
Следующая версия
Предыдущая версия
yii2:docs [2017/01/04 14:03] – [Таблица] mirocowyii2:docs [2019/04/18 13:17] (текущий) – [Active Record] mirocow
Строка 1: Строка 1:
 {{tag>Yii2 jquery ajax csrfToken url html view urlmanager activerecord docs}} {{tag>Yii2 jquery ajax csrfToken url html view urlmanager activerecord docs}}
  
-========= Документация по Yii 2 Framework =========+====== Документация по Yii 2 Framework ======
  
- +===== Configuration =====
- +
-====== Configuration ======+
  
 <code php> <code php>
Строка 36: Строка 34:
 ]; ];
 </code> </code>
 +===== URL Management =====
  
-======== PHPUnit ======== +<code php> 
- +echo \Yii::$app->urlManager->createUrl(['site/page', 'id' => 'about']); 
-добавить в конфигуратор композера composer.json +// /index.php/site/page/id/about/ 
-<code+echo \Yii::$app->urlManager->createUrl(['date-time/fast-forward', 'id' => 105]) 
-+// /index.php?r=date-time/fast-forward&id=105 
-    "require-dev"{ +echo \Yii::$app->urlManager->createAbsoluteUrl('blog/post/index'); 
-        "phpunit/phpunit""3.7.*" +// http://www.example.com/index.php/blog/post/index/
-    } +
-}+
 </code> </code>
- 
-    * php composer.phar update 
-    * php vendor/bin/phpunit vendor/yiisoft/yii2/yii/test/ 
- 
-======== URL Management ======== 
  
 <code php> <code php>
Строка 66: Строка 58:
 </code> </code>
  
-====== Request ====== +==== Конфигурация ====
- +
-===== GET =====+
  
 <code php> <code php>
-Yii::$app->request->get(); +<?php 
-Yii::$app->request->getQueryParams(); +return [ 
-Yii::$app->request->getQueryParam('File'); +    // ... 
-Yii::$app->request->get('File'); +    'components' => [ 
-</code> +        'urlManager=> [ 
-===== POST ===== +            'enablePrettyUrl' => true, 
- +            'showScriptName' => false, 
-<code php+            'enableStrictParsing' => true, 
-Yii::$app->request->post(); +            'suffix' ='.html', 
-Yii::$app->request->getBodyParams(); +            'rules' => [ 
-Yii::$app->request->getBodyParam('File'); +                '<action:(login|logout|about)>' => 'site/<action>', 
-Yii::$app->request->post('File'); +     
-</code> +                // ... 
-====== View ====== +     
- +                ['class' => 'app\components\CarUrlRule''connectionID' => 'db', ...], 
-===== Blocks ===== +            ],   
- +        ],
-====== CSS ====== +
- +
-<code php> +
-$this->registerCssFile(); +
-</code+
-====== JS ====== +
- +
-==== Вставка кода внутри представления ==== +
- +
-В примере производится вставка JS кода из assets c применением переменной в скрипте JS_FABRIC_CAR_URL +
-<code php+
-$this Yii::$app->view; +
-</code> +
-   +
-<code php> +
-<?php  +
-$this->registerJs('var JS_FABRIC_CAR_URL "' . Html::url(['/core/ajax/fabric-car']) . '";', View::POS_HEAD, 'js-fabric-car-url'); +
-$publish Yii::$app->assetManager->publish(Yii::getAlias('@app/modules/core/assets/js')); +
-$this->registerJsFile($publish[1] . '/block-select-car.js', [yii\web\JqueryAsset::className()], ['position'=>View::POS_END]); +
-?>  +
-</code+
- +
-==== assetManager ==== +
- +
-<code php> +
-'components' => +
-    'assetManager=> [ +
-        'class' => 'yii\web\AssetManager', +
-        'forceCopy' => true         +
     ],     ],
-],+];
 </code> </code>
 +==== Url ====
  
-  * forceCopy - Включает постоянное обновление асетов +=== yii\helpers\Url::toRoute ===
-==== Добавление csrfToken в Ajax запрос (Yii2) ==== +
- +
-=== через ajaxSetup === +
- +
- +
-<code php> +
-$js_global_variables = ' +
-$.ajaxSetup({ +
-        data: ' . \yii\helpers\Json::encode([ +
-            \yii::$app->request->csrfParam => \yii::$app->request->csrfToken, +
-        ]) . ' +
-    });' . PHP_EOL; +
-$this->registerJs($js_global_variables, yii\web\View::POS_HEAD, 'js_global_variables'); +
-</code> +
- +
-=== или через header === +
- +
- +
-<code php> +
-$js_global_variables = ' +
-$.ajaxPrefilter(function( options ) { +
-    if ( !options.beforeSend) { +
-        options.beforeSend = function (xhr) {  +
-            xhr.setRequestHeader("HTTP_X_CSRF_TOKEN", ' . \yii::$app->request->csrfToken .'); +
-        } +
-    } +
-});' . PHP_EOL; +
-$this->registerJs($js_global_variables, yii\web\View::POS_HEAD, 'js_global_variables'); +
-</code> +
- +
-=== или через JQuery === +
- +
- +
-<code js> +
-      $.ajax({ +
-        url: 'http://site?controller/action', +
-        type: 'post', +
-        data: {payload: payload, _csrf: yii.getCsrfToken()},         +
-        dataType: 'json', +
-      }).success(function(response) { +
-      }); +
-</code> +
-====== Image ====== +
- +
- +
-====== yii\helpers\Url::toRoute ======+
  
 <code php> <code php>
Строка 183: Строка 99:
 </code> </code>
  
-====== yii\helpers\Url::to ======+=== yii\helpers\Url::to ===
  
 <code php> <code php>
Строка 213: Строка 129:
 Примеры использоватия можно глянуть в тестах https://github.com/yiisoft/yii2/blob/master/tests/unit/framework/helpers/UrlTest.php Примеры использоватия можно глянуть в тестах https://github.com/yiisoft/yii2/blob/master/tests/unit/framework/helpers/UrlTest.php
  
-====== yii\helpers\Html::url (old) ======+=== yii\helpers\Html::url (old) ===
  
 <code php> <code php>
Строка 233: Строка 149:
 Примеры использоватия можно глянуть в тестах https://github.com/yiisoft/yii2/blob/master/tests/unit/framework/helpers/UrlTest.php Примеры использоватия можно глянуть в тестах https://github.com/yiisoft/yii2/blob/master/tests/unit/framework/helpers/UrlTest.php
  
-====== createUrl ======+==== createUrl ====
  
 <code php> <code php>
Строка 248: Строка 164:
 echo $this->createUrl('/site/index', $schema = null); // absolute route no matter what controller is making this call echo $this->createUrl('/site/index', $schema = null); // absolute route no matter what controller is making this call
 </code> </code>
-====== createAbsoluteUrl (old) ======+ 
 +=== createAbsoluteUrl (old) ===
  
 Усли $this - это yii\web\Controller Усли $this - это yii\web\Controller
Строка 260: Строка 177:
 </code> </code>
  
-вместо старых методов нада использовать **yii\helpers::toRoute**+вместо старых методов надо использовать **yii\helpers::toRoute**
  
 Усли $this - это yii\web\Controller Усли $this - это yii\web\Controller
Строка 270: Строка 187:
 </code> </code>
  
-вместо старых методов нада использовать **yii\helpers::toRoute**+вместо старых методов надо использовать **yii\helpers::toRoute**
  
-==== urlManager ====+==== Request ====
  
 +=== GET ===
  
 <code php> <code php>
-echo \Yii::$app->urlManager->createUrl(['site/page', 'id' => 'about']); +Yii::$app->request->get(); 
-// /index.php/site/page/id/about/ +Yii::$app->request->getQueryParams(); 
-echo \Yii::$app->urlManager->createUrl(['date-time/fast-forward''id' => 105]+Yii::$app->request->getQueryParam('File'); 
-// /index.php?r=date-time/fast-forward&id=105 +Yii::$app->request->get('File');
-echo \Yii::$app->urlManager->createAbsoluteUrl('blog/post/index'); +
-// http://www.example.com/index.php/blog/post/index/+
 </code> </code>
  
-== Custom ==+=== POST ===
  
 <code php> <code php>
-<?php +Yii::$app->request->post(); 
-return [ +Yii::$app->request->getBodyParams(); 
-    // ... +Yii::$app->request->getBodyParam('File'); 
-    'components=> [ +Yii::$app->request->post('File'); 
-        'urlManager' => [ +</code> 
-            'enablePrettyUrl' => true, + 
-            'showScriptName' => false, +===== View ===== 
-            'enableStrictParsing' => true, + 
-            'suffix' ='.html', +==== CSS ==== 
-            'rules' => [ + 
-                '<action:(login|logout|about)>' => 'site/<action>', +<code php
-     +$this->registerCssFile(); 
-                // ... +</code> 
-     + 
-                ['class' => 'app\components\CarUrlRule''connectionID' => 'db', ...], +==== JS ==== 
-            ],   + 
-        ],+<code php
 +$this->registerJsFile(); 
 +</code> 
 + 
 +=== Вставка кода внутри представления === 
 + 
 +В примере производится вставка JS кода из assets c применением переменной в скрипте JS_FABRIC_CAR_URL 
 +<code php
 +$this Yii::$app->view; 
 +</code> 
 +   
 +<code php> 
 +<?php  
 +$this->registerJs('var JS_FABRIC_CAR_URL "' . Html::url(['/core/ajax/fabric-car']) . '";', View::POS_HEAD, 'js-fabric-car-url'); 
 +$publish Yii::$app->assetManager->publish(Yii::getAlias('@app/modules/core/assets/js')); 
 +$this->registerJsFile($publish[1] . '/block-select-car.js', [yii\web\JqueryAsset::className()], ['position'=>View::POS_END]); 
 +?>  
 +</code
 + 
 +==== assetManager ==== 
 + 
 +<code php> 
 +'components' => 
 +    'assetManager=> [ 
 +        'class' => 'yii\web\AssetManager', 
 +        'forceCopy' => true         
     ],     ],
-];+],
 </code> </code>
  
-====== Controller ======+  * forceCopy - Включает постоянное обновление асетов
  
-===== Как программно вызвать контроллер? =====+=== через ajaxSetup ==
 + 
 +Добавление csrfToken в Ajax запрос (Yii2)
  
 <code php> <code php>
-$className = 'backend\controllers\SiteController'; +$js_global_variables = ' 
-$controller Yii::createObject($className, [$id, $this]);+$.ajaxSetup({ 
 +        data: ' . \yii\helpers\Json::encode([ 
 +            \yii::$app->request->csrfParam => \yii::$app->request->csrfToken, 
 +        ]) . ' 
 +    });' . PHP_EOL; 
 +$this->registerJs($js_global_variables, yii\web\View::POS_HEAD, 'js_global_variables');
 </code> </code>
-====== yii\helpers\Html (old) ======+ 
 +или через header
  
 <code php> <code php>
-// ['label' => 'Добавление', 'url' => ['/admin/user/create']] +$js_global_variables = ' 
-Html::a("Log in here", ["user/reset", "hash" => $hash, "sid" =$sid]); +$.ajaxPrefilter(function( options ) { 
-Html::url(["user/reset""hash" => $hash, "sid" => $sid]);+    if ( !options.beforeSend) { 
 +        options.beforeSend function (xhr) {  
 +            xhr.setRequestHeader("HTTP_X_CSRF_TOKEN", ' . \yii::$app->request->csrfToken .'); 
 +        } 
 +    } 
 +});' . PHP_EOL; 
 +$this->registerJs($js_global_variables, yii\web\View::POS_HEAD'js_global_variables');
 </code> </code>
  
-**Подробно** https://github.com/yiisoft/yii2/blob/master/docs/guide/url.md+или через JQuery 
 + 
 +<code js> 
 +      $.ajax({ 
 +        url: 'http://site?controller/action', 
 +        type: 'post', 
 +        data: {payload: payload, _csrf: yii.getCsrfToken()},         
 +        dataType: 'json', 
 +      }).success(function(response) { 
 +      }); 
 +</code> 
 + 
 +==== Form ==== 
 + 
 +  * [[yii2:form|ActiveForm]] 
 +  * [[yii2:form|HTML]]    
 + 
 +**Подробно** https://github.com/yiisoft/yii2/blob/master/docs/guide/form.md
  
-======== Ajax ========+===== Ajax =====
  
   * [[yii2:Ajax|Active Form Ajax Validation]]   * [[yii2:Ajax|Active Form Ajax Validation]]
   * [[yii2:Ajax:select|Зависимый select от другого select'а]]   * [[yii2:Ajax:select|Зависимый select от другого select'а]]
  
-===== Pjax =====+==== Pjax ====
  
 <code php> <code php>
Строка 382: Строка 354:
 <?php Pjax::end(); ?> <?php Pjax::end(); ?>
 </code> </code>
-======== User ======== 
  
-====== RBAC ======+===== Виджеты / Widgets =====
  
-  * [[yii2:user:rbac|RBAC]]+  * [[yii2:widgets:masked-input|]] - http://demos.krajee.com/masked-input
  
-**Подробно** https://github.com/yiisoft/yii2/blob/master/docs/guide/authorization.md +===== Model / AR / DAO / Запросы к БД ===== 
-======== Access ========+ 
 +Как получить модель из модуля
  
 <code php> <code php>
-    'access' => [ +        $user    Yii::$app->getModule("user")->model("User", ["scenario" => "register"]); 
-            'class' => \yii\web\AccessControl::className()+        $profile = Yii::$app->getModule("user")->model("Profile");
-            'rules' =+
-                    [ +
-                            'actions' => ['index'], +
-                            'allow' => false, +
-                            'roles' => ['?'], +
-                    ], +
-                    [ +
-                            'actions' => ['index', 'update','view','create','delete']+
-                            'allow' => true, +
-                            'matchCallback' => function({ +
-                            return \Yii::$app->user->identity->role <\Yii::$app->user->identity->MANAGER                    +
-                            } +
-                    ], +
-            ], +
-    ],  +
 </code> </code>
  
 +==== Active Record ====
  
 +<code php>
 +class Post extends ActiveRecord
 +{
 +    public function getCreator()
 +    {
 +        return $this->hasOne('User', ['id' => 'user_id']);
 +    }
 +    public function getComments()
 +    {
 +        return $this->hasMany('Comment', ['post_id' => 'id']);
 +    }
 +    public function getTrustComments($isTrust = true)
 +    {
 +        return $this->hasMany('Comment', ['post_id' => 'id'])
 +            ->where('status = :status', [
 +                     ':status' => $isTrust ? self::TRUST : self::UNTRUST,
 +              ])
 +            ->orderBy('id');
 +    }
 +}
 +</code>
  
 +<code php>
 +        $price = PriceItem::find()
 +            ->select(['price', 'create_time' => 'DATE_FORMAT(create_time, "%d.%m.%Y")'])
 +            ->where(['and', 
 +                ['price_list_form_id' => $price_list_form_ids], 
 +                ['>', 'create_time', '2015.01.01']
 +        ])->orderBy(['price' => SORT_ASC])->asArray()->one();
 +</code>
  
-======== Model ========+<code php> 
 +// we receive an ActiveQuery instance 
 +$query Post::find(); 
 +  
 +// all posts 
 +$posts $query->all(); 
 +  
 +// looking for all the posts with a condition 
 +$posts $query 
 +    ->where(array('status' => Post::DRAFT)) 
 +    ->orderBy('time'
 +    ->all(); 
 +  
 +// looking for a post  
 +$post $query 
 +   ->where(['id' => 10, 'status' => Post::READ]) 
 +   ->one(); 
 +  
 +// or easier: "where" condition can be transmitted directly to the factory method 
 +$post Post::find(['id' => 10, 'status' => Post::READ]); 
 +  
 +// having transmitted to the factory method not a massive, but a number equivalent to the primary key search  
 +$post Post::find(10) 
 +   ->where(['status' => Post::READ]) 
 +   ->one(); 
 +  
 +// we index the result to a necessary attribute 
 +$posts $query->indexBy('title')->all(); 
 +  
 +// the result as an array 
 +$posts $query->asArray()->all(); 
 +</code>
  
-===== modules/user =====+<code php> 
 +User::find()->where(['and', ['phone_number' => $phone], ['<>', 'id', $user->id] ])->exists(); 
 +User::find()->where(['or', ['phone_number' => $phone], ['=', 'id', $user->id] ])->exists(); 
 +</code> 
 + 
 +=== Ключи в эллементах коллекции AR ===
  
 <code php> <code php>
-        $user    Yii::$app->getModule("user")->model("User", ["scenario" => "register"]); +$query SparesCategory::find()->where(['parent_id' => 0]); 
-        $profile = Yii::$app->getModule("user")->model("Profile");+$query->indexBy = function($row){ // Ключ в который будет помещена возвращаемая модель 
 +    return $row->id; 
 +}; 
 +$categories = $query->all(); 
 +</code>
  
-        if($user->load($_POST)){ +<code php> 
-           if ($user->save()) { +        $quey = CarMark::find()->indexBy(function($row){ 
-       $profile->user_id = $user->id+            return $row->id; 
-                 $profile->save(false); +        })->all()
-                 +</code> 
 + 
 +=== Создание модели из возвращаемы данных Command (с помощью populateRecord()) === 
 + 
 +<code php> 
 +        $sql = "SELECT * FROM `tbl_spares_category` c 
 +            LEFT JOIN tbl_form_spares_category fc ON fc.category_id = c.id 
 +            WHERE fc.form_id = :form_id AND fc.category_id = :category_id"; 
 +        $select_marks = Yii::$app->db->createCommand($sql,
 +            ':form_id' =$form_id, 
 +            ':category_id' => $category_id, 
 +        ])->queryAll()
 +   
 +        foreach($marks as $row){ 
 +             
 +            // Only yii2 alpha 
 +            //$mark = SparesCategoryForm::create($row); 
 +           
 +            $mark = new SparesCategoryForm; 
 +            SparesCategoryForm::populateRecord($mark, $row); 
 +             
 +   
 +            if(isset($mark->id)){ 
 +   
 +              // do somethig 
 +   
 +            }
         }         }
 </code> </code>
  
-  * https://github.com/yiisoft/yii2/blob/master/docs/guide/model.md +  * [[Activedataprovider|Activedataprovider]] 
-  * https://github.com/johnitvn/yii2-user-plus +  * [[SqlDataProvider|SqlDataProvider]] 
-====== Join ======+  * [[ArrayDataProvider|ArrayDataProvider]] 
 +==== Join ====
  
-==== with() ====+=== with() ===
  
 Не делает SQL JOIN(), применяется не только в реляционых БД (NoSql) Не делает SQL JOIN(), применяется не только в реляционых БД (NoSql)
 Применяется только для построений конструкций вида **WHERE IN()**, плюс наполняют [[yii2:start#relation|relation]] Применяется только для построений конструкций вида **WHERE IN()**, плюс наполняют [[yii2:start#relation|relation]]
  
-==== leftJoin() ====+=== leftJoin() ===
  
 Добавляет SQL LEFT JOIN(), применяется только в реляционыых БД, плюс наполняют [[yii2:start#relation|relation]] Добавляет SQL LEFT JOIN(), применяется только в реляционыых БД, плюс наполняют [[yii2:start#relation|relation]]
Строка 447: Строка 501:
 </code> </code>
  
-==== joinWith() ====+=== joinWith() ===
  
 Добавляет SQL JOIN(), применяется только в реляционыых БД, плюс наполняют [[yii2:start#relation|relation]] Добавляет SQL JOIN(), применяется только в реляционыых БД, плюс наполняют [[yii2:start#relation|relation]]
Строка 474: Строка 528:
 https://github.com/yiisoft/yii2/blob/master/docs/guide/active-record.md#joining-with-relations https://github.com/yiisoft/yii2/blob/master/docs/guide/active-record.md#joining-with-relations
  
-==== innerJoinWith() ====+=== innerJoinWith() ===
  
- +==== Validate (Rules) ====
-====== Validate (Rules) ======+
  
 <code php> <code php>
Строка 487: Строка 540:
     {     {
         return [         return [
-                  ['attribute1', 'attribute2', ...], +                  
-                  'validator class or alias', +                    ['attribute1', 'attribute2', ...], 
-                  // specifies in which scenario(s) this rule is active. +                    'validator class or alias', 
-                  // if not given, it means it is active in all scenarios +                    // specifies in which scenario(s) this rule is active. 
-                  'on' => ['scenario1', 'scenario2', ...], +                    // if not given, it means it is active in all scenarios 
-                  // the following name-value pairs will be used +                    'on' => ['scenario1', 'scenario2', ...], 
-                  // to initialize the validator properties +                    // the following name-value pairs will be used 
-                  'property1' => 'value1', +                    // to initialize the validator properties 
-                  'property2' => 'value2', +                    '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 
 +                    'except' => ['scenario1', 'scenario2', ...], 
 +                    // the following name-value pairs will be used 
 +                    // to initialize the validator properties 
 +                    'property1' => 'value1', 
 +                    'property2' => 'value2', 
 +                    // ... 
 +                  ],          
               ];               ];
     }     }
Строка 537: Строка 604:
   * **Подробно** https://github.com/yiisoft/yii2/blob/master/docs/guide/model.md   * **Подробно** https://github.com/yiisoft/yii2/blob/master/docs/guide/model.md
   * **Список базовых валидаторов:** https://github.com/yiisoft/yii2/blob/master/docs/guide/validation.md   * **Список базовых валидаторов:** https://github.com/yiisoft/yii2/blob/master/docs/guide/validation.md
-====== Scenario ======+ 
 +==== Scenario ====
  
 <code php> <code php>
Строка 570: Строка 638:
  
 **Подробно** https://github.com/yiisoft/yii2/blob/master/docs/guide/structure-models.md#scenarios- **Подробно** https://github.com/yiisoft/yii2/blob/master/docs/guide/structure-models.md#scenarios-
-====== Connection/Command/QueryBuilder ====== 
  
-==== Connection ====+==== Relation ==== 
 + 
 +<code php> 
 +class Customer extends \yii\db\ActiveRecord 
 +
 +    // 
 +    public function getOrders() 
 +    { 
 +        return $this->hasMany(Order::className(), ['customer_id' => 'id']); 
 +    }     
 +   
 +    // 
 +    public function getBigOrders($threshold = 100) 
 +    { 
 +        return $this->hasMany(Order::className(), ['customer_id' => 'id']) 
 +            ->where('subtotal > :threshold', [':threshold' => $threshold]) 
 +            ->orderBy('id'); 
 +    } 
 + 
 +    // Вытащить данные из таблицы модели Item, используя связи из таблицы tbl_order_item 
 +    public function getItems() 
 +    { 
 +      // Получить данные через таблицу tbl_order_item 
 +      return $this->hasMany(Item::className(), ['id' => 'item_id']) 
 +            ->viaTable('tbl_order_item', ['order_id' => 'id']); 
 +    } 
 +     
 +    // 
 +    public static function olderThan($query, $age = 30) 
 +    { 
 +        $query->andWhere('age > :age', [':age' => $age]); 
 +    } 
 +
 +</code> 
 + 
 +<code php> 
 +$customer = Customer::find(1); 
 +$orders = $customer->orders; 
 +$orders = $customer->getBigOrders(200)->all(); 
 +$customers = Customer::find()->olderThan(50)->all(); 
 +</code> 
 + 
 +<code php> 
 +$customer = Customer::find(1); 
 +$order = new Order(); 
 +$order->comment = ''; 
 +$customer->link('orders', $customer); 
 +</code> 
 + 
 +==== Events ==== 
 + 
 +<code php> 
 +class Post extends ActiveRecord 
 +
 +  public function init() 
 +  { 
 +    $this->on('beforeAction', function($event) { 
 +      // отменяем действие 
 +      $event->isValid = false; 
 +    }); 
 +  } 
 +
 +</code> 
 + 
 +<code php> 
 +$component->on('beforeAction', $handler); 
 +</code> 
 +==== Как получить SQL и Параметры из ActiveQuery ==== 
 + 
 +<code php> 
 +$query = Post::find()->where(array('id' => 10, 'status' => Post::READ))->createCommand(); 
 + 
 +// SQL 
 +echo $query->sql 
 + 
 +// Params: 
 +print_r($query->params)   
 +</code> 
 +==== Объекты доступа к данным (Data Access Objects, DAO) ==== 
 + 
 +=== Соеденение ===
  
 <code php> <code php>
Строка 582: Строка 729:
   * https://github.com/yiisoft/yii2/blob/master/docs/guide/database-basics.md   * https://github.com/yiisoft/yii2/blob/master/docs/guide/database-basics.md
  
-==== Command ====+=== Методы запроса ===
  
   * queryOne()   * queryOne()
Строка 591: Строка 738:
  
 **Подробно**  https://github.com/yiisoft/yii2/blob/master/framework/db/Command.php **Подробно**  https://github.com/yiisoft/yii2/blob/master/framework/db/Command.php
 +
 +== createCommand ==
  
 <code php> <code php>
Строка 631: Строка 780:
 </code> </code>
  
-==== Query Builder and Query ====+==== Построитель запросов (Query Builder and Query====
  
 <code php> <code php>
Строка 684: Строка 833:
   * https://github.com/yiisoft/yii2/blob/master/docs/guide/db-query-builder.md   * https://github.com/yiisoft/yii2/blob/master/docs/guide/db-query-builder.md
  
-====== Transactions ======+==== Transactions ====
  
 <code php> <code php>
Строка 698: Строка 847:
 </code> </code>
  
-====== Active Record ======+==== Batch ====
  
-<code php> +=== Batch ===
-class Post extends ActiveRecord +
-+
-    public function getCreator() +
-    { +
-        return $this->hasOne('User', array('id' => 'user_id')); +
-    } +
-    public function getComments() +
-    { +
-        return $this->hasMany('Comment', array('post_id' => 'id')); +
-    } +
-    public function getTrustComments($isTrust = true) +
-    { +
-        return $this->hasMany('Comment', array('post_id' => 'id')) +
-            ->where('status = :status', array( +
-                     ':status' => $isTrust ? self::TRUST : self::UNTRUST, +
-              )) +
-            ->orderBy('id'); +
-    } +
-+
-</code> +
- +
-<code php> +
-        $price = PriceItem::find() +
-            ->select(['price', 'create_time' => 'DATE_FORMAT(create_time, "%d.%m.%Y")']) +
-            ->where(['and',  +
-                ['price_list_form_id' => $price_list_form_ids],  +
-                ['>', 'create_time', '2015.01.01'+
-        ])->orderBy(['price' => SORT_ASC])->asArray()->one(); +
-</code> +
- +
-<code php> +
-// we receive an ActiveQuery instance +
-$query = Post::find(); +
-  +
-// all posts +
-$posts = $query->all(); +
-  +
-// looking for all the posts with a condition +
-$posts = $query +
-    ->where(array('status' => Post::DRAFT)) +
-    ->orderBy('time'+
-    ->all(); +
-  +
-// looking for a post  +
-$post = $query +
-   ->where(array('id' => 10, 'status' => Post::READ)) +
-   ->one(); +
-  +
-// or easier: "where" condition can be transmitted directly to the factory method +
-$post = Post::find(array('id' => 10, 'status' => Post::READ)); +
-  +
-// having transmitted to the factory method not a massive, but a number equivalent to the primary key search  +
-$post = Post::find(10) +
-   ->where(array('status' => Post::READ)) +
-   ->one(); +
-  +
-// we index the result to a necessary attribute +
-$posts = $query->indexBy('title')->all(); +
-  +
-// the result as an array +
-$posts = $query->asArray()->all(); +
-</code> +
- +
-===== Как получить SQL и Параметры из ActiveQuery ===== +
- +
-<code php> +
-$query = Post::find()->whwre(array('id' => 10, 'status' => Post::READ))->createCommand(); +
- +
-// SQL +
-echo $query->sql +
- +
-// Params: +
-print_r($query->params)   +
-</code> +
- +
-==== Batch ====+
  
  
Строка 806: Строка 879:
 Yii::$app->db->createCommand()->batchInsert(Post::tableName(), $postModel->attributes(), $rows)->execute(); Yii::$app->db->createCommand()->batchInsert(Post::tableName(), $postModel->attributes(), $rows)->execute();
 </code> </code>
-==== Each ====+ 
 +=== Each ===
  
 <code php> <code php>
Строка 818: Строка 892:
 </code> </code>
  
-==== Ключи в эллементах коллекции AR ====+===== Controller =====
  
-== AR ==+==== Как программно вызвать контроллер? ====
  
 <code php> <code php>
-$query SparesCategory::find()->where(['parent_id=> 0])+$className = 'backend\controllers\SiteController'; 
-$query->indexBy function($row){ // Ключ в который будет помещена возвращаемая модель +$controller Yii::createObject($className, [$id$this]);
-    return $row->id+
-}; +
-$categories = $query->all();+
 </code> </code>
  
-<code php> +==== yii\helpers\Html (old) ====
-        $quey CarMark::find()->indexBy(function($row){ +
-            return $row->id; +
-        })->all(); +
-</code> +
- +
-==== Создание модели из возвращаемы данных Command (с помощью populateRecord()) ====+
  
 <code php> <code php>
-        $sql "SELECT * FROM `tbl_spares_category` c +// ['label' => 'Добавление', 'url' => ['/admin/user/create']] 
-            LEFT JOIN tbl_form_spares_category fc ON fc.category_id c.id +Html::a("Log in here", ["user/reset", "hash" => $hash"sid" => $sid]); 
-            WHERE fc.form_id = :form_id AND fc.category_id = :category_id"+Html::url(["user/reset", "hash" =$hash"sid" => $sid]);
-        $select_marks = Yii::$app->db->createCommand($sql, [ +
-            ':form_id' => $form_id, +
-            ':category_id' => $category_id, +
-        ])->queryAll(); +
-   +
-        foreach($marks as $row){ +
-             +
-            // Only yii2 alpha +
-            //$mark = SparesCategoryForm::create($row); +
-           +
-            $mark new SparesCategoryForm; +
-            SparesCategoryForm::populateRecord($mark, $row); +
-             +
-   +
-            if(isset($mark->id)){ +
-   +
-              // do somethig +
-   +
-            } +
-        }+
 </code> </code>
  
 +**Подробно** https://github.com/yiisoft/yii2/blob/master/docs/guide/url.md
  
 +===== Module =====
  
-  * [[Activedataprovider|Activedataprovider]] +==== Submodule ====
-  * [[SqlDataProvider|SqlDataProvider]] +
-  * [[ArrayDataProvider|ArrayDataProvider]] +
- +
-**Подробно:** +
- +
-====== Relation ====== +
- +
-<code php> +
-class Customer extends \yii\db\ActiveRecord +
-+
-    // +
-    public function getOrders() +
-    { +
-        return $this->hasMany(Order::className(), ['customer_id' => 'id']); +
-    }     +
-   +
-    // +
-    public function getBigOrders($threshold = 100) +
-    { +
-        return $this->hasMany(Order::className(), ['customer_id' => 'id']) +
-            ->where('subtotal > :threshold', [':threshold' => $threshold]) +
-            ->orderBy('id'); +
-    } +
- +
-    // Вытащить данные из таблицы модели Item, используя связи из таблицы tbl_order_item +
-    public function getItems() +
-    { +
-      // Получить данные через таблицу tbl_order_item +
-      return $this->hasMany(Item::className(), ['id' => 'item_id']) +
-            ->viaTable('tbl_order_item', ['order_id' => 'id']); +
-    } +
-     +
-    // +
-    public static function olderThan($query, $age = 30) +
-    { +
-        $query->andWhere('age > :age', [':age' => $age]); +
-    } +
-+
-</code> +
- +
-<code php> +
-$customer = Customer::find(1); +
-$orders = $customer->orders; +
-$orders = $customer->getBigOrders(200)->all(); +
-$customers = Customer::find()->olderThan(50)->all(); +
-</code> +
- +
-<code php> +
-$customer = Customer::find(1); +
-$order = new Order(); +
-$order->comment = ''; +
-$customer->link('orders', $customer); +
-</code> +
- +
-======== Events ======== +
- +
-<code php> +
-class Post extends ActiveRecord +
-+
-  public function init() +
-  { +
-    $this->on('beforeAction', function($event) { +
-      // отменяем действие +
-      $event->isValid = false; +
-    }); +
-  } +
-+
-</code> +
- +
-<code php> +
-$component->on('beforeAction', $handler); +
-</code> +
- +
-======== Components ======== +
- +
-Создание объекта компанента +
-<code php> +
-$object = Yii::createObject(array( +
-    'class' => 'MyClass', +
-    'property1' => 'abc', +
-    'property2' => 'cde', +
-), $param1, $param2); +
-</code> +
- +
-======== Theme ======== +
- +
-<code php> +
-'view' => array( +
-    'theme' => array( +
-        'pathMap' => array('@app/views' => '@webroot/themes/basic'), +
-        'baseUrl' => '@www/themes/basic', +
-    ), +
-), +
-</code> +
- +
-====== Form ====== +
- +
-  * [[yii2:form|ActiveForm]] +
-  * [[yii2:form|HTML]]    +
- +
-**Подробно** https://github.com/yiisoft/yii2/blob/master/docs/guide/form.md +
-====== Assets ====== +
- +
- +
-======== Console ======== +
- +
-===== IsConsole ===== +
- +
-<code php> +
- if(Yii::$app->request->isConsoleRequest){ +
-   // +
- } +
-</code> +
-======== Module ======== +
- +
-====== Submodule ======+
  
 Для работы сабмодуля, необходимо выполнить его подключение, через указание submodule namespace модуля Для работы сабмодуля, необходимо выполнить его подключение, через указание submodule namespace модуля
Строка 1008: Строка 939:
 </code> </code>
  
- +==== Helpers ====
- +
-======== Helpers ========+
  
   * https://github.com/yiisoft/yii2/blob/master/docs/guide/security.md   * https://github.com/yiisoft/yii2/blob/master/docs/guide/security.md
  
-======== Behaviors/Filters ========+==== Behaviors/Filters ====
  
 <code php> <code php>
 public function behaviors() public function behaviors()
 { {
-    return array( +  return array( 
-        'access' => array( +    'access' => array( 
-            'class' => 'yii\web\AccessControl', +      'class' => 'yii\web\AccessControl', 
-            'rules' => array( +      'rules' => array( 
-                array('allow' => true, 'actions' => array('admin'), 'roles' => array('@')), +        array('allow' => true, 'actions' => array('admin'), 'roles' => array('@')), 
-                array('allow' => false), +        array('allow' => false), 
-            ), +      ), 
-        ), +    ), 
-    );+  );
 } }
 </code> </code>
  
-====== Статьи ======+==== Behaviors/Date ====
  
- +<code php> 
-  * http://habrahabr.ru/post/208328/ +public function behaviors() { 
- +  return [ 
- +    [ 
-======== Локализация - i18N/intl ======== +      'class' => TimestampBehavior::className(), 
- +      'createdAtAttribute' => 'create_time', 
-  apt=get install php5-intl +      //'updatedAtAttribute' => 'update_time', 
-   +      'value' => new Expression('NOW()'), 
- +    ], 
-======== Session ========+  ]; 
 +} 
 +</code> 
 +===== Session =====
  
 <code php> <code php>
Строка 1049: Строка 981:
 </code> </code>
  
-===== setFlash =====+==== setFlash ====
  
 В контролере В контролере
Строка 1091: Строка 1023:
 | Toastr               | toastr                       | https://github.com/CodeSeven/toastr                   | docs/Toastr.md             | | Toastr               | toastr                       | https://github.com/CodeSeven/toastr                   | docs/Toastr.md             |
  
-====== Cache ======+ 
 +===== Console ===== 
 + 
 +==== IsConsole ==== 
 + 
 +<code php> 
 + if(Yii::$app->request->isConsoleRequest){ 
 +   // 
 + } 
 +</code> 
 + 
 +==== Params / Параметры ==== 
 + 
 +<code php> 
 +<?php 
 + 
 +namespace console\controllers; 
 + 
 +use yii\console\Controller; 
 + 
 +class QueueController extends Controller 
 +
 +    public $pid_file = ''; 
 + 
 +    public function __get($name) 
 +    { 
 +        $name = str_replace('-', '_', $name); 
 + 
 +        return $this->$name; 
 +    } 
 + 
 +    public function __set($name, $value) 
 +    { 
 +        $name = str_replace('-', '_', $name); 
 + 
 +        $this->$name = $value; 
 +    } 
 + 
 + 
 +    public function options($actionID) 
 +    { 
 +        return ['pid-file']; 
 +    } 
 + 
 +    public function actionRun() 
 +    { 
 + 
 +    } 
 +
 +</code> 
 + 
 + 
 +===== User ===== 
 + 
 +==== RBAC ==== 
 + 
 +  * [[yii2:user:rbac|RBAC]] 
 + 
 +**Подробно** https://github.com/yiisoft/yii2/blob/master/docs/guide/authorization.md 
 + 
 +==== Access ==== 
 + 
 +<code php> 
 +    'access' => [ 
 +            'class' => \yii\web\AccessControl::className(), 
 +            'rules' => [ 
 +                    [ 
 +                            'actions' => ['index'], 
 +                            'allow' => false, 
 +                            'roles' => ['?'], 
 +                    ], 
 +                    [ 
 +                            'actions' => ['index', 'update','view','create','delete'], 
 +                            'allow' => true, 
 +                            'matchCallback' => function() { 
 +                            return \Yii::$app->user->identity->role <= \Yii::$app->user->identity->MANAGER;                     
 +                            } 
 +                    ], 
 +            ], 
 +    ],   
 +</code> 
 + 
 + 
 +===== Components ===== 
 + 
 +Создание объекта компанента 
 +<code php> 
 +$object = Yii::createObject(array( 
 +    'class' => 'MyClass', 
 +    'property1' => 'abc', 
 +    'property2' => 'cde', 
 +), $param1, $param2); 
 +</code> 
 + 
 +===== Theme ===== 
 + 
 +<code php> 
 +'view' => array( 
 +    'theme' => array( 
 +        'pathMap' => array('@app/views' => '@webroot/themes/basic'), 
 +        'baseUrl' => '@www/themes/basic', 
 +    ), 
 +), 
 +</code> 
 + 
 +===== Cache =====
  
 <code php> <code php>
Строка 1115: Строка 1152:
   * [[yii\caching\TagDependency]]: Связывает кэшированные данные элемента с одним или несколькими тегами. Вы можете аннулировать кэширование данных элементов с заданным тегом(тегами) по вызову. [[yii\caching\TagDependency::invalidate()]];   * [[yii\caching\TagDependency]]: Связывает кэшированные данные элемента с одним или несколькими тегами. Вы можете аннулировать кэширование данных элементов с заданным тегом(тегами) по вызову. [[yii\caching\TagDependency::invalidate()]];
  
-===== Кэширование запросов =====+==== Кэширование запросов ====
  
 <code php> <code php>
Строка 1179: Строка 1216:
 }); });
 </code> </code>
-===== Статьи =====+ 
 +===== Локализация - i18N/intl ===== 
 + 
 +  apt=get install php5-intl 
 + 
 +==== Перевод (локализация проекта) ==== 
 + 
 +  * https://github.com/lajax/yii2-translate-manager 
 + 
 +===== PHPUnit ===== 
 + 
 +добавить в конфигуратор композера composer.json 
 +<code> 
 +
 +    "require-dev":
 +        "phpunit/phpunit": "3.7.*" 
 +    } 
 +
 +</code> 
 + 
 +    * php composer.phar update 
 +    * php vendor/bin/phpunit vendor/yiisoft/yii2/yii/test/ 
 + 
 +====== Статьи ======
  
   * https://github.com/yiisoft/yii2/blob/master/docs/guide-ru/caching-data.md   * https://github.com/yiisoft/yii2/blob/master/docs/guide-ru/caching-data.md
   * https://gist.github.com/jkovacs618/ab225ecadf55cb1feca9   * https://gist.github.com/jkovacs618/ab225ecadf55cb1feca9
 +  * http://habrahabr.ru/post/208328/
  
 ====== Описание ====== ====== Описание ======
Строка 1190: Строка 1250:
   * http://userguide.icu-project.org/formatparse/messages   * http://userguide.icu-project.org/formatparse/messages
   * http://icu-project.org/apiref/icu4c/classMessageFormat.html   * http://icu-project.org/apiref/icu4c/classMessageFormat.html
 +