Различия

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

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

Предыдущая версия справа и слева Предыдущая версия
Следующая версия
Предыдущая версия
yii2:docs [2015/10/25 21:53] – [Как получить SQL из ActiveQuery] 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' =
 +        'urlManager' =[ 
 +            'enablePrettyUrl' =true, 
 +            'showScriptName' =false, 
 +            'enableStrictParsing' =true, 
 +            'suffix' => '.html', 
 +            'rules' => [ 
 +                '<action:(login|logout|about)>' => 'site/<action>'
 +     
 +                // ... 
 +     
 +                ['class' => 'app\components\CarUrlRule', 'connectionID' => 'db', ...], 
 +            ],   
 +        ], 
 +    ], 
 +];
 </code> </code>
-===== POST ===== +==== Url ====
- +
-<code php> +
-Yii::$app->request->post(); +
-Yii::$app->request->getBodyParams(); +
-Yii::$app->request->getBodyParam('File'); +
-Yii::$app->request->post('File'); +
-</code> +
-====== View ====== +
- +
-===== Blocks ===== +
- +
-====== CSS ====== +
- +
-====== 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> +
- +
-==== Добавление csrfToken в Ajax запрос ==== +
- +
-<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> +
-====== Image ====== +
  
-====== yii\helpers\Url::toRoute ======+=== yii\helpers\Url::toRoute ===
  
 <code php> <code php>
Строка 151: Строка 99:
 </code> </code>
  
-====== yii\helpers\Url::to ======+=== yii\helpers\Url::to ===
  
 <code php> <code php>
Строка 181: Строка 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>
Строка 201: Строка 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>
Строка 216: Строка 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
Строка 228: Строка 177:
 </code> </code>
  
-вместо старых методов нада использовать **yii\helpers::toRoute**+вместо старых методов надо использовать **yii\helpers::toRoute**
  
 Усли $this - это yii\web\Controller Усли $this - это yii\web\Controller
Строка 238: Строка 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>
Строка 350: Строка 354:
 <?php Pjax::end(); ?> <?php Pjax::end(); ?>
 </code> </code>
-======== User ======== 
  
-====== RBAC ======+===== Виджеты / Widgets =====
  
-  * [[yii2:user:rbac:description|Описание]] +  * [[yii2:widgets:masked-input|]] - http://demos.krajee.com/masked-input
-  * [[yii2:user:rbac|RBAC]]+
  
-**Подробно** 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]] 
-====== Join ======+  * [[SqlDataProvider|SqlDataProvider]] 
 +  * [[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]]
Строка 415: Строка 501:
 </code> </code>
  
-==== joinWith() ====+=== joinWith() ===
  
 Добавляет SQL JOIN(), применяется только в реляционыых БД, плюс наполняют [[yii2:start#relation|relation]] Добавляет SQL JOIN(), применяется только в реляционыых БД, плюс наполняют [[yii2:start#relation|relation]]
Строка 442: Строка 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>
Строка 455: Строка 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', 
 +                    // ... 
 +                  ],          
               ];               ];
     }     }
Строка 505: Строка 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>
Строка 538: Строка 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>
Строка 550: Строка 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()
Строка 559: Строка 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>
Строка 599: Строка 780:
 </code> </code>
  
-==== Query Builder and Query ====+==== Построитель запросов (Query Builder and Query====
  
 <code php> <code php>
Строка 652: Строка 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>
Строка 666: Строка 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> 
-// 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> <code php>
-$query = Post::find()->whwre(array('id' => 10, 'status' => Post::READ))->createCommand();+foreach (Customer::find()->batch() as $customers{
  
-// SQL +}
-echo $query->sql+
  
-// Params: +foreach (Customer::find()->batch(10as $customers) { 
-print_r($query->params +    // $customers — массив из 10 или менее объектов Customer 
 +}
 </code> </code>
  
-==== Batch ====+<code php> 
 +$rows [];
  
 +foreach ($models as $model) {
 +    if (!$model->validate()) {
 +        // At least one model has invalid data
  
-<code php> +        break; 
-foreach (Customer::find()->batch() as $customers) {+    }
  
 +    $rows[] = $model->attributes;
 } }
 +$rows =  \yii\helpers\ArrayHelper::getColumn($models, 'attributes;');
 +$postModel = new Post;
  
-foreach (Customer::find()->batch(10as $customers+Yii::$app->db->createCommand()->batchInsert(Post::tableName()$postModel->attributes()$rows)->execute();
-    // $customers — массив из 10 или менее объектов Customer +
-}+
 </code> </code>
  
-==== Each ====+=== Each ===
  
 <code php> <code php>
Строка 760: Строка 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>
 +
 +==== yii\helpers\Html (old) ====
  
 <code php> <code php>
-        $quey CarMark::find()->indexBy(function($row){ +// ['label' => 'Добавление', 'url' => ['/admin/user/create']] 
-            return $row->id+Html::a("Log in here", ["user/reset", "hash" => $hash, "sid" =$sid])
-        })->all();+Html::url(["user/reset", "hash" => $hash, "sid" => $sid]);
 </code> </code>
  
-==== Создание модели из возвращаемы данных Command (с помощью populateRecord()) ====+**Подробно** https://github.com/yiisoft/yii2/blob/master/docs/guide/url.md
  
 +===== Module =====
 +
 +==== Submodule ====
 +
 +Для работы сабмодуля, необходимо выполнить его подключение, через указание submodule namespace модуля
 <code php> <code php>
-        $sql = "SELECT * FROM `tbl_spares_category` c +namespace mirocow\eav
-            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"+class Module extends \yii\base\Module {
-        $select_marks = Yii::$app->db->createCommand($sql, [ +
-            ':form_id' => $form_id, +
-            ':category_id' => $category_id, +
-        ])->queryAll();+
      
-        foreach($marks as $row){ +    // ... 
-             +    public function init() { 
-            // Only yii2 alpha + 
-            //$mark = SparesCategoryForm::create($row); +      // .. 
-           + 
-            $mark = new SparesCategoryForm; +      $this->setModule('admin''yii\user\modules\admin\Module'); 
-            SparesCategoryForm::populateRecord($mark$row); +    }
-            +
      
-            if(isset($mark->id)){+    // Пример перенаправления роута в саб модуль admin 
 +    public function createController($route) { 
 +       
 +        return $this->getModule('admin')->createController(str_replace('admin/','',$route)); 
 +       
 +    }  
      
-              // do somethig +}
-   +
-            } +
-        }+
 </code> </code>
  
 +==== Helpers ====
  
 +  * https://github.com/yiisoft/yii2/blob/master/docs/guide/security.md
  
-  * [[Activedataprovider|Activedataprovider ]] - Pager / Генерация страниц +==== Behaviors/Filters ====
-  * [[SqlDataProvider|SqlDataProvider ]] - Pager / Генерация страниц +
- +
-**Подробно:** +
- +
-====== Relation ======+
  
 <code php> <code php>
-class Customer extends \yii\db\ActiveRecord+public function behaviors()
 { {
-    // +  return array
-    public function getOrders() +    'access' => array
-    +      'class' => 'yii\web\AccessControl', 
-        return $this->hasMany(Order::className(), ['customer_id' => 'id']); +      'rules' => array( 
-    }     +        array('allow=true, 'actions' => array('admin'), 'roles' => array('@'))
-   +        array('allow' => false)
-    // +      ), 
-    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>
 +
 +==== Behaviors/Date ====
  
 <code php> <code php>
-$customer Customer::find(1); +public function behaviors() { 
-$orders $customer->orders; +  return [ 
-$orders $customer->getBigOrders(200)->all(); +    [ 
-$customers Customer::find()->olderThan(50)->all();+      'class' => TimestampBehavior::className(), 
 +      'createdAtAttribute' => 'create_time', 
 +      //'updatedAtAttribute' => 'update_time', 
 +      'value' => new Expression('NOW()'), 
 +    ], 
 +  ]; 
 +}
 </code> </code>
 +===== Session =====
  
 <code php> <code php>
-$customer = Customer::find(1); +Yii::$app->session->get('key')
-$order = new Order(); +Yii::$app->session->set('key', 'value');
-$order->comment = ''; +
-$customer->link('orders', $customer);+
 </code> </code>
  
-======== Events ========+==== setFlash ====
  
 +В контролере
 <code php> <code php>
-class Post extends ActiveRecord +Yii::$app->session->setFlash('info', $shell->output); 
-+return $this->redirect('/site');
-  public function init() +
-  { +
-    $this->on('beforeAction', function($event+
-      // отменяем действие +
-      $event->isValid = false; +
-    }); +
-  } +
-}+
 </code> </code>
 +return делать обязательно. инчаче после редиректа сообщение не выведется
  
 +Вывод стандартным способом
 <code php> <code php>
-$component->on('beforeAction'$handler);+<?php foreach (Yii::$app->session->getAllFlashes() as $key => $message) { 
 +  echo '<div class="alert alert-$key . '">' . $message . '</div>'; 
 +} ?>
 </code> </code>
  
-======== Components ======== +Вывод с помощью виджета [[https://github.com/loveorigami/yii2-notification-wrapper|loveorigami/yii2-notification-wrapper]]
- +
-Создание объекта компанента+
 <code php> <code php>
-$object Yii::createObject(array+<?Wrapper::widget([ 
-    'class' => 'MyClass', +  'layerClass' => 'lo\modules\noty\layers\Noty', 
-    'property1' => 'abc', +]);?>
-    'property2' => 'cde', +
-), $param1, $param2);+
 </code> </code>
 +Данный виджет поддерживает большое кол-во виджетов обображения таких как:
 +| Library (Layer)      | Bower                        | Project homepage                                      | Docs                       |
 +| Bootstrap Alert      | -                            | http://getbootstrap.com/components/#alerts            | docs/Alert.md              |
 +| Bootstrap Notify     | remarkable-bootstrap-notify  | https://github.com/mouse0270/bootstrap-notify         | docs/BootstrapNotify.md    |
 +| Growl                | jquery-growl                 | https://github.com/ksylvest/jquery-growl              | docs/Growl.md              |
 +| iGrowl               | igrowl                       | https://github.com/catc/iGrowl                        | docs/Igrowl.md             |
 +| jQuery Notify        | jquery.notify                | https://github.com/CreativeDream/jquery.notify        | docs/JqueryNotify.md       |
 +| jQuery Notify Bar    | jqnotifybar                  | https://github.com/dknight/jQuery-Notify-bar          | docs/JqueryNotifyBar.md    |
 +| jQuery Toaster       | jquery.toaster               | https://github.com/scottoffen/jquery.toaster          | docs/JqueryToaster.md      |
 +| jQuery Toast Plugin  | jquery-toast-plugin          | https://github.com/kamranahmedse/jquery-toast-plugin  | docs/JqueryToastPlugin.md  |
 +| Lobibox              | lobibox                      | https://github.com/arboshiki/lobibox                  | docs/Lobibox.md            |
 +| Notie                | notie                        | https://github.com/jaredreich/notie                   | docs/Notie.md              |
 +| Notific8             | notific8                     | https://github.com/ralivue/notific8                   | docs/Notific8.md           |
 +| NotifIt              | notifit                      | https://github.com/naoxink/notifIt                    | docs/NotifIt.md            |
 +| Notify.js            | notifyjs                     | https://github.com/notifyjs/notifyjs                  | docs/Notifyjs.md           |
 +| Noty                 | noty                         | https://github.com/needim/noty                        | docs/Noty.md               |
 +| PNotify              | pnotify                      | https://github.com/sciactive/pnotify                  | docs/PNotify.md            |
 +| Sweetalert           | sweetalert                   | https://github.com/t4t5/sweetalert                    | docs/Sweetalert.md         |
 +| Toastr               | toastr                       | https://github.com/CodeSeven/toastr                   | docs/Toastr.md             |
  
-======== Theme ========+ 
 +===== Console ===== 
 + 
 +==== IsConsole ====
  
 <code php> <code php>
-'view' => array( + if(Yii::$app->request->isConsoleRequest){ 
-    'theme' =array( +   // 
-        'pathMap' =array('@app/views' => '@wwwroot/themes/basic'), + }
-        'baseUrl' => '@www/themes/basic', +
-    ), +
-),+
 </code> </code>
  
-====== Form ======+==== Params / Параметры ====
  
-  * [[yii2:form|ActiveForm]] +<code php> 
-  * [[yii2:form|HTML]]   +<?php
  
-**Подробно** https://github.com/yiisoft/yii2/blob/master/docs/guide/form.md +namespace console\controllers;
-====== Assets ======+
  
 +use yii\console\Controller;
  
-======== Console ========+class QueueController extends Controller 
 +
 +    public $pid_file '';
  
-======== Module ========+    public function __get($name) 
 +    { 
 +        $name str_replace('-', '_', $name);
  
-====== Submodule ======+        return $this->$name; 
 +    }
  
-Для работы сабмодулянеобходимо выполнить его подключение, через указание submodule namespace модуля +    public function __set($name$value) 
-<code php> +    { 
-namespace mirocow\eav;+        $name = str_replace('-', '_', $name);
  
-class Module extends \yii\base\Module { +        $this->$name = $value; 
-   +    }
-    // ... +
-    public function init() {+
  
-      // .. 
  
-      $this->setModule('admin', 'yii\user\modules\admin\Module');+    public function options($actionID) 
 +    { 
 +        return ['pid-file']; 
 +    } 
 + 
 +    public function actionRun() 
 +    { 
     }     }
-   
-    // Пример перенаправления роута в саб модуль admin 
-    public function createController($route) { 
-       
-        return $this->getModule('admin')->createController(str_replace('admin/','',$route)); 
-       
-    }   
-   
 } }
 </code> </code>
  
  
 +===== User =====
  
-======== Helpers ========+==== RBAC ====
  
-  * https://github.com/yiisoft/yii2/blob/master/docs/guide/security.md+  * [[yii2:user:rbac|RBAC]]
  
-======== Behaviors/Filters ========+**Подробно** https://github.com/yiisoft/yii2/blob/master/docs/guide/authorization.md 
 + 
 +==== Access ====
  
 <code php> <code php>
-public function behaviors() +    'access' => [ 
-+            'class' => \yii\web\AccessControl::className()
-    return array( +            'rules' => [ 
-        'access' => array( +                    [ 
-            'class' => 'yii\web\AccessControl'+                            'actions' => ['index'], 
-            'rules' => array( +                            'allow' => false, 
-                array('allow' => true, 'actions' => array('admin'), 'roles' => array('@'))+                            'roles' => ['?'], 
-                array('allow' => false)+                    ], 
-            ), +                    [ 
-        )+                            'actions' => ['index', 'update','view','create','delete']
-    ); +                            'allow' => true
-}+                            'matchCallback' => function(
 +                            return \Yii::$app->user->identity->role <= \Yii::$app->user->identity->MANAGER;                     
 +                            } 
 +                    ]
 +            ]
 +    ],  
 </code> </code>
  
-====== Статьи ====== 
  
 +===== Components =====
  
-  * http://habrahabr.ru/post/208328/+Создание объекта компанента 
 +<code php> 
 +$object = Yii::createObject(array( 
 +    'class' => 'MyClass', 
 +    'property1' => 'abc', 
 +    'property2' => 'cde', 
 +), $param1, $param2); 
 +</code>
  
- +===== Theme =====
-======== Локализация - i18N/intl ======== +
- +
-  apt=get install php5-intl +
-   +
- +
-======== Session ========+
  
 <code php> <code php>
-Yii::$app->session->get('key'); +'view' =array( 
-Yii::$app->session->set('key', 'value');+    'theme=> array( 
 +        'pathMap' =array('@app/views=> '@webroot/themes/basic'), 
 +        'baseUrl=> '@www/themes/basic', 
 +    )
 +),
 </code> </code>
  
-====== Cache ======+===== Cache =====
  
 <code php> <code php>
Строка 1007: Строка 1152:
   * [[yii\caching\TagDependency]]: Связывает кэшированные данные элемента с одним или несколькими тегами. Вы можете аннулировать кэширование данных элементов с заданным тегом(тегами) по вызову. [[yii\caching\TagDependency::invalidate()]];   * [[yii\caching\TagDependency]]: Связывает кэшированные данные элемента с одним или несколькими тегами. Вы можете аннулировать кэширование данных элементов с заданным тегом(тегами) по вызову. [[yii\caching\TagDependency::invalidate()]];
  
-===== Кэширование запросов =====+==== Кэширование запросов ====
  
 <code php> <code php>
Строка 1071: Строка 1216:
 }); });
 </code> </code>
-===== Статьи ===== 
  
-  * https://github.com/yiisoft/yii2/blob/master/docs/guide-ru/caching-data.md+===== Локализация 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://gist.github.com/jkovacs618/ab225ecadf55cb1feca9
 +  * http://habrahabr.ru/post/208328/
  
 ====== Описание ====== ====== Описание ======
Строка 1081: Строка 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
 +