Различия
Показаны различия между двумя версиями страницы.
Предыдущая версия справа и слева Предыдущая версия Следующая версия | Предыдущая версия | ||
yii2:docs [2017/01/04 22:19] – [assetManager] mirocow | yii2:docs [2019/04/18 13:17] (текущий) – [Active Record] mirocow | ||
---|---|---|---|
Строка 289: | Строка 289: | ||
}).success(function(response) { | }).success(function(response) { | ||
}); | }); | ||
+ | </ | ||
+ | |||
+ | ==== Form ==== | ||
+ | |||
+ | * [[yii2: | ||
+ | * [[yii2: | ||
+ | |||
+ | **Подробно** https:// | ||
+ | |||
+ | ===== Ajax ===== | ||
+ | |||
+ | * [[yii2: | ||
+ | * [[yii2: | ||
+ | |||
+ | ==== Pjax ==== | ||
+ | |||
+ | <code php> | ||
+ | use app\modules\cabinet\components\CabinetController; | ||
+ | use app\models\Image; | ||
+ | |||
+ | class CameraController extends CabinetController | ||
+ | { | ||
+ | public function actionFavorite() | ||
+ | { | ||
+ | $id = (int) Yii:: | ||
+ | |||
+ | if (!$id) { | ||
+ | return false; | ||
+ | } | ||
+ | |||
+ | $image = Image:: | ||
+ | |||
+ | if ($image-> | ||
+ | Image:: | ||
+ | return $this-> | ||
+ | } else { | ||
+ | Image:: | ||
+ | return $this-> | ||
+ | } | ||
+ | |||
+ | return false; | ||
+ | } | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | Вывод партиала в main.php | ||
+ | |||
+ | <code php> | ||
+ | <?= $this-> | ||
+ | </ | ||
+ | |||
+ | Отображаемая вьюха favorite.php | ||
+ | |||
+ | <code php> | ||
+ | <?php | ||
+ | use yii\widgets\Pjax; | ||
+ | use yii\helpers\Html; | ||
+ | ?> | ||
+ | <?php Pjax:: | ||
+ | <?= Html:: | ||
+ | <?= Html:: | ||
+ | <?= Html:: | ||
+ | <?= Html:: | ||
+ | <?php Pjax:: | ||
</ | </ | ||
Строка 294: | Строка 358: | ||
* [[yii2: | * [[yii2: | ||
+ | |||
+ | ===== Model / AR / DAO / Запросы к БД ===== | ||
+ | |||
+ | Как получить модель из модуля | ||
+ | |||
+ | <code php> | ||
+ | $user = Yii:: | ||
+ | $profile = Yii:: | ||
+ | </ | ||
+ | |||
+ | ==== Active Record ==== | ||
+ | |||
+ | <code php> | ||
+ | class Post extends ActiveRecord | ||
+ | { | ||
+ | public function getCreator() | ||
+ | { | ||
+ | return $this-> | ||
+ | } | ||
+ | public function getComments() | ||
+ | { | ||
+ | return $this-> | ||
+ | } | ||
+ | public function getTrustComments($isTrust = true) | ||
+ | { | ||
+ | return $this-> | ||
+ | -> | ||
+ | ': | ||
+ | ]) | ||
+ | -> | ||
+ | } | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | <code php> | ||
+ | $price = PriceItem:: | ||
+ | -> | ||
+ | -> | ||
+ | [' | ||
+ | ['>', | ||
+ | ])-> | ||
+ | </ | ||
+ | |||
+ | <code php> | ||
+ | // we receive an ActiveQuery instance | ||
+ | $query = Post:: | ||
+ | |||
+ | // all posts | ||
+ | $posts = $query-> | ||
+ | |||
+ | // looking for all the posts with a condition | ||
+ | $posts = $query | ||
+ | -> | ||
+ | -> | ||
+ | ->all(); | ||
+ | |||
+ | // looking for a post | ||
+ | $post = $query | ||
+ | | ||
+ | | ||
+ | |||
+ | // or easier: " | ||
+ | $post = Post:: | ||
+ | |||
+ | // having transmitted to the factory method not a massive, but a number equivalent to the primary key search | ||
+ | $post = Post:: | ||
+ | | ||
+ | | ||
+ | |||
+ | // we index the result to a necessary attribute | ||
+ | $posts = $query-> | ||
+ | |||
+ | // the result as an array | ||
+ | $posts = $query-> | ||
+ | </ | ||
+ | |||
+ | <code php> | ||
+ | User:: | ||
+ | User:: | ||
+ | </ | ||
+ | |||
+ | === Ключи в эллементах коллекции AR === | ||
+ | |||
+ | <code php> | ||
+ | $query = SparesCategory:: | ||
+ | $query-> | ||
+ | return $row-> | ||
+ | }; | ||
+ | $categories = $query-> | ||
+ | </ | ||
+ | |||
+ | <code php> | ||
+ | $quey = CarMark:: | ||
+ | return $row-> | ||
+ | })-> | ||
+ | </ | ||
+ | |||
+ | === Создание модели из возвращаемы данных Command (с помощью populateRecord()) === | ||
+ | |||
+ | <code php> | ||
+ | $sql = " | ||
+ | LEFT JOIN tbl_form_spares_category fc ON fc.category_id = c.id | ||
+ | WHERE fc.form_id = :form_id AND fc.category_id = : | ||
+ | $select_marks = Yii:: | ||
+ | ': | ||
+ | ': | ||
+ | ])-> | ||
+ | | ||
+ | foreach($marks as $row){ | ||
+ | | ||
+ | // Only yii2 alpha | ||
+ | //$mark = SparesCategoryForm:: | ||
+ | | ||
+ | $mark = new SparesCategoryForm; | ||
+ | SparesCategoryForm:: | ||
+ | | ||
+ | | ||
+ | if(isset($mark-> | ||
+ | | ||
+ | // do somethig | ||
+ | | ||
+ | } | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | * [[Activedataprovider|Activedataprovider]] | ||
+ | * [[SqlDataProvider|SqlDataProvider]] | ||
+ | * [[ArrayDataProvider|ArrayDataProvider]] | ||
+ | ==== Join ==== | ||
+ | |||
+ | === with() === | ||
+ | |||
+ | Не делает SQL JOIN(), применяется не только в реляционых БД (NoSql) | ||
+ | Применяется только для построений конструкций вида **WHERE IN()**, плюс наполняют [[yii2: | ||
+ | |||
+ | === leftJoin() === | ||
+ | |||
+ | Добавляет SQL LEFT JOIN(), применяется только в реляционыых БД, плюс наполняют [[yii2: | ||
+ | |||
+ | <code php> | ||
+ | $this-> | ||
+ | </ | ||
+ | |||
+ | === joinWith() === | ||
+ | |||
+ | Добавляет SQL JOIN(), применяется только в реляционыых БД, плюс наполняют [[yii2: | ||
+ | |||
+ | <code php> | ||
+ | // Выбираем MyModel с relation1 и relation2. | ||
+ | // Все три забираем запросом с JOIN. | ||
+ | $query = MyModel:: | ||
+ | -> | ||
+ | |||
+ | $countQuery = clone $query; | ||
+ | $pages = new Pagination([' | ||
+ | |||
+ | $items = $query | ||
+ | -> | ||
+ | -> | ||
+ | -> | ||
+ | // Забираем дополнительно relation3 и relation4. | ||
+ | // Фильтровать по ним нам не нужно, так что будут | ||
+ | // запросы вида WHERE ID IN (1,2,3,4) или аналоги | ||
+ | // для noSQL. | ||
+ | -> | ||
+ | ->all(); | ||
+ | </ | ||
+ | |||
+ | https:// | ||
+ | |||
+ | === innerJoinWith() === | ||
+ | |||
+ | ==== Validate (Rules) ==== | ||
+ | |||
+ | <code php> | ||
+ | class User extends \yii\db\ActiveRecord | ||
+ | { | ||
+ | // ... | ||
+ | |||
+ | public function rule() | ||
+ | { | ||
+ | return [ | ||
+ | [ | ||
+ | [' | ||
+ | ' | ||
+ | // specifies in which scenario(s) this rule is active. | ||
+ | // if not given, it means it is active in all scenarios | ||
+ | ' | ||
+ | // the following name-value pairs will be used | ||
+ | // to initialize the validator properties | ||
+ | ' | ||
+ | ' | ||
+ | // ... | ||
+ | ], | ||
+ | [ | ||
+ | [' | ||
+ | ' | ||
+ | // specifies in which scenario(s) this rule is active. | ||
+ | // if not given, it means it is active in all scenarios | ||
+ | ' | ||
+ | // the following name-value pairs will be used | ||
+ | // to initialize the validator properties | ||
+ | ' | ||
+ | ' | ||
+ | // ... | ||
+ | ], | ||
+ | ]; | ||
+ | } | ||
+ | |||
+ | } | ||
+ | </ | ||
+ | |||
+ | Пример использования в модели | ||
+ | <code php> | ||
+ | if ($User-> | ||
+ | |||
+ | $User = new User; | ||
+ | $Profile = new Profile; | ||
+ | |||
+ | // validate for ajax request | ||
+ | $Profile-> | ||
+ | if (Yii:: | ||
+ | Yii:: | ||
+ | return ActiveForm:: | ||
+ | } | ||
+ | |||
+ | // validate for normal request | ||
+ | if ($User-> | ||
+ | // do somthing | ||
+ | } | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | Пример применения валидатора без использования модели | ||
+ | <code php> | ||
+ | $email = ' | ||
+ | $validator = new yii\validators\EmailValidator(); | ||
+ | if ($validator-> | ||
+ | echo 'Email is valid.'; | ||
+ | } else { | ||
+ | echo $error; | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | * **Подробно** https:// | ||
+ | * **Список базовых валидаторов: | ||
+ | |||
+ | ==== Scenario ==== | ||
+ | |||
+ | <code php> | ||
+ | class User extends \yii\db\ActiveRecord | ||
+ | { | ||
+ | // ... | ||
+ | |||
+ | public function getProduct() | ||
+ | { | ||
+ | return $this-> | ||
+ | } | ||
+ | |||
+ | public function scenarios() | ||
+ | { | ||
+ | return [ | ||
+ | ' | ||
+ | ' | ||
+ | ' | ||
+ | ], | ||
+ | ]; | ||
+ | } | ||
+ | | ||
+ | public function afterSave($insert) | ||
+ | { | ||
+ | parent:: | ||
+ | if ($this-> | ||
+ | // FIXME: TODO: WIP, TBD | ||
+ | } | ||
+ | } | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | **Подробно** https:// | ||
+ | |||
+ | ==== Relation ==== | ||
+ | |||
+ | <code php> | ||
+ | class Customer extends \yii\db\ActiveRecord | ||
+ | { | ||
+ | // | ||
+ | public function getOrders() | ||
+ | { | ||
+ | return $this-> | ||
+ | } | ||
+ | | ||
+ | // | ||
+ | public function getBigOrders($threshold = 100) | ||
+ | { | ||
+ | return $this-> | ||
+ | -> | ||
+ | -> | ||
+ | } | ||
+ | |||
+ | // Вытащить данные из таблицы модели Item, используя связи из таблицы tbl_order_item | ||
+ | public function getItems() | ||
+ | { | ||
+ | // Получить данные через таблицу tbl_order_item | ||
+ | return $this-> | ||
+ | -> | ||
+ | } | ||
+ | | ||
+ | // | ||
+ | public static function olderThan($query, | ||
+ | { | ||
+ | $query-> | ||
+ | } | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | <code php> | ||
+ | $customer = Customer:: | ||
+ | $orders = $customer-> | ||
+ | $orders = $customer-> | ||
+ | $customers = Customer:: | ||
+ | </ | ||
+ | |||
+ | <code php> | ||
+ | $customer = Customer:: | ||
+ | $order = new Order(); | ||
+ | $order-> | ||
+ | $customer-> | ||
+ | </ | ||
+ | |||
+ | ==== Events ==== | ||
+ | |||
+ | <code php> | ||
+ | class Post extends ActiveRecord | ||
+ | { | ||
+ | public function init() | ||
+ | { | ||
+ | $this-> | ||
+ | // отменяем действие | ||
+ | $event-> | ||
+ | }); | ||
+ | } | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | <code php> | ||
+ | $component-> | ||
+ | </ | ||
+ | ==== Как получить SQL и Параметры из ActiveQuery ==== | ||
+ | |||
+ | <code php> | ||
+ | $query = Post:: | ||
+ | |||
+ | // SQL | ||
+ | echo $query-> | ||
+ | |||
+ | // Params: | ||
+ | print_r($query-> | ||
+ | </ | ||
+ | ==== Объекты доступа к данным (Data Access Objects, DAO) ==== | ||
+ | |||
+ | === Соеденение === | ||
+ | |||
+ | <code php> | ||
+ | $connection = \Yii:: | ||
+ | </ | ||
+ | |||
+ | **Подробно** | ||
+ | |||
+ | * https:// | ||
+ | |||
+ | === Методы запроса === | ||
+ | |||
+ | * queryOne() | ||
+ | * queryAll() | ||
+ | * query() | ||
+ | * queryScalar() | ||
+ | * queryColumn() | ||
+ | |||
+ | **Подробно** | ||
+ | |||
+ | == createCommand == | ||
+ | |||
+ | <code php> | ||
+ | $command = $connection-> | ||
+ | $post = $command-> | ||
+ | </ | ||
+ | |||
+ | <code php> | ||
+ | $connection-> | ||
+ | ' | ||
+ | ' | ||
+ | ])-> | ||
+ | </ | ||
+ | |||
+ | <code php> | ||
+ | $command = $connection-> | ||
+ | $command-> | ||
+ | </ | ||
+ | |||
+ | <code php> | ||
+ | $connection-> | ||
+ | [' | ||
+ | [' | ||
+ | [' | ||
+ | ])-> | ||
+ | </ | ||
+ | |||
+ | <code php> | ||
+ | $connection-> | ||
+ | </ | ||
+ | |||
+ | <code php> | ||
+ | $connection-> | ||
+ | </ | ||
+ | |||
+ | <code php> | ||
+ | $command = $connection-> | ||
+ | $command-> | ||
+ | $post = $command-> | ||
+ | </ | ||
+ | |||
+ | ==== Построитель запросов (Query Builder and Query) ==== | ||
+ | |||
+ | <code php> | ||
+ | $rows = (new \yii\db\Query()) | ||
+ | -> | ||
+ | -> | ||
+ | -> | ||
+ | ->all(); | ||
+ | |||
+ | // which is equivalent to the following code: | ||
+ | |||
+ | $query = (new \yii\db\Query()) | ||
+ | -> | ||
+ | -> | ||
+ | -> | ||
+ | |||
+ | // Create a command. You can get the actual SQL using $command-> | ||
+ | $command = $query-> | ||
+ | |||
+ | // Execute the command: | ||
+ | $rows = $command-> | ||
+ | </ | ||
+ | |||
+ | <code php> | ||
+ | $query = (new \yii\db\Query()) | ||
+ | -> | ||
+ | -> | ||
+ | -> | ||
+ | |||
+ | // Create a command. You can get the actual SQL using $command-> | ||
+ | $command = $query-> | ||
+ | |||
+ | // Execute the command: | ||
+ | $rows = $command-> | ||
+ | </ | ||
+ | |||
+ | Простой спооб получить записи из указанной БД | ||
+ | |||
+ | <code php> | ||
+ | $rows = (new \yii\db\Query()) | ||
+ | -> | ||
+ | -> | ||
+ | // | ||
+ | // | ||
+ | -> | ||
+ | -> | ||
+ | -> | ||
+ | </ | ||
+ | |||
+ | **Подробно** | ||
+ | |||
+ | * https:// | ||
+ | |||
+ | ==== Transactions ==== | ||
+ | |||
+ | <code php> | ||
+ | $transaction = $connection-> | ||
+ | try { | ||
+ | $connection-> | ||
+ | $connection-> | ||
+ | // ... executing other SQL statements ... | ||
+ | $transaction-> | ||
+ | } catch(Exception $e) { | ||
+ | $transaction-> | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | ==== Batch ==== | ||
+ | |||
+ | === Batch === | ||
+ | |||
+ | |||
+ | <code php> | ||
+ | foreach (Customer:: | ||
+ | |||
+ | } | ||
+ | |||
+ | foreach (Customer:: | ||
+ | // $customers — массив из 10 или менее объектов Customer | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | <code php> | ||
+ | $rows = []; | ||
+ | |||
+ | foreach ($models as $model) { | ||
+ | if (!$model-> | ||
+ | // At least one model has invalid data | ||
+ | |||
+ | break; | ||
+ | } | ||
+ | |||
+ | $rows[] = $model-> | ||
+ | } | ||
+ | $rows = \yii\helpers\ArrayHelper:: | ||
+ | $postModel = new Post; | ||
+ | |||
+ | Yii:: | ||
+ | </ | ||
+ | |||
+ | === Each === | ||
+ | |||
+ | <code php> | ||
+ | foreach (Customer:: | ||
+ | |||
+ | } | ||
+ | |||
+ | foreach (Customer:: | ||
+ | // $customers — массив из 10 или менее объектов Customer | ||
+ | } | ||
+ | </ | ||
+ | |||
===== Controller ===== | ===== Controller ===== | ||
Строка 313: | Строка 911: | ||
**Подробно** https:// | **Подробно** https:// | ||
+ | ===== Module ===== | ||
+ | |||
+ | ==== Submodule ==== | ||
+ | |||
+ | Для работы сабмодуля, | ||
+ | <code php> | ||
+ | namespace mirocow\eav; | ||
+ | |||
+ | class Module extends \yii\base\Module { | ||
+ | | ||
+ | // ... | ||
+ | public function init() { | ||
+ | |||
+ | // .. | ||
+ | |||
+ | $this-> | ||
+ | } | ||
+ | | ||
+ | // Пример перенаправления роута в саб модуль admin | ||
+ | public function createController($route) { | ||
+ | | ||
+ | return $this-> | ||
+ | | ||
+ | } | ||
+ | | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | ==== Helpers ==== | ||
+ | |||
+ | * https:// | ||
+ | |||
+ | ==== Behaviors/ | ||
+ | |||
+ | <code php> | ||
+ | public function behaviors() | ||
+ | { | ||
+ | return array( | ||
+ | ' | ||
+ | ' | ||
+ | ' | ||
+ | array(' | ||
+ | array(' | ||
+ | ), | ||
+ | ), | ||
+ | ); | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | ==== Behaviors/ | ||
+ | |||
+ | <code php> | ||
+ | public function behaviors() { | ||
+ | return [ | ||
+ | [ | ||
+ | ' | ||
+ | ' | ||
+ | //' | ||
+ | ' | ||
+ | ], | ||
+ | ]; | ||
+ | } | ||
+ | </ | ||
===== Session ===== | ===== Session ===== | ||
Строка 371: | Строка 1032: | ||
// | // | ||
} | } | ||
+ | </ | ||
+ | |||
+ | ==== 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(' | ||
+ | |||
+ | return $this-> | ||
+ | } | ||
+ | |||
+ | public function __set($name, | ||
+ | { | ||
+ | $name = str_replace(' | ||
+ | |||
+ | $this-> | ||
+ | } | ||
+ | |||
+ | |||
+ | public function options($actionID) | ||
+ | { | ||
+ | return [' | ||
+ | } | ||
+ | |||
+ | public function actionRun() | ||
+ | { | ||
+ | |||
+ | } | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | |||
+ | ===== User ===== | ||
+ | |||
+ | ==== RBAC ==== | ||
+ | |||
+ | * [[yii2: | ||
+ | |||
+ | **Подробно** https:// | ||
+ | |||
+ | ==== Access ==== | ||
+ | |||
+ | <code php> | ||
+ | ' | ||
+ | ' | ||
+ | ' | ||
+ | [ | ||
+ | ' | ||
+ | ' | ||
+ | ' | ||
+ | ], | ||
+ | [ | ||
+ | ' | ||
+ | ' | ||
+ | ' | ||
+ | return \Yii:: | ||
+ | } | ||
+ | ], | ||
+ | ], | ||
+ | ], | ||
+ | </ | ||
+ | |||
+ | |||
+ | ===== Components ===== | ||
+ | |||
+ | Создание объекта компанента | ||
+ | <code php> | ||
+ | $object = Yii:: | ||
+ | ' | ||
+ | ' | ||
+ | ' | ||
+ | ), $param1, $param2); | ||
+ | </ | ||
+ | |||
+ | ===== Theme ===== | ||
+ | |||
+ | <code php> | ||
+ | ' | ||
+ | ' | ||
+ | ' | ||
+ | ' | ||
+ | ), | ||
+ | ), | ||
</ | </ | ||
Строка 465: | Строка 1220: | ||
apt=get install php5-intl | apt=get install php5-intl | ||
+ | |||
+ | ==== Перевод (локализация проекта) ==== | ||
+ | |||
+ | * https:// | ||
===== PHPUnit ===== | ===== PHPUnit ===== | ||
Строка 480: | Строка 1239: | ||
* php vendor/ | * php vendor/ | ||
- | ===== Статьи ===== | + | ====== Статьи |
* https:// | * https:// | ||
Строка 486: | Строка 1245: | ||
* http:// | * http:// | ||
- | ===== Описание ===== | + | ====== Описание |
* https:// | * https:// |