Это старая версия документа!


Документация по Yii 2 Framework

<?php
return [
    'components' => [
        'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'mysql:host=localhost;dbname=yii2',
            'username' => 'yii2', 
            'password' => '<password>',
        ],
        'cache' => [
            'class' => 'yii\caching\DummyCache',
        ],      
        'urlManager' => [
            'rules' => [
                '<action:(login|logout|about)>' => 'site/<action>',
 
                // ...
 
                ['class' => 'app\components\CarUrlRule', 'connectionID' => 'db', ...],
            ],  
            'enablePrettyUrl' => true,
            'enableStrictParsing' => true,
            'showScriptName' => false,
            'suffix' => '.html',
        ],
    ]
];
echo \Yii::$app->urlManager->createUrl(['site/page', 'id' => 'about']);
// /index.php/site/page/id/about/
echo \Yii::$app->urlManager->createUrl(['date-time/fast-forward', 'id' => 105])
// /index.php?r=date-time/fast-forward&id=105
echo \Yii::$app->urlManager->createAbsoluteUrl('blog/post/index');
// http://www.example.com/index.php/blog/post/index/
$route = [
// ... path + params
];
 
$url = \Yii::$app->urlManager;
$url->createUrl($route);
$url->createAbsoluteUrl($route);
 
$url = Yii::$app->urlManager->createUrl($route);
$url = Yii::$app->urlManager->createAbsoluteUrl($route);
<?php
return [
    // ...
    'components' => [
        'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'enableStrictParsing' => true,
            'suffix' => '.html',
            'rules' => [
                '<action:(login|logout|about)>' => 'site/<action>',
 
                // ...
 
                ['class' => 'app\components\CarUrlRule', 'connectionID' => 'db', ...],
            ],  
        ],
    ],
];

yii\helpers\Url::toRoute

echo Url::toRoute([''], $schema = false); // currently active route
echo Url::toRoute(['view', 'id' => 'contact'], $schema = false); // same controller, different action
echo Url::toRoute(['post/index'], $schema = false); // same module, different controller and action
echo Url::toRoute(['/site/index'], $schema = false); // absolute route no matter what controller is making this call
echo Url::toRoute(['post/read', 'id' => 100, '#' => 'title'], $schema = false)
echo Url::toRoute('', $schema = false); // currently active route
echo Url::toRoute('post/index', $schema = false); // same module, different controller and action
echo Url::toRoute('/site/index', $schema = false); // absolute route no matter what controller is making this call

yii\helpers\Url::to

echo Url::to('', $schema = false); // currently active route
echo Url::to('post/index', $schema = false); // same module, different controller and action
echo Url::to('/site/index', $schema = false); // absolute route no matter what controller is making this call
echo Url::to('@web', $schema = false);
echo Url::canonical(); // get canonical URL for the curent page
echo Url::home(); // get home URL
echo Url::remember(); // save URL to be used later
echo Url::previous(); // get previously saved URL
  • $schema = true - Абсолютный адрес
  • $schema = 'https' - Указание на испоользование шифрованного протокола

Синоним для yii\helpers\Url::toRoute

echo Url::to([''], $schema = false); // currently active route
echo Url::to(['view', 'id' => 'contact'], $schema = false); // same controller, different action
echo Url::to(['post/index'], $schema = false); // same module, different controller and action
echo Url::to(['/site/index'], $schema = false); // absolute route no matter what controller is making this call
echo Url::to(['post/read', 'id' => 100, '#' => 'title'], $schema = false)

Примеры использоватия можно глянуть в тестах https://github.com/yiisoft/yii2/blob/master/tests/unit/framework/helpers/UrlTest.php

yii\helpers\Html::url (old)

echo Html::url(['']); // currently active route
echo Html::url(['view', 'id' => 'contact']); // same controller, different action
echo Html::url(['post/index']); // same module, different controller and action
echo Html::url(['/site/index']); // absolute route no matter what controller is making this call
echo Html::url(['post/read', 'id' => 100, '#' => 'title'])
echo Html::url(''); // currently active route
echo Html::url('post/index'); // same module, different controller and action
echo Html::url('/site/index'); // absolute route no matter what controller is making this call

вместо старых методов нада использовать yii\helpers\Url::to

Примеры использоватия можно глянуть в тестах https://github.com/yiisoft/yii2/blob/master/tests/unit/framework/helpers/UrlTest.php

echo $this->createUrl([''], $schema = null); // currently active route
echo $this->createUrl(['view', 'id' => 'contact'], $schema = null); // same controller, different action
echo $this->createUrl(['post/index'], $schema = null); // same module, different controller and action
echo $this->createUrl(['/site/index'], $schema = null); // absolute route no matter what controller is making this call
echo $this->createUrl(['post/read', 'id' => 100, '#' => 'title'], $schema = null)
echo $this->createUrl('', $schema = null); // currently active route
echo $this->createUrl('post/index', $schema = null); // same module, different controller and action
echo $this->createUrl('/site/index', $schema = null); // absolute route no matter what controller is making this call

createAbsoluteUrl (old)

Усли $this - это yii\web\Controller

echo $this->createAbsoluteUrl([''], $schema = null); // currently active route
echo $this->createAbsoluteUrl(['view', 'id' => 'contact'], $schema = null); // same controller, different action
echo $this->createAbsoluteUrl(['post/index'], $schema = null); // same module, different controller and action
echo $this->createAbsoluteUrl(['/site/index'], $schema = null); // absolute route no matter what controller is making this call
echo $this->createAbsoluteUrl(['post/read', 'id' => 100, '#' => 'title'], $schema = null)

вместо старых методов надо использовать yii\helpers::toRoute

Усли $this - это yii\web\Controller

echo $this->createAbsoluteUrl('', $schema = null); // currently active route
echo $this->createAbsoluteUrl('post/index', $schema = null); // same module, different controller and action
echo $this->createAbsoluteUrl('/site/index', $schema = null); // absolute route no matter what controller is making this call

вместо старых методов надо использовать yii\helpers::toRoute

GET

Yii::$app->request->get();
Yii::$app->request->getQueryParams();
Yii::$app->request->getQueryParam('File');
Yii::$app->request->get('File');

POST

Yii::$app->request->post();
Yii::$app->request->getBodyParams();
Yii::$app->request->getBodyParam('File');
Yii::$app->request->post('File');
$this->registerCssFile();
$this->registerJsFile();

Вставка кода внутри представления

В примере производится вставка JS кода из assets c применением переменной в скрипте JS_FABRIC_CAR_URL

$this = Yii::$app->view;
<?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]);
?> 
'components' => [
    'assetManager' => [
        'class' => 'yii\web\AssetManager',
        'forceCopy' => true,          
    ],
],
  • forceCopy - Включает постоянное обновление асетов

через ajaxSetup

Добавление csrfToken в Ajax запрос (Yii2)

$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');

или через header

$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');

или через JQuery

      $.ajax({
        url: 'http://site?controller/action',
        type: 'post',
        data: {payload: payload, _csrf: yii.getCsrfToken()},        
        dataType: 'json',
      }).success(function(response) {
      });
$className = 'backend\controllers\SiteController';
$controller = Yii::createObject($className, [$id, $this]);
// ['label' => 'Добавление', 'url' => ['/admin/user/create']]
Html::a("Log in here", ["user/reset", "hash" => $hash, "sid" => $sid]);
Html::url(["user/reset", "hash" => $hash, "sid" => $sid]);

Подробно https://github.com/yiisoft/yii2/blob/master/docs/guide/url.md

Yii::$app->session->get('key');
Yii::$app->session->set('key', 'value');

В контролере

Yii::$app->session->setFlash('info', $shell->output);
return $this->redirect('/site');

return делать обязательно. инчаче после редиректа сообщение не выведется

Вывод стандартным способом

<?php foreach (Yii::$app->session->getAllFlashes() as $key => $message) {
  echo '<div class="alert alert-' . $key . '">' . $message . '</div>';
} ?>

Вывод с помощью виджета loveorigami/yii2-notification-wrapper

<?= Wrapper::widget([
  'layerClass' => 'lo\modules\noty\layers\Noty',
]);?>

Данный виджет поддерживает большое кол-во виджетов обображения таких как:

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
 if(Yii::$app->request->isConsoleRequest){
   //
 }
// Создать зависимость от времени модификации файла example.txt.
$dependency = new \yii\caching\FileDependency(['fileName' => 'example.txt']);
 
// Данные устаревают через 30 секунд.
// Данные могут устареть и раньше, если example.txt будет изменён.
$cache->set($key, $data, 30, $dependency);
 
// Кэш будет проверен, если данные устарели.
// Он также будет проверен, если указанная зависимость была изменена.
// Вернется false, если какое-либо из этих условий выполнено.
$data = $cache->get($key);
  • yii\caching\ChainedDependency: зависимость меняется, если любая зависимость в цепочке изменяется;
  • yii\caching\DbDependency: зависимость меняется, если результат некоторого определенного SQL запроса изменён;
  • yii\caching\ExpressionDependency: зависимость меняется, если результат определенного PHP выражения изменён;
  • yii\caching\FileDependency: зависимость меняется, если изменилось время последней модификации файла;
  • yii\caching\TagDependency: Связывает кэшированные данные элемента с одним или несколькими тегами. Вы можете аннулировать кэширование данных элементов с заданным тегом(тегами) по вызову. invalidate();
$result = $db->cache(function ($db) {
 
    // Результат SQL запроса будет возвращен из кэша если
    // кэширование запросов включено и результат запроса присутствует в кэше
    return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();
 
});
 
$result = Customer::getDb()->cache(function ($db) {
    return Customer::find()->where(['id' => 1])->one();
});
$duration = 60;     // кэширование результата на 60 секунд
$dependency = ...;  // параметры зависимости
 
$result = $db->cache(function ($db) {
 
    // ... выполнять SQL запросы здесь ...
 
    return $result;
 
}, $duration, $dependency);
$result = $db->cache(function ($db) {
 
    // SQL запросы, которые используют кэширование
 
    $db->noCache(function ($db) {
 
        // SQL запросы, которые не используют кэширование
 
    });
 
    // ...
 
    return $result;
});
// использовать кэширование запросов и установить срок действия кэша на 60 секунд
$customer = $db->createCommand('SELECT * FROM customer WHERE id=1')->cache(60)->queryOne();
$result = $db->cache(function ($db) {
 
    // Используется кэширование SQL запросов
 
    // не использовать кэширование запросов для этой команды
    $customer = $db->createCommand('SELECT * FROM customer WHERE id=1')->noCache()->queryOne();
 
    // ...
 
    return $result;
});
apt=get install php5-intl