Полезные штуки в Yii

---------Публикация ресурсов:--------------------
$datepicker = Yii::app()->clientScript;
$datepicker->packages = array(
            'datepicker' => array(
                'basePath' => 'application.vendor.eternicode.bootstrap-datepicker',
                'baseUrl',
                'js' => array('dist/js/bootstrap-datepicker.js', 
                    'dist/locales/bootstrap-datepicker.'
                    . substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2) . '.min.js'),
                'css' => array('dist/css/bootstrap-datepicker.min.css'),
                'depends' => array('jquery'),
                'position' => CClientScript::POS_END,
            ),
        );
$datepicker->registerPackage('datepicker');

---Установка Yii1.1.16 спомощью Composer:--------
Переходим с свою корневую папку будущего сайта:
cd /srv/Sites/yiiblog/webroot/
curl -sS https://getcomposer.org/installer | php;
vim composer.json
>>>>put into composer.json file:>>>>>>>>>>
{
     "require": {
         "fxp/composer-asset-plugin": ">=1.0.0",
         "yiisoft/yii": "1.*",
         "crisu83/yiistrap": ">=2.0.3",
         "2amigos/yiiwheels": "dev-master"
     },
     "minimum-stability": "dev"
}
>>>>>>>>>>>>>>endfile>>>>>>>>>>>>>>>
php composer.phar install
vendor/yiisoft/yii/framework/yiic webapp .
php composer.phar require "twbs/bootstrap"
Сначала установим Yiistrap в конфиге добавим:
>>>>>>>>>>>>main.php:>>>>>>>>>>>>>>>
...
'aliases'=>array(
        'bootstrap'=>realpath(__DIR__ . '/../extensions/yiistrap'),
        'vendor.twbs.bootstrap.dist' => realpath(__DIR__ . '/../../vendor/twbs/bootstrap/dist'),
),
...
'import'=>array(
         ...
        'bootstrap.behaviors.*',
        'bootstrap.components.*',
        'bootstrap.form.*',
        'bootstrap.gii.bootstrap.*',
        'bootstrap.helpers.*',
        'bootstrap.widgets.*',
 ),
'modules'=>array(
 ...
 'gii'=>array(
 ...
       'generatorPaths'=>array('bootstrap.gii'),
    ),
),
'components'=>array(
    ...
    'bootstrap'=>array(
        'class'=>'bootstrap.components.TbApi',
    ),
    ...
),

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Check if bootstrap is in extensions/bootstrap. That way it should work.
sudo chmod -R 0777 ./../../protected/
----Установка Yii2 (Composer должен быть уже установлен!):---------
if base apps:
php composer.phar create-project yiisoft/yii2-app-basic basic 2.0.3
if advanced application:
php composer.phar create-project yiisoft/yii2-app-advanced advanced 2.0.3

----ЗАпись HTML в DB:------------------------------------------
$purifier = new CHtmlPurifier();
$post->text = $purifier->purify($post->text);
$post->save();
--------------Интернационализация i18n:------------------------
В конфиге вначале добавляем:
    'language' => substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2),
    'sourceLanguage' => 'en-US',
    ...
 Используя файл с следующим конфигом можно получать массивы перевода автоматически командой:
 yiic message protected/config/translation_config.php
 ---php file:------
/**
Error: the configuration file is not specified.

USAGE
  yiic message <config-file>

DESCRIPTION
  This command searches for messages to be translated in the specified
  source files and compiles them into PHP arrays as message source.

PARAMETERS
 * config-file: required, the path of the configuration file. You can find
   an example in framework/messages/config.php.

   The file can be placed anywhere and must be a valid PHP script which
   returns an array of name-value pairs. Each name-value pair represents
   a configuration option.

   The following options are available:
*/
return array(
    'sourcePath'=>'/srv/Sites/hotel/webroot',//: string, root directory of all source files.
    'messagePath'=>'/srv/Sites/hotel/webroot/protected/messages',
    //: string, root directory containing message translations.
    'languages'=>array('ru','ua'),//: array, list of language codes that the extracted messages
     //should be translated to. For example, array('zh_cn','en_au').
    'fileTypes'=>array('php'),//: array, a list of file extensions (e.g. 'php', 'xml').
     //Only the files whose extension name can be found in this list
     //will be processed. If empty, all files will be processed.
    'exclude'=>array('vendor','assets'),
    //: array, a list of directory and file exclusions. Each
     //exclusion can be either a name or a path. If a file or directory name
    //or path matches the exclusion, it will not be copied. For example,
    //an exclusion of '.svn' will exclude all files and directories whose
    //name is '.svn'. And an exclusion of '/a/b' will exclude file or
    //directory 'sourcePath/a/b'.
    'translator'=>'Yii::t',//: the name of the function for translating messages.
     //Defaults to 'Yii::t'. This is used as a mark to find messages to be
     //translated. Accepts both string for single function name or array for
    //multiple function names.
    'overwrite'=>true,//: if message file must be overwritten with the merged messages.
    'removeOld'=>true,//: if message no longer needs translation it will be removed,
     //instead of being enclosed between a pair of '@@' marks.
    'sort'=>'odsolete',//: sort messages by key when merging, regardless of their translation
     //state (new, obsolete, translated.)
    'fileHeader'=>false,//: A boolean indicating whether the file should contain a default
     //comment that explains the message file or a string representing
     //some PHP code or comment to add before the return tag in the message file.
);
---- end php file -----
 Если на сайте используются модули, и Вы хотите хранить переводы в папках внутри модуля блога, то вместо
 Yii::t('blog', 'Title');
 используйте имя класса модуля:
 Yii::t('BlogModule.blog', 'Title');
 Теперь можно сложить файлы blog.php в языковые поддиректории папки protected/modules/blog/messages.
---------------частоиспользуемые методы-хелперы:---------------
$this->createUrl('site/page', array('view'=>'about'), string $ampersand='&');
CHtml::link('Link Text',array('controller/action','id'=>$val));
$this->redirect($this->createUrl('site/page', array('view' => 'thanks')));
Yii::app()->request->hostInfo;
Yii::app()->getBaseUrl(true);
if ($this->getRoute() === 'site/index') echo 'class="active"';
Yii::app()->controller->module->id;
$this->module->id;
Yii::app()->db->getLastInsertID();
Сессии session:
Yii::app()->session->add(‘product’, $productId);
Yii::app()->session->get(‘product’);
Yii::app()->session->remove(‘product’);
unset(Yii::app()->session[$variable][$key]);
Cookie
$cookie=Yii::app()->request->cookies[$name];
$value=$cookie->value;
$cookie=new CHttpCookie($name,$value);
Yii::app()->request->cookies[$name]=$cookie;
$timestamp=CDateTimeParser::parse($dateFromDatabase,'yyyy-MM-dd hh:mm:ss');
<?php echo CPasswordHelper::hashPassword('pass_to_sonbyadmin', 14); ?>
--------------
<?php
$this->widget('zii.widgets.grid.CGridView', array(
  'dataProvider' => $dataProvider,
  'columns' => array(
    array(
      'header'=>'Хитрая колонка',
      'value'=>'$this->grid->getOwner()->renderPartial(\'cells/_myCustomCell\', array(\'data\'=>$data),true',
      'type'=>'raw',
    ),
  ), 
...
Как это работает
В папке с вьюшками контроллера, который выводит гридвью на экран создаем папку cells, а в ней по желанию файлы вьюшек (в нашем случае это _myCustomCell), где данные модели доступны через переменную $data (а не $model, что важно). После этого в коде объявления колонки мы указываем значение, и выводим «сырое» ('type'=>'raw') представление данных — то есть голый неэкранированный HTML из вьюшки.
--------Simple pagination for DAO model:-----------------
$sql = 'select j.id,j.title from journey j';
$count_query = 'select count(*) from journey';
$item_count = Yii::app()->db->createCommand($count_query)->queryScalar();
$dataProvider = new CSqlDataProvider($sql, array(
    'keyField' => 'id',
    'totalItemCount' => $item_count,
    'pagination' => array(
        'pageSize' => 3,
    ),
    ));
$model = $dataProvider->getData();
$this->widget('CLinkPager'/*or 'CLinkPager'*/, array(
    'pages' => $dataProvider->pagination)
);
foreach ($model as $val) {
    echo '<p>name: ' . $val['title'] . '</p>';
}
----------------Проверка уникальности в модели:-------
array('email', 'unique', 'className'=>'User', 'attributeName'=>'email'), ..
---------------show qty sql queries and here time execution:---------
list($queryCount, $queryTime) = Yii::app()->db->getStats();
echo "Query count: $queryCount, Total query time: ".sprintf('%0.5f',$queryTime)."s";

Комментариев нет :

Отправить комментарий

Благодарю за ваше участие!