Различия

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

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

Предыдущая версия справа и слева Предыдущая версия
Следующая версия
Предыдущая версия
yii2:docs [2017/01/04 22:42] – [Relation] mirocowyii2:docs [2019/04/18 13:17] (текущий) – [Active Record] mirocow
Строка 290: Строка 290:
       });       });
 </code> </code>
 +
 +==== Form ====
 +
 +  * [[yii2:form|ActiveForm]]
 +  * [[yii2:form|HTML]]   
 +
 +**Подробно** https://github.com/yiisoft/yii2/blob/master/docs/guide/form.md
  
 ===== Ajax ===== ===== Ajax =====
Строка 368: Строка 375:
     public function getCreator()     public function getCreator()
     {     {
-        return $this->hasOne('User', array('id' => 'user_id'));+        return $this->hasOne('User', ['id' => 'user_id']);
     }     }
     public function getComments()     public function getComments()
     {     {
-        return $this->hasMany('Comment', array('post_id' => 'id'));+        return $this->hasMany('Comment', ['post_id' => 'id']);
     }     }
     public function getTrustComments($isTrust = true)     public function getTrustComments($isTrust = true)
     {     {
-        return $this->hasMany('Comment', array('post_id' => 'id')+        return $this->hasMany('Comment', ['post_id' => 'id']
-            ->where('status = :status', array(+            ->where('status = :status', [
                      ':status' => $isTrust ? self::TRUST : self::UNTRUST,                      ':status' => $isTrust ? self::TRUST : self::UNTRUST,
-              ))+              ])
             ->orderBy('id');             ->orderBy('id');
     }     }
Строка 409: Строка 416:
 // looking for a post  // looking for a post 
 $post = $query $post = $query
-   ->where(array('id' => 10, 'status' => Post::READ))+   ->where(['id' => 10, 'status' => Post::READ])
    ->one();    ->one();
    
 // or easier: "where" condition can be transmitted directly to the factory method // or easier: "where" condition can be transmitted directly to the factory method
-$post = Post::find(array('id' => 10, 'status' => Post::READ));+$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  // having transmitted to the factory method not a massive, but a number equivalent to the primary key search 
 $post = Post::find(10) $post = Post::find(10)
-   ->where(array('status' => Post::READ))+   ->where(['status' => Post::READ])
    ->one();    ->one();
    
Строка 425: Строка 432:
 // the result as an array // the result as an array
 $posts = $query->asArray()->all(); $posts = $query->asArray()->all();
 +</code>
 +
 +<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> </code>
  
Строка 528: Строка 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', 
 +                    // ... 
 +                  ],          
               ];               ];
     }     }
Строка 662: Строка 688:
 </code> </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 ==== ==== Как получить SQL и Параметры из ActiveQuery ====
  
Строка 674: Строка 717:
 print_r($query->params)   print_r($query->params)  
 </code> </code>
-==== DAO ====+==== Объекты доступа к данным (Data Access Objects, DAO====
  
 === Соеденение === === Соеденение ===
Строка 696: Строка 739:
 **Подробно**  https://github.com/yiisoft/yii2/blob/master/framework/db/Command.php **Подробно**  https://github.com/yiisoft/yii2/blob/master/framework/db/Command.php
  
-== Query Builder and Query ==+== createCommand == 
 + 
 +<code php> 
 +$command = $connection->createCommand('SELECT * FROM tbl_post WHERE id=1'); 
 +$post = $command->queryOne(); 
 +</code> 
 + 
 +<code php> 
 +$connection->createCommand()->insert('tbl_user',
 +    'name' => 'Sam', 
 +    'age' => 30, 
 +])->execute(); 
 +</code> 
 + 
 +<code php> 
 +$command = $connection->createCommand('UPDATE tbl_post SET status=1 WHERE id=1'); 
 +$command->execute(); 
 +</code> 
 + 
 +<code php> 
 +$connection->createCommand()->batchInsert('tbl_user', ['name', 'age'],
 +    ['Tom', 30], 
 +    ['Jane', 20], 
 +    ['Linda', 25], 
 +])->execute(); 
 +</code> 
 + 
 +<code php> 
 +$connection->createCommand()->update('tbl_user', ['status' => 1], 'age > 30')->execute(); 
 +</code> 
 + 
 +<code php> 
 +$connection->createCommand()->delete('tbl_user', 'status = 0')->execute(); 
 +</code> 
 + 
 +<code php> 
 +$command = $connection->createCommand('SELECT * FROM tbl_post WHERE id=:id'); 
 +$command->bindValue(':id', $_GET['id']); 
 +$post = $command->query(); 
 +</code> 
 + 
 +==== Построитель запросов (Query Builder and Query) ====
  
 <code php> <code php>
Строка 748: Строка 832:
  
   * 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
- 
-== createCommand == 
- 
-<code php> 
-$command = $connection->createCommand('SELECT * FROM tbl_post WHERE id=1'); 
-$post = $command->queryOne(); 
-</code> 
- 
-<code php> 
-$connection->createCommand()->insert('tbl_user', [ 
-    'name' => 'Sam', 
-    'age' => 30, 
-])->execute(); 
-</code> 
- 
-<code php> 
-$command = $connection->createCommand('UPDATE tbl_post SET status=1 WHERE id=1'); 
-$command->execute(); 
-</code> 
- 
-<code php> 
-$connection->createCommand()->batchInsert('tbl_user', ['name', 'age'], [ 
-    ['Tom', 30], 
-    ['Jane', 20], 
-    ['Linda', 25], 
-])->execute(); 
-</code> 
- 
-<code php> 
-$connection->createCommand()->update('tbl_user', ['status' => 1], 'age > 30')->execute(); 
-</code> 
- 
-<code php> 
-$connection->createCommand()->delete('tbl_user', 'status = 0')->execute(); 
-</code> 
- 
-<code php> 
-$command = $connection->createCommand('SELECT * FROM tbl_post WHERE id=:id'); 
-$command->bindValue(':id', $_GET['id']); 
-$post = $command->query(); 
-</code> 
  
 ==== Transactions ==== ==== Transactions ====
Строка 848: Строка 891:
 } }
 </code> </code>
 +
 ===== Controller ===== ===== Controller =====
  
Строка 867: Строка 911:
 **Подробно** https://github.com/yiisoft/yii2/blob/master/docs/guide/url.md **Подробно** https://github.com/yiisoft/yii2/blob/master/docs/guide/url.md
  
 +===== Module =====
 +
 +==== Submodule ====
 +
 +Для работы сабмодуля, необходимо выполнить его подключение, через указание submodule namespace модуля
 +<code php>
 +namespace mirocow\eav;
 +
 +class Module extends \yii\base\Module {
 +  
 +    // ...
 +    public function init() {
 +
 +      // ..
 +
 +      $this->setModule('admin', 'yii\user\modules\admin\Module');
 +    }
 +  
 +    // Пример перенаправления роута в саб модуль admin
 +    public function createController($route) {
 +      
 +        return $this->getModule('admin')->createController(str_replace('admin/','',$route));
 +      
 +    }  
 +  
 +}
 +</code>
 +
 +==== Helpers ====
 +
 +  * https://github.com/yiisoft/yii2/blob/master/docs/guide/security.md
 +
 +==== Behaviors/Filters ====
 +
 +<code php>
 +public function behaviors()
 +{
 +  return array(
 +    'access' => array(
 +      'class' => 'yii\web\AccessControl',
 +      'rules' => array(
 +        array('allow' => true, 'actions' => array('admin'), 'roles' => array('@')),
 +        array('allow' => false),
 +      ),
 +    ),
 +  );
 +}
 +</code>
 +
 +==== Behaviors/Date ====
 +
 +<code php>
 +public function behaviors() {
 +  return [
 +    [
 +      'class' => TimestampBehavior::className(),
 +      'createdAtAttribute' => 'create_time',
 +      //'updatedAtAttribute' => 'update_time',
 +      'value' => new Expression('NOW()'),
 +    ],
 +  ];
 +}
 +</code>
 ===== Session ===== ===== Session =====
  
Строка 926: Строка 1033:
  }  }
 </code> </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 ===== ===== User =====
Строка 957: Строка 1105:
 </code> </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 ===== ===== Cache =====
Строка 1050: Строка 1220:
  
   apt=get install php5-intl   apt=get install php5-intl
 +
 +==== Перевод (локализация проекта) ====
 +
 +  * https://github.com/lajax/yii2-translate-manager
  
 ===== PHPUnit ===== ===== PHPUnit =====
Строка 1065: Строка 1239:
     * php vendor/bin/phpunit vendor/yiisoft/yii2/yii/test/     * 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
Строка 1071: Строка 1245:
   * http://habrahabr.ru/post/208328/   * http://habrahabr.ru/post/208328/
  
-===== Описание =====+====== Описание ======
  
   * https://github.com/yiisoft/yii2/blob/master/docs/guide/i18n.md#advanced-placeholder-formatting   * https://github.com/yiisoft/yii2/blob/master/docs/guide/i18n.md#advanced-placeholder-formatting