crazy owl yii1=> yii2
TRANSCRIPT
Yii1 => Yii2или "Назад в будущее"
Алексей Смолянов
Контакты:
Email: [email protected]
Skype: alexei.smolyanov
Twitter: @Dlittledev
Начнем с выбора
Кодить или не кодить ?
Наш выбор
PHPОтносительно легок в освоенииБольшое сообществоМасса библиотек, фреймворков и тдРазвивается
О фреймворкахНе всегда нужныИзбыточныМонстрообразныПереусложненыОптимальныМой - самый лучший!
Какой же выбрать ?
Мы выбрали Yii
Почему Yii?Легкий (в меру)ГибкийРасширяемыйПоддерживается (не в пример kohana etc.)Довольно большое комьюнитиРусскоязычный разработчик (-и) ядраПлагины/РасширенияДокументация
Спасибо за внимание
А теперь поехали!
Yii 2.0 is finally coming, after more than three years of intensivedevelopment with almost 10,000 commits by over 300 authors!
Thank you for your support and patience!
Yii2Latest News
OCT 12, 2014
Yii 2.0.0 is released
DEC 3, 2008
Yii 1.0.0 is released
РазвертываниеGit cloneArchivecp /path-from /path-toмиграции для БД
Yii2 - composer!
Миграцииclass m101129_185401_create_news_table extends \yii\db\Migration{ public function up() { $this->createTable('news', [ 'id' => 'pk', 'title' => Schema::TYPE_STRING . ' NOT NULL', 'content' => Schema::TYPE_TEXT, ] ); }
public function down() { $this->dropTable('news'); }}
Типы приложенийYii1basicmany ends - вручную
Yii2basicminimal (Макаров)advanced
Окружения и конфиги
backendcommonconsoleenvironmentsfrontend
Конфиги
Конфигиcommon/config/main.phpcommon/config/main-local.phpfrontend/config/main.phpfrontend/config/main-local.php
Параметрыcommon/config/params.phpcommon/config/params-local.phpfrontend/config/params.phpfrontend/config/params-local.php
Окончательный конфиг
Жизненный цикл приложения
HTTP Headers
Request// $headers is an object of yii\web\HeaderCollection$headers = Yii::$app->request->headers;
// returns the Accept header value$accept = $headers->get('Accept');
if ($headers->has('User-Agent')) { // there is User-Agent header}
Быстрый доступ к заголовкамuserAgentcontentTypeacceptableContentTypesacceptableLanguages
Response$headers = Yii::$app->response->headers;
$headers->add('Pragma', 'no-cache');
$headers->set('Pragma', 'no-cache');
$values = $headers->remove('Pragma');
Yii::$app->response->content = 'hello world!';
$response = Yii::$app->response;
$response->format = \yii\web\Response::FORMAT_JSON;
$response->data = ['message' => 'hello world'];
MVCМодельВидКонтроллер
КонтроллерFiltersActions
Готовые фильтрыpublic function behaviors(){ return [ [ 'class' => 'yii\filters\HttpCache', 'only' => ['index', 'view'], 'lastModified' => function ($action, $params) { $q = new \yii\db\Query(); return $q->from('user')->max('updated_at'); }, ], ];}
Готовые фильтрыuse yii\filters\PageCache;use yii\caching\DbDependency;
public function behaviors(){ return [ 'pageCache' => [ 'class' => PageCache::className(), 'only' => ['index'], 'duration' => 60, 'dependency' => [ 'class' => DbDependency::className(), 'sql' => 'SELECT COUNT(*) FROM post', ], 'variations' => [ \Yii::$app->language, ] ], ];}
Модель
МодельАтрибуты (свойства)Лейблы атрибутовВалидацияСценарии валидацииМассовое присваиваниеПоведенияСкоупы (scopes)
Полезные штуки: sluggablepublic function behaviors(){ return [ [ 'class' => SluggableBehavior::className(), 'attribute' => 'title', 'slugAttribute' => 'slug', ], ];}
Полезные штуки: blamablepublic function behaviors(){ return [ [ 'class' => BlameableBehavior::className(), 'createdByAttribute' => 'author_id', 'updatedByAttribute' => 'updater_id', ], ];}
Полезные штуки: rate limiterpublic function behaviors(){ return [ 'rateLimiter' => [ 'class' => \yii\filters\RateLimiter::className(), ], ];}
Запросы в БД (DAO)// INSERT
$connection->createCommand()->insert('user', [ 'name' => 'Sam', 'age' => 30,])->execute();
// INSERT multiple rows at once
$connection->createCommand()->batchInsert('user', ['name', 'age'], [ ['Tom', 30], ['Jane', 20], ['Linda', 25],])->execute();
// UPDATE
$connection->createCommand()->update('user', ['status' => 1], 'age > 30') ->execute();
// DELETE
$connection->createCommand()->delete('user', 'status = 0')->execute();
Запросы в БД (Query builder)$query->select(['user.name AS author', 'post.title as title']) ->from('user') ->leftJoin('post', 'post.user_id = user.id');
Multiple conditions can simultaneously be set in where using the hash format:
$query->where([ 'status' => 10, 'type' => 2, 'id' => [4, 8, 15, 16, 23, 42],]);
That code will generate the following SQL:
WHERE (̀ ̀= 10) AND (̀ ̀= 2) AND (̀ ̀IN (4, 8, 15, 16, 23, 42))
$query = (new Query()) ->from('user') ->orderBy('id');
foreach ($query->batch() as $users) { // $users is an array of 100 or fewer rows from the user table}
// or if you want to iterate the row one by oneforeach ($query->each() as $user) { // $user represents one row of data from the user table}
status type id
Отображения (views)$this$this->contextшаблонытемывиджетыформы
Формы$form = ActiveForm::begin([ 'id' => 'login-form', 'options' => ['class' => 'form-horizontal'],])
$form->field($model, 'username')$form->field($model, 'password')->passwordInput()
<div class="form-group"> <div class="col-lg-offset-1 col-lg-11"> Html::submitButton('Login', ['class' => 'btn btn-primary']) </div></div>
ActiveForm::end()
$form->field($model, 'password')->passwordInput()
$form->field($model, 'username')->textInput() ->hint('Please enter your name')->label('Name')
Полезные штуки: валидация поусловию
[ ['state', 'required', 'when' => function($model) { return $model->country == 'USA'; }],]
[ ['state', 'required', 'when' => function ($model) { return $model->country == 'USA'; }, 'whenClient' => "function (attribute, value) { return $('#country').val() == 'USA'; }"],]
Полезные штуки: валидация "налету"$email = '[email protected]';$validator = new yii\validators\EmailValidator();
if ($validator->validate($email, $error)) { echo 'Email is valid.';} else { echo $error;}
Полезные штуки: форматированиеecho Yii::$app->formatter->asDate('2014-01-01', 'long'); // output: January 1, 2014echo Yii::$app->formatter->asPercent(0.125, 2); // output: 12.50%echo Yii::$app->formatter->asEmail('[email protected]'); // output: <a href="mailto:[email protected]">[email protected]</a>echo Yii::$app->formatter->asBoolean(true); // output: Yesecho Yii::$app->formatter->asDate(null); // output: (Not set)echo Yii::$app->formatter->format('2014-01-01', 'date'); // output: January 1, 2014echo Yii::$app->formatter->format(0.125, ['percent', 2]); // output: 12.50%
Полезные штуки: хелперы// Remember current URLUrl::remember();
// Remember URL specified. See Url::to() for argument format.Url::remember(['product/view', 'id' => 42]);
// Remember URL specified with a name givenUrl::remember(['product/view', 'id' => 42], 'product');
In the next request we can get URL remembered in the following way:$url = Url::previous();
$productUrl = Url::previous('product');
Полезные штуки: log target'bootstrap' => ['log'],
'components' => [ 'log' => [ 'targets' => [ [ 'class' => 'yii\log\DbTarget', 'levels' => ['error', 'warning'], ], [ 'class' => 'yii\log\EmailTarget', 'levels' => ['error'], 'categories' => ['yii\db\*'], 'message' => [ 'from' => ['[email protected]'], 'to' => ['[email protected]', '[email protected]'], 'subject' => 'Database errors at example.com', ], ], ], ],],
Полезные штуки: кодогенератор
Полезные штуки: дебаггер
И много-много еще всего ...
Вопросы?
Спасибо за внимание!
Yii1 => Yii2или "Назад в будущее"Алексей Смолянов
Контакты:
Email: [email protected]
Skype: alexei.smolyanov
Twitter: @Dlittledev