YII
Yii – Load modules dynamically from db or directory
In this article, we are going to discuss about How to load the modules dynamically from DB or from Directory in YII framework. In Yii application development, we can set up modules configuration in config.php. Sometimes, we need to load modules configuration from database or directory glob. After searching the topic in google and comparing some solutions, I found the elegant way to implement this. Hope it can help.
You can modify the index.php file of your Yii application.
require_once($yii);
class ExtendableWebApp extends CWebApplication {
protected function init() {
// this example dynamically loads every module which can be found
// under `modules` directory
// this can be easily done to load modules
// based on MySQL db or any other as well
foreach (glob(dirname(__FILE__).'/protected/modules/*', GLOB_ONLYDIR) as $moduleDirectory) {
$this->setModules(array(basename($moduleDirectory)));
}
return parent::init();
}
}
$app=new ExtendableWebApp($config);
$app->run();
Reference: http://www.yiiframework.com/forum/index.php/topic/23467-dynamically-load-modules-models-and-configurations/page__p__144316#entry144316
You can modify the index.php file of your Yii application.
require_once($yii);
class ExtendableWebApp extends CWebApplication {
protected function init() {
// this example dynamically loads every module which can be found
// under `modules` directory
// this can be easily done to load modules
// based on MySQL db or any other as well
foreach (glob(dirname(__FILE__).'/protected/modules/*', GLOB_ONLYDIR) as $moduleDirectory) {
$this->setModules(array(basename($moduleDirectory)));
}
return parent::init();
}
}
$app=new ExtendableWebApp($config);
$app->run();
Reference: http://www.yiiframework.com/forum/index.php/topic/23467-dynamically-load-modules-models-and-configurations/page__p__144316#entry144316
PHP CMS Frameworks
June 17, 2015
Read more →
YII
Export to Excel from Grid view in YII Framework 2.0
In this article, we are going to discuss about How to export the grid view data in to excel in YII Frameworkk 2.0. The Yii PHP project started on January 1, 2008, in order to fix some drawbacks of the PRADO framework.
For example, in its early versions PRADO was slow when handling complex pages, had a steep learning curve and many controls were difficult to customize, while Yii was much more efficient at that time. In October 2008, after ten months of private development, the first alpha version of Yii was released. On December 3, 2008, Yii 1.0 was formally released.
Step 1 : Install PHP Excel In Yiiframework 2.0
Add below line in composer.json and update composer to install phpoffice excel.
"require": {
......
"phpoffice/phpexcel": "*"
......
}
Step 2 : Excel Gridview Class In Yiiframework 2.0
Create a class file with name 'ExcelGrid.php' by extending the basic GridView class.
<?php
namespace app\components;
use Yii;
use Closure;
use yii\i18n\Formatter;
use yii\base\InvalidConfigException;
use yii\helpers\Url;
use yii\helpers\Html;
use yii\helpers\Json;
use yii\helpers\ArrayHelper;
use yii\widgets\BaseListView;
use yii\base\Model;
use \PHPExcel;
use \PHPExcel_IOFactory;
use \PHPExcel_Settings;
use \PHPExcel_Style_Fill;
use \PHPExcel_Writer_IWriter;
use \PHPExcel_Worksheet;
class ExcelGrid extends \yii\grid\GridView
{
public $columns_array;
public $properties;
public $filename='excel';
public $extension='xlsx';
private $_provider;
private $_visibleColumns;
private $_beginRow = 1;
private $_endRow;
private $_endCol;
private $_objPHPExcel;
private $_objPHPExcelSheet;
private $_objPHPExcelWriter;
public function init(){
parent::init();
}
public function run(){
//$this->test();
$this->init_provider();
$this->init_excel_sheet();
$this->initPHPExcelWriter('Excel2007');
$this->generateHeader();
$row = $this->generateBody();
$writer = $this->_objPHPExcelWriter;
$this->setHttpHeaders();
$writer->save('php://output');
Yii::$app->end();
//$writer->save('test.xlsx');
parent::run();
}
public function init_provider(){
$this->_provider = clone($this->dataProvider);
}
public function init_excel_sheet(){
$this->_objPHPExcel=new PHPExcel();
$creator = '';
$title = '';
$subject = '';
$description = 'Excel Grid';
$category = '';
$keywords = '';
$manager = '';
$created = date("Y-m-d H:i:s");
$lastModifiedBy = '';
extract($this->properties);
$this->_objPHPExcel->getProperties()
->setCreator($creator)
->setTitle($title)
->setSubject($subject)
->setDescription($description)
->setCategory($category)
->setKeywords($keywords)
->setManager($manager)
->setCompany($company)
->setCreated($created)
->setLastModifiedBy($lastModifiedBy);
$this->_objPHPExcelSheet = $this->_objPHPExcel->getActiveSheet();
}
public function initPHPExcelWriter($writer)
{
$this->_objPHPExcelWriter = PHPExcel_IOFactory::createWriter(
$this->_objPHPExcel,
$writer
);
}
public function generateHeader(){
$this->setVisibleColumns();
$sheet = $this->_objPHPExcelSheet;
$colFirst = self::columnName(1);
$this->_endCol = 0;
foreach ($this->_visibleColumns as $column) {
$this->_endCol++;
$head = ($column instanceof \yii\grid\DataColumn) ? $this->getColumnHeader($column) : $column->header;
$cell = $sheet->setCellValue(self::columnName($this->_endCol) . $this->_beginRow, $head, true);
}
$sheet->freezePane($colFirst . ($this->_beginRow + 1));
}
public function generateBody()
{
$columns = $this->_visibleColumns;
$models = array_values($this->_provider->getModels());
if (count($columns) == 0) {
$cell = $this->_objPHPExcelSheet->setCellValue('A1', $this->emptyText, true);
$model = reset($models);
return 0;
}
$keys = $this->_provider->getKeys();
$this->_endRow = 0;
foreach ($models as $index => $model) {
$key = $keys[$index];
$this->generateRow($model, $key, $index);
$this->_endRow++;
}
// Set autofilter on
$this->_objPHPExcelSheet->setAutoFilter(
self::columnName(1) .
$this->_beginRow .
":" .
self::columnName($this->_endCol) .
$this->_endRow
);
return ($this->_endRow > 0) ? count($models) : 0;
}
public function generateRow($model, $key, $index)
{
$cells = [];
/* @var $column Column */
$this->_endCol = 0;
foreach ($this->_visibleColumns as $column) {
if ($column instanceof \yii\grid\SerialColumn || $column instanceof \yii\grid\ActionColumn) {
continue;
} else {
$format = $column->format;
$value = ($column->content === null) ?
$this->formatter->format($column->getDataCellValue($model, $key, $index), $format) :
call_user_func($column->content, $model, $key, $index, $column);
}
if (empty($value) && !empty($column->attribute) && $column->attribute !== null) {
$value =ArrayHelper::getValue($model, $column->attribute, '');
}
$this->_endCol++;
$cell = $this->_objPHPExcelSheet->setCellValue(self::columnName($this->_endCol) . ($index + $this->_beginRow + 1),
strip_tags($value), true);
}
}
protected function setVisibleColumns()
{
$cols = [];
foreach ($this->columns as $key => $column) {
if ($column instanceof \yii\grid\SerialColumn || $column instanceof \yii\grid\ActionColumn) {
continue;
}
$cols[] = $column;
}
$this->_visibleColumns = $cols;
}
public function getColumnHeader($col)
{
if(isset($this->columns_array[$col->attribute]))
return $this->columns_array[$col->attribute];
/* @var $model yii\base\Model */
if ($col->header !== null || ($col->label === null && $col->attribute === null)) {
return trim($col->header) !== '' ? $col->header : $col->grid->emptyCell;
}
$provider = $this->dataProvider;
if ($col->label === null) {
if ($provider instanceof ActiveDataProvider && $provider->query instanceof ActiveQueryInterface) {
$model = new $provider->query->modelClass;
$label = $model->getAttributeLabel($col->attribute);
} else {
$models = $provider->getModels();
if (($model = reset($models)) instanceof Model) {
$label = $model->getAttributeLabel($col->attribute);
} else {
$label =$col->attribute;
}
}
} else {
$label = $col->label;
}
return $label;
}
public static function columnName($index)
{
$i = $index - 1;
if ($i >= 0 && $i < 26) {
return chr(ord('A') + $i);
}
if ($i > 25) {
return (self::columnName($i / 26)) . (self::columnName($i % 26 + 1));
}
return 'A';
}
protected function setHttpHeaders()
{
header("Cache-Control: no-cache");
header("Expires: 0");
header("Pragma: no-cache");
header("Content-Type: application/{$this->extension}");
header("Content-Disposition: attachment; filename={$this->filename}.{$this->extension}");
}
}
Add the above class in 'project/components' folder and defined namespace as
namespace app\components;
Step 3 : Gridview To Excel In Yiiframework 2.0
After completed above steps, Just you have to call 'ExcelGrid' widget using namespace to export data as excel in yii2.
Excel.php
<?php
\app\components\ExcelGrid::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
//'extension'=>'xlsx',
//'filename'=>'excel',
'properties' =>[
//'creator' =>'',
//'title' => '',
//'subject' => '',
//'category' => '',
//'keywords' => '',
//'manager' => '',
],
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'username',
'createdby',
'createdon',
],
]);
?>
Controller.php
<?php
............
class CategoryController extends Controller
public function actionExcel()
{
$searchModel = new categorySearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->renderPartial('excel', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
public function actionIndex()
{
$searchModel = new categorySearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
............
?>
For example, in its early versions PRADO was slow when handling complex pages, had a steep learning curve and many controls were difficult to customize, while Yii was much more efficient at that time. In October 2008, after ten months of private development, the first alpha version of Yii was released. On December 3, 2008, Yii 1.0 was formally released.
Step 1 : Install PHP Excel In Yiiframework 2.0
Add below line in composer.json and update composer to install phpoffice excel.
"require": {
......
"phpoffice/phpexcel": "*"
......
}
Step 2 : Excel Gridview Class In Yiiframework 2.0
Create a class file with name 'ExcelGrid.php' by extending the basic GridView class.
<?php
namespace app\components;
use Yii;
use Closure;
use yii\i18n\Formatter;
use yii\base\InvalidConfigException;
use yii\helpers\Url;
use yii\helpers\Html;
use yii\helpers\Json;
use yii\helpers\ArrayHelper;
use yii\widgets\BaseListView;
use yii\base\Model;
use \PHPExcel;
use \PHPExcel_IOFactory;
use \PHPExcel_Settings;
use \PHPExcel_Style_Fill;
use \PHPExcel_Writer_IWriter;
use \PHPExcel_Worksheet;
class ExcelGrid extends \yii\grid\GridView
{
public $columns_array;
public $properties;
public $filename='excel';
public $extension='xlsx';
private $_provider;
private $_visibleColumns;
private $_beginRow = 1;
private $_endRow;
private $_endCol;
private $_objPHPExcel;
private $_objPHPExcelSheet;
private $_objPHPExcelWriter;
public function init(){
parent::init();
}
public function run(){
//$this->test();
$this->init_provider();
$this->init_excel_sheet();
$this->initPHPExcelWriter('Excel2007');
$this->generateHeader();
$row = $this->generateBody();
$writer = $this->_objPHPExcelWriter;
$this->setHttpHeaders();
$writer->save('php://output');
Yii::$app->end();
//$writer->save('test.xlsx');
parent::run();
}
public function init_provider(){
$this->_provider = clone($this->dataProvider);
}
public function init_excel_sheet(){
$this->_objPHPExcel=new PHPExcel();
$creator = '';
$title = '';
$subject = '';
$description = 'Excel Grid';
$category = '';
$keywords = '';
$manager = '';
$created = date("Y-m-d H:i:s");
$lastModifiedBy = '';
extract($this->properties);
$this->_objPHPExcel->getProperties()
->setCreator($creator)
->setTitle($title)
->setSubject($subject)
->setDescription($description)
->setCategory($category)
->setKeywords($keywords)
->setManager($manager)
->setCompany($company)
->setCreated($created)
->setLastModifiedBy($lastModifiedBy);
$this->_objPHPExcelSheet = $this->_objPHPExcel->getActiveSheet();
}
public function initPHPExcelWriter($writer)
{
$this->_objPHPExcelWriter = PHPExcel_IOFactory::createWriter(
$this->_objPHPExcel,
$writer
);
}
public function generateHeader(){
$this->setVisibleColumns();
$sheet = $this->_objPHPExcelSheet;
$colFirst = self::columnName(1);
$this->_endCol = 0;
foreach ($this->_visibleColumns as $column) {
$this->_endCol++;
$head = ($column instanceof \yii\grid\DataColumn) ? $this->getColumnHeader($column) : $column->header;
$cell = $sheet->setCellValue(self::columnName($this->_endCol) . $this->_beginRow, $head, true);
}
$sheet->freezePane($colFirst . ($this->_beginRow + 1));
}
public function generateBody()
{
$columns = $this->_visibleColumns;
$models = array_values($this->_provider->getModels());
if (count($columns) == 0) {
$cell = $this->_objPHPExcelSheet->setCellValue('A1', $this->emptyText, true);
$model = reset($models);
return 0;
}
$keys = $this->_provider->getKeys();
$this->_endRow = 0;
foreach ($models as $index => $model) {
$key = $keys[$index];
$this->generateRow($model, $key, $index);
$this->_endRow++;
}
// Set autofilter on
$this->_objPHPExcelSheet->setAutoFilter(
self::columnName(1) .
$this->_beginRow .
":" .
self::columnName($this->_endCol) .
$this->_endRow
);
return ($this->_endRow > 0) ? count($models) : 0;
}
public function generateRow($model, $key, $index)
{
$cells = [];
/* @var $column Column */
$this->_endCol = 0;
foreach ($this->_visibleColumns as $column) {
if ($column instanceof \yii\grid\SerialColumn || $column instanceof \yii\grid\ActionColumn) {
continue;
} else {
$format = $column->format;
$value = ($column->content === null) ?
$this->formatter->format($column->getDataCellValue($model, $key, $index), $format) :
call_user_func($column->content, $model, $key, $index, $column);
}
if (empty($value) && !empty($column->attribute) && $column->attribute !== null) {
$value =ArrayHelper::getValue($model, $column->attribute, '');
}
$this->_endCol++;
$cell = $this->_objPHPExcelSheet->setCellValue(self::columnName($this->_endCol) . ($index + $this->_beginRow + 1),
strip_tags($value), true);
}
}
protected function setVisibleColumns()
{
$cols = [];
foreach ($this->columns as $key => $column) {
if ($column instanceof \yii\grid\SerialColumn || $column instanceof \yii\grid\ActionColumn) {
continue;
}
$cols[] = $column;
}
$this->_visibleColumns = $cols;
}
public function getColumnHeader($col)
{
if(isset($this->columns_array[$col->attribute]))
return $this->columns_array[$col->attribute];
/* @var $model yii\base\Model */
if ($col->header !== null || ($col->label === null && $col->attribute === null)) {
return trim($col->header) !== '' ? $col->header : $col->grid->emptyCell;
}
$provider = $this->dataProvider;
if ($col->label === null) {
if ($provider instanceof ActiveDataProvider && $provider->query instanceof ActiveQueryInterface) {
$model = new $provider->query->modelClass;
$label = $model->getAttributeLabel($col->attribute);
} else {
$models = $provider->getModels();
if (($model = reset($models)) instanceof Model) {
$label = $model->getAttributeLabel($col->attribute);
} else {
$label =$col->attribute;
}
}
} else {
$label = $col->label;
}
return $label;
}
public static function columnName($index)
{
$i = $index - 1;
if ($i >= 0 && $i < 26) {
return chr(ord('A') + $i);
}
if ($i > 25) {
return (self::columnName($i / 26)) . (self::columnName($i % 26 + 1));
}
return 'A';
}
protected function setHttpHeaders()
{
header("Cache-Control: no-cache");
header("Expires: 0");
header("Pragma: no-cache");
header("Content-Type: application/{$this->extension}");
header("Content-Disposition: attachment; filename={$this->filename}.{$this->extension}");
}
}
Add the above class in 'project/components' folder and defined namespace as
namespace app\components;
Step 3 : Gridview To Excel In Yiiframework 2.0
After completed above steps, Just you have to call 'ExcelGrid' widget using namespace to export data as excel in yii2.
Excel.php
<?php
\app\components\ExcelGrid::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
//'extension'=>'xlsx',
//'filename'=>'excel',
'properties' =>[
//'creator' =>'',
//'title' => '',
//'subject' => '',
//'category' => '',
//'keywords' => '',
//'manager' => '',
],
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'username',
'createdby',
'createdon',
],
]);
?>
Controller.php
<?php
............
class CategoryController extends Controller
public function actionExcel()
{
$searchModel = new categorySearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->renderPartial('excel', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
public function actionIndex()
{
$searchModel = new categorySearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
............
?>
PHP CMS Frameworks
April 15, 2015
Read more →
YII
Cookies Handling In Yii PHP Framework 2.0
In this article, we are going to discuss about How to handle cookies in YII Php framework. A cookie is a small file that the server embeds on the user's computer and it is often used to identify a user. In plain PHP we can access using $_COOKIE global variable.
In Yii, cookie is an object of 'yii\web\Cookie'. 'yii\web\Request' and 'yii\web\Response' maintain a collection of cookies via the property named cookies.
Set Cookies
Using below code we can send the new cookie to the user.
$cookies = Yii::$app->response->cookies;
// add a new cookie to the response to be sent
$cookies->add(new \yii\web\Cookie([
'name' => 'username',
'value' => 'yiiuser',
]));
Get Cookies
We can get get the cookies from the yii app request.
$cookies = Yii::$app->request->cookies;
// get the cookie value
$username = $cookies->getValue('username');
//return default value if the cookie is not available
$username = $cookies->getValue('username', 'default');
// Check the availability of the cookie
if ($cookies->has('username'))
echo $cookies->getValue('username');
Remove Cookies
To delete the cookie value, we can use the remove() function of yii.
$cookies = Yii::$app->response->cookies;
$cookies->remove('username');
unset($cookies['username']);
In Yii, cookie is an object of 'yii\web\Cookie'. 'yii\web\Request' and 'yii\web\Response' maintain a collection of cookies via the property named cookies.
Set Cookies
Using below code we can send the new cookie to the user.
$cookies = Yii::$app->response->cookies;
// add a new cookie to the response to be sent
$cookies->add(new \yii\web\Cookie([
'name' => 'username',
'value' => 'yiiuser',
]));
Get Cookies
We can get get the cookies from the yii app request.
$cookies = Yii::$app->request->cookies;
// get the cookie value
$username = $cookies->getValue('username');
//return default value if the cookie is not available
$username = $cookies->getValue('username', 'default');
// Check the availability of the cookie
if ($cookies->has('username'))
echo $cookies->getValue('username');
Remove Cookies
To delete the cookie value, we can use the remove() function of yii.
$cookies = Yii::$app->response->cookies;
$cookies->remove('username');
unset($cookies['username']);
PHP CMS Frameworks
March 11, 2015
Read more →
YII
Remove index.php from URL in Yii PHP Framework
In this article, we are going to discuss about how to remove the index.php from the URL (enable search engine friendly SEF URL) in YII php framework. We can get the SEF url by removing the index.php from the URL. If you are using YII framework you are noticed that by default index.php will be included with your URL. In this article I am going to explain about How to remove the index.php from the YII framework site URL.
By removing the index.php from the URL we can get the site URL like below
http://domain.com/about
To acheive this, follow the below steps.
.htaccess
Please add the following lines in '.htaccess' file inside the 'web' directory of YII 2.0 application.
RewriteEngine on
# If a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Otherwise forward it to index.php
RewriteRule . index.php
Configuration of Web.php File
By default 'config/web.php' file does not have a option 'urlManager'. If we want to enable a pretty url, We have to add and configure the 'urlManager' in 'web.php' file.
To remove the 'index.php' from url, we have to the 'showScriptName' value as false.
To remove the 'r' route variable from url, set the 'enablePrettyUrl' value as true.
.................
'urlManager' => [
'class' => 'yii\web\UrlManager',
// Disable index.php
'showScriptName' => false,
// Disable r= routes
'enablePrettyUrl' => true,
'rules' => array(
),
],
.................
By removing the index.php from the URL we can get the site URL like below
http://domain.com/about
To acheive this, follow the below steps.
.htaccess
Please add the following lines in '.htaccess' file inside the 'web' directory of YII 2.0 application.
RewriteEngine on
# If a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Otherwise forward it to index.php
RewriteRule . index.php
Configuration of Web.php File
By default 'config/web.php' file does not have a option 'urlManager'. If we want to enable a pretty url, We have to add and configure the 'urlManager' in 'web.php' file.
To remove the 'index.php' from url, we have to the 'showScriptName' value as false.
To remove the 'r' route variable from url, set the 'enablePrettyUrl' value as true.
.................
'urlManager' => [
'class' => 'yii\web\UrlManager',
// Disable index.php
'showScriptName' => false,
// Disable r= routes
'enablePrettyUrl' => true,
'rules' => array(
),
],
.................
PHP CMS Frameworks
March 04, 2015
Read more →
YII
Create custom component in Yii PHP Framework
In this article, we are going to discuss about How to create custom component in YII PHP framework. Yii framework having default application components and it is giving different type of services. For example 'urlManager' component, 'db' component etc. Every application component has an uniqueID and will call through expression format. We can create Application components like global or local variables.
Syntax And Core Components
Application compoent syntax
Yii::$app->componentID
sample Core Application Components
Yii::$app->db
Yii::$app->cache
Yii::$app->request
Yii::$app->session
Yii::$app->mailer
etc
Create Your Own Component In Yii
Create a folder named "components" in the project root directory. Now create one class 'MessageComponent' with extends class 'Component' inside the components folder. Using this component, we will display message.
Please see the below code to create a custom component class.
<?php
namespace app\components;
use yii\base\Component;
class MessageComponent extends Component{
public $content;
public function init(){
parent::init();
$this->content= 'Hello Yii 2.0';
}
public function display($content=null){
if($content!=null){
$this->content= $content;
}
echo Html::encode($this->content);
}
}
?>
Config Component In Yii
We have to register 'MessageComponent' by configuring the yii\base\Application::$components property inside the config/web.php file (application configurations).
'components' => [
'message' => [
'class' => 'app\components\MessageComponent',
],
],
Now we can access this component using 'Yii::$app()->message' expression
Call Yii Custom Component Function
Using configured 'message' component, we can call the method inside the 'MessageComponent'.
<?php
Yii::$app->message->display('I am Yii2.0 Programmer');
?>
Syntax And Core Components
Application compoent syntax
Yii::$app->componentID
sample Core Application Components
Yii::$app->db
Yii::$app->cache
Yii::$app->request
Yii::$app->session
Yii::$app->mailer
etc
Create Your Own Component In Yii
Create a folder named "components" in the project root directory. Now create one class 'MessageComponent' with extends class 'Component' inside the components folder. Using this component, we will display message.
Please see the below code to create a custom component class.
<?php
namespace app\components;
use yii\base\Component;
class MessageComponent extends Component{
public $content;
public function init(){
parent::init();
$this->content= 'Hello Yii 2.0';
}
public function display($content=null){
if($content!=null){
$this->content= $content;
}
echo Html::encode($this->content);
}
}
?>
Config Component In Yii
We have to register 'MessageComponent' by configuring the yii\base\Application::$components property inside the config/web.php file (application configurations).
'components' => [
'message' => [
'class' => 'app\components\MessageComponent',
],
],
Now we can access this component using 'Yii::$app()->message' expression
Call Yii Custom Component Function
Using configured 'message' component, we can call the method inside the 'MessageComponent'.
<?php
Yii::$app->message->display('I am Yii2.0 Programmer');
?>
PHP CMS Frameworks
January 07, 2015
Read more →
YII
YII Controller methods - render and renderPartial
In this article, we are going to discuss about the two controller methods in YII, render and renderPartial. Both the render and renderPartial methods are used to creating the controller's view content. Simply put this is the information the view will receive from the controller.
The difference between render and renderPartial is that the latter will not load the layout. This is useful in case you'd like to have a popup window or ajax functionality which shows short information.
Here is an example with a whole method:
public function actionView($slug) {
$model = $this->loadSlug($slug);
$category = $this->loadCategory($model->category);
$this->render('view', array( 'model' => $model, 'category' => $category->category ));
}
The first argument for render is view. This is the view file to which will be added .php. This should be the file protected/views/view_name/view.php.
The next interesting thing is the array which comes as second argument. This is how you set the properties or variables that will be sent to the view and will be available there. In our case we will have $model (array) and $category at our disposal in the view file.
Eventually you could create variables in the view and you don't have to necessarily pass them from the controller. However, this will not be in the spirit of MVC.
The difference between render and renderPartial is that the latter will not load the layout. This is useful in case you'd like to have a popup window or ajax functionality which shows short information.
Here is an example with a whole method:
public function actionView($slug) {
$model = $this->loadSlug($slug);
$category = $this->loadCategory($model->category);
$this->render('view', array( 'model' => $model, 'category' => $category->category ));
}
The first argument for render is view. This is the view file to which will be added .php. This should be the file protected/views/view_name/view.php.
The next interesting thing is the array which comes as second argument. This is how you set the properties or variables that will be sent to the view and will be available there. In our case we will have $model (array) and $category at our disposal in the view file.
Eventually you could create variables in the view and you don't have to necessarily pass them from the controller. However, this will not be in the spirit of MVC.
PHP CMS Frameworks
December 07, 2014
Read more →
YII
Access Rules and Access Control in YII
In this article, we are going to discuss about How use Access Rules and Access Control in YII framework. Yii gives powerful options for limiting access per controller methods / actions. Imagine that in an example controller we have actions index, view, create, update, delete (typical CRUD).
Here is how our access rules should look provided our remote IP is 4.2.2.2 and we want only authorized user 'admin' to access the administrative actions:
public function accessRules() {
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions' => array('index', 'view'),
'users' => array('*'),
),
array('allow', // allow admin users the admin actions
'actions' => array('create', 'update', 'delete'),
'users' => array('admin'),
'ips'=>array('127.0.1.1','4.2.2.2'),
),
array('deny', // deny all users
'users' => array('*'),
),
);
}
The above shows a good practice to limit the access by IP and not only to rely on authorization. This is very important for your website security.
Here is how our access rules should look provided our remote IP is 4.2.2.2 and we want only authorized user 'admin' to access the administrative actions:
public function accessRules() {
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions' => array('index', 'view'),
'users' => array('*'),
),
array('allow', // allow admin users the admin actions
'actions' => array('create', 'update', 'delete'),
'users' => array('admin'),
'ips'=>array('127.0.1.1','4.2.2.2'),
),
array('deny', // deny all users
'users' => array('*'),
),
);
}
The above shows a good practice to limit the access by IP and not only to rely on authorization. This is very important for your website security.
PHP CMS Frameworks
November 13, 2014
Read more →
YII
SEO and Clean URLs in YII Framework
In this article, we are going to discuss about How to create a SEO and Clean URLs in Yii PHP Framework. Yii is a modern and robust PHP framework aimed to secure and scalable programming. It is not hardern or more complex compared to the popular PHP frameworks such as CakePHP. It supports all major databases from MySQL to Sqlite. The best is that it is much faster and scalable compared to other frameworks. The latter is what made me reconsider using it over CakePHP.
By default Yii routes all URL requests transparently through the main index.php file and your URLs look like this:
http://example.org/?r=site/page&view=about
Our aim is to make it look:
http://example.org/site/page/view/about
For this purpose follow these steps:
Open your site root protected/config/main.php and uncomment the part about the urlManager so that it looks like this:
'urlManager'=>array(
'urlFormat'=>'path',
'showScriptName'=> false,
'rules'=>array(
'/'=>'/view',
),
),
Add the following lines to your .htaccess (provided you are using Apache or compatible web server):
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php
Last you may wish to drop controller / action from the URL. This can be also done by a custom rule in the urlManager array in protected/config/main.php:
'about'=>'site/page/view/about',
This will ensure that by just going to http://example.org/about you will be routed to http://example.org/site/page/view/about.
By default Yii routes all URL requests transparently through the main index.php file and your URLs look like this:
http://example.org/?r=site/page&view=about
Our aim is to make it look:
http://example.org/site/page/view/about
For this purpose follow these steps:
Open your site root protected/config/main.php and uncomment the part about the urlManager so that it looks like this:
'urlManager'=>array(
'urlFormat'=>'path',
'showScriptName'=> false,
'rules'=>array(
'/'=>'/view',
),
),
Add the following lines to your .htaccess (provided you are using Apache or compatible web server):
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php
Last you may wish to drop controller / action from the URL. This can be also done by a custom rule in the urlManager array in protected/config/main.php:
'about'=>'site/page/view/about',
This will ensure that by just going to http://example.org/about you will be routed to http://example.org/site/page/view/about.
PHP CMS Frameworks
October 15, 2014
Read more →
YII
Steps to install new theme in YII PHP Framework
In this article, we are going to discuss about the step by step procedure to install the new theme in YII PHP Framework. In web application, designing also has same importance as development because user interface matters. If UI is not user friendly then ultimately application won't be useful. Here i'll show you brand new theme installation on yii php framework.
First we need some template compatible with yii framework. I found two template link which is free Theme1 Theme2 download both templates from given links. After downloading complete follow the steps.
Step 1:
Open your YII app folder where you've installed yii framework app.
Step 2:
Copy the template folder and paste it into the theme directory which exist in your app folder (/yiiapp/themes/)
Step 3:
Open the protected folder and find config directory and open it, in config directory there is one main.php file open it in any text editor.(/yiiapp/protected/config/main.php)
Step 4:
Make the following changes in the main.php ('theme'=>'themename',) here is the screen shoot of main.php file
Step 5:
It simply route your theme folder and find cleangrad if found load it
Step 6:
Check theme has been installed successfully. (http://localhost/yiiapp/)
First we need some template compatible with yii framework. I found two template link which is free Theme1 Theme2 download both templates from given links. After downloading complete follow the steps.
Step 1:
Open your YII app folder where you've installed yii framework app.
Step 2:
Copy the template folder and paste it into the theme directory which exist in your app folder (/yiiapp/themes/)
Step 3:
Open the protected folder and find config directory and open it, in config directory there is one main.php file open it in any text editor.(/yiiapp/protected/config/main.php)
Step 4:
Make the following changes in the main.php ('theme'=>'themename',) here is the screen shoot of main.php file
Step 5:
It simply route your theme folder and find cleangrad if found load it
Step 6:
Check theme has been installed successfully. (http://localhost/yiiapp/)
PHP CMS Frameworks
August 04, 2014
Read more →
YII
Steps to install YII php framework on ubuntu linux
In this article, we are going to discuss about How to install YII PHP Framework on Ubuntu Linux systems. YII is widely used best PHP Framework. Yii helps Web developers build complex applications. Yii is pronounced as Yee or [ji:], and is an acroynym for "Yes It Is!". Yii is a free, open-source Web application development framework written in PHP5 that promotes clean, DRY design and encourages rapid development. It works to streamline your application development and helps to ensure an extremely efficient, extensible, and maintainable end product.
Steps to install YII PHP framework on ubuntu linux
Step 1:
Download the latest version of YII framework from http://www.yiiframework.com
Step 2:
Extract downloaded YII framework tar.gz file in same directory
cd Downloads/
tar -zxvf yii-1.1.14.f0fee9.tar.gz
Step 3:
Rename extracted folder as yii
mv yii-1.1.14.f0fee9 yii
Step 4:
Move the extracted YII folder to root directory of your webserver (opt/lampp/htdocs/yii)
mv yii /opt/lampp/htdocs
Step 5:
Create a new folder as name appyii in root directory (appyii will contain yii framework files)
Step 6:
Apply YII framework to your appyii folder by yiic.php webapp file using php cli
mkdir appyii
php yii/framework/yiic.yiic.bat yiic.php
php yii/framework/yiic.php webapp /opt/lampp/htdocs/appyii/
Create a web application under '/opt/lampp/htdocs/appyii'? (yes|no) [no] :
Step 7:
Test that the installation has been done (http://localhost/appyii)
Note: if php command line interpreter not installed
PHP command line installation on Ubuntu Linux
The PHP command-line interpreter runs PHP scripts from the command line.
copy and paste the following command to your terminal
sudo apt-get install php5-cli
Steps to install YII PHP framework on ubuntu linux
Step 1:
Download the latest version of YII framework from http://www.yiiframework.com
Step 2:
Extract downloaded YII framework tar.gz file in same directory
cd Downloads/
tar -zxvf yii-1.1.14.f0fee9.tar.gz
Step 3:
Rename extracted folder as yii
mv yii-1.1.14.f0fee9 yii
Step 4:
Move the extracted YII folder to root directory of your webserver (opt/lampp/htdocs/yii)
mv yii /opt/lampp/htdocs
Step 5:
Create a new folder as name appyii in root directory (appyii will contain yii framework files)
Step 6:
Apply YII framework to your appyii folder by yiic.php webapp file using php cli
mkdir appyii
php yii/framework/yiic.yiic.bat yiic.php
php yii/framework/yiic.php webapp /opt/lampp/htdocs/appyii/
Create a web application under '/opt/lampp/htdocs/appyii'? (yes|no) [no] :
Step 7:
Test that the installation has been done (http://localhost/appyii)
Note: if php command line interpreter not installed
PHP command line installation on Ubuntu Linux
The PHP command-line interpreter runs PHP scripts from the command line.
copy and paste the following command to your terminal
sudo apt-get install php5-cli
PHP CMS Frameworks
July 31, 2014
Read more →
YII
Steps to use AJAX form validation in YII Framework
In this article, we are going to discuss about How to implement the Ajax form validation in YII PHP Framework. Yii supports AJAX form validation, which essentially posts the form values to the server, validates them, and sends back the validation errors, all without leaving the page. It does this every time you tab out of a (changed) field.
Here's how Yii's AJAX validation works:
Step 1 :
Add the below code in your yii form declaration
<php $form = $this->beginWidget('CActiveForm', array(
'id'=>'lowercasemodelname-form', //not technically required but works w gii generated controllers
'enableAjaxValidation'=>true //turn on ajax validation on the client side
));
And have at least one form element with a matching error function:
<?php echo $form->textField($model, 'my_attribute'); ?>
<?php echo $form->error($model, 'my_attribute'); ?>
This makes Yii include the JQuery javascript library, as well as a Yii javascript file called jquery.yiiactiveform.js
Step 2:
In your controller file, in create or update, after you load the model, but before you load it from POST, call this
if(Yii::app()->getRequest()->getIsAjaxRequest()) {
echo CActiveForm::validate( array( $model));
Yii::app()->end();
}
Which is sligtly different than how Gii generates it, but no big diff. CActiveForm::validate() can take an array of models, which is not clear the way Gii does it.
Step 3:
Make sure that your model has at least one validation rule for the insert or update scenario. After you tab out of a changed field, Yii sends a standard AJAX POST to the server, and gets back a JSON response like this:
{"Field_id":["Validation error a"],"Another_field_id":["Validation error B"]}
which yii then plugs into the error field below your field.
Step 4:
When you use the $form->error() function, Yii adds a hidden div after your form element:
<div id="Model_attributename_em_" class="errorMessage" style="display:none"></div>
If that field has a validation error, then Yii sets the display to block, writes the validation error message to its innerHtml, and then you see the error. If it later validates, yii hides it again.
Step 5:
Yii will also add class names to the parent container of the field that it's validating. In most cases, this is a <div class="row">. When a form field is valid, it adds "success" class to the div - which makes it green. When it's invalid, it adds "error" class, which makes it red. It also quickly adds a "validating" class, which does nothing, but you can supply it yourself and change the look of a field while it's validating.
Here's how Yii's AJAX validation works:
Step 1 :
Add the below code in your yii form declaration
<php $form = $this->beginWidget('CActiveForm', array(
'id'=>'lowercasemodelname-form', //not technically required but works w gii generated controllers
'enableAjaxValidation'=>true //turn on ajax validation on the client side
));
And have at least one form element with a matching error function:
<?php echo $form->textField($model, 'my_attribute'); ?>
<?php echo $form->error($model, 'my_attribute'); ?>
This makes Yii include the JQuery javascript library, as well as a Yii javascript file called jquery.yiiactiveform.js
Step 2:
In your controller file, in create or update, after you load the model, but before you load it from POST, call this
if(Yii::app()->getRequest()->getIsAjaxRequest()) {
echo CActiveForm::validate( array( $model));
Yii::app()->end();
}
Which is sligtly different than how Gii generates it, but no big diff. CActiveForm::validate() can take an array of models, which is not clear the way Gii does it.
Step 3:
Make sure that your model has at least one validation rule for the insert or update scenario. After you tab out of a changed field, Yii sends a standard AJAX POST to the server, and gets back a JSON response like this:
{"Field_id":["Validation error a"],"Another_field_id":["Validation error B"]}
which yii then plugs into the error field below your field.
Step 4:
When you use the $form->error() function, Yii adds a hidden div after your form element:
<div id="Model_attributename_em_" class="errorMessage" style="display:none"></div>
If that field has a validation error, then Yii sets the display to block, writes the validation error message to its innerHtml, and then you see the error. If it later validates, yii hides it again.
Step 5:
Yii will also add class names to the parent container of the field that it's validating. In most cases, this is a <div class="row">. When a form field is valid, it adds "success" class to the div - which makes it green. When it's invalid, it adds "error" class, which makes it red. It also quickly adds a "validating" class, which does nothing, but you can supply it yourself and change the look of a field while it's validating.
PHP CMS Frameworks
July 23, 2014
Read more →
YII
Implement Autocomplete in YII PHP Framework
In this article, we are going to discuss about How to implement Ajax autocomplete in YII PHP Framework. YII is one of the most popular PHP Framework. Autocomplete, or word completion, is a feature provided by many web browsers, e-mail programs, search engine interfaces, source code editors, database query tools, word processors, and command line interpreters. Here is the tutorial to implement the Autocomplete in YII framework.
We are going to implement the Autocomplete in YII using Tokeninput jQuery plugin. Tokeninput is a jQuery plugin which allows your users to select multiple items from a predefined list, using autocompletion as they type to find each item. You may have seen a similar type of text entry when filling in the recipients field sending messages on facebook.
To get started, we'll create a table city that will accept connections, then send back messages, json_encode result.
To show how simple it is, let's do it in site/index!
index.php:
$array[] = array('id' => 1, 'name' => 'Bali');
$array[] = array('id' => 2, 'name' => 'Singapore');
$this->widget('application.extensions.autocomplete.AutoComplete', array(
'theme' => 'facebook',
'name' => 'searchCity',
//'prePopulate' => CJavaScript::encode($array),
'sourceUrl' => Yii::app()->createUrl('ajax/city'),
'hintText' => 'Try Typing places',
//'htmlOptions' => array('class' => 'form-control', 'placeholder' => 'Try Typing Places'),
//'widthInput' => '50px',
//'widthToken' => '250px',
));
AjaxController:
public function actionCity()
{
// search keyword from ajax
$q = $_GET['q'];
$rows = array();
$sql = 'SELECT id, `name` FROM city WHERE `name` LIKE "%' . $q . '%"';
$rows = Yii::app()->db->createCommand($sql)->queryAll();
if ($rows)
echo CJSON::encode($rows);
}
Finally, let's create a table city to test it.
DROP TABLE IF EXISTS `city`;
CREATE TABLE `city` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY (`id`),
UNIQUE KEY `idx_name_countryCode` (`name`),
KEY `idx_name` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=114 DEFAULT CHARSET=utf8;
/*Data for the table `city` */
insert into `city`(`id`,`name`) values (76,'Airport Soekarno Hatta');
insert into `city`(`id`,`name`) values (22,'Amed');
insert into `city`(`id`,`name`) values (77,'Ancol');
insert into `city`(`id`,`name`) values (75,'Badung');
insert into `city`(`id`,`name`) values (1,'Bali');
Open this page in your web-browser. It will even work if you open it directly from disk using a localhost/Yiifolder
Features
We are going to implement the Autocomplete in YII using Tokeninput jQuery plugin. Tokeninput is a jQuery plugin which allows your users to select multiple items from a predefined list, using autocompletion as they type to find each item. You may have seen a similar type of text entry when filling in the recipients field sending messages on facebook.
To get started, we'll create a table city that will accept connections, then send back messages, json_encode result.
To show how simple it is, let's do it in site/index!
index.php:
$array[] = array('id' => 1, 'name' => 'Bali');
$array[] = array('id' => 2, 'name' => 'Singapore');
$this->widget('application.extensions.autocomplete.AutoComplete', array(
'theme' => 'facebook',
'name' => 'searchCity',
//'prePopulate' => CJavaScript::encode($array),
'sourceUrl' => Yii::app()->createUrl('ajax/city'),
'hintText' => 'Try Typing places',
//'htmlOptions' => array('class' => 'form-control', 'placeholder' => 'Try Typing Places'),
//'widthInput' => '50px',
//'widthToken' => '250px',
));
AjaxController:
public function actionCity()
{
// search keyword from ajax
$q = $_GET['q'];
$rows = array();
$sql = 'SELECT id, `name` FROM city WHERE `name` LIKE "%' . $q . '%"';
$rows = Yii::app()->db->createCommand($sql)->queryAll();
if ($rows)
echo CJSON::encode($rows);
}
Finally, let's create a table city to test it.
DROP TABLE IF EXISTS `city`;
CREATE TABLE `city` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY (`id`),
UNIQUE KEY `idx_name_countryCode` (`name`),
KEY `idx_name` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=114 DEFAULT CHARSET=utf8;
/*Data for the table `city` */
insert into `city`(`id`,`name`) values (76,'Airport Soekarno Hatta');
insert into `city`(`id`,`name`) values (22,'Amed');
insert into `city`(`id`,`name`) values (77,'Ancol');
insert into `city`(`id`,`name`) values (75,'Badung');
insert into `city`(`id`,`name`) values (1,'Bali');
Open this page in your web-browser. It will even work if you open it directly from disk using a localhost/Yiifolder
Features
- Very simple install. Just download add your folder extensions.
- Intuitive UI for selecting multiple items from a large list
- Easy to skin/style purely in css, no images required
- Supports any backend which can generate JSON, including PHP, Rails, Django, ASP.net
- Smooth animations when results load
- Select, delete and navigate items using the mouse or keyboard
- Client-side result caching to reduce server load
- Crossdomain support via JSONP
- Callbacks when items are added or removed from the list
- Preprocess results from the server with the onResult callback
- Programatically add, remove, clear and get tokens
- Customize the output format of the results and tokens
PHP CMS Frameworks
July 20, 2014
Read more →
YII
YII PHP Framework - Introduction
The Yii PHP project started on January 1, 2008, in order to fix some drawbacks of the PRADO framework. For example, in its early versions PRADO was slow when handling complex pages, had a steep learning curve and many controls were difficult to customize, while Yii was much more efficient at that time. In October 2008, after ten months of private development, the first alpha version of Yii was released. On December 3, 2008, Yii 1.0 was formally released.
Features:
Features:
- Model-View-Controller (MVC) design pattern.
- Generation of complex WSDL service specifications and management of Web service request handling.
- Internationalization and localization (I18N and L10N). It supports message translation, date and time formatting, number formatting, and interface localization.
- Layered caching scheme. It supports data caching, page caching, fragment caching and dynamic content. The storage medium of caching can be changed.
- Error handling and logging. Errors are handled and presented more nicely, and log messages can be categorized, filtered and routed to different destinations.
- Security measures include cross-site scripting (XSS) prevention, cross-site request forgery (CSRF) prevention, cookie tampering prevention, etc.
- Unit and functionality testing based on PHPUnit and Selenium.
- Automatic code generation for the skeleton application, CRUD applications, etc.
- Code generated by Yii components and command line tools complies to the XHTML standard.
- Carefully designed to work well with third-party code. For example, it's possible to use code from PEAR or Zend Framework in a Yii application.
PHP CMS Frameworks
June 19, 2014
Read more →
No more posts to load.
About this blog
PHPCMSFramework.com
Tutorials for WordPress, Laravel, Drupal, Joomla, Symfony & more — including AI-powered PHP guides. Publishing since 2012.
Trending posts
- Steps to create a Contact Form in Symfony With SwiftMailer
- Building a RAG System in Laravel from Scratch
- Build a WhatsApp AI Assistant Using Laravel, Twilio and OpenAI
- Laravel and Prism PHP: The Modern Way to Work with AI Models
- CIBB - Basic Forum With Codeigniter and Twitter Bootstrap
- Drupal 7 - Create your custom Hello World module
- Build an AI Code Review Bot with Laravel — Real-World Use Case
- Create Front End Component in Joomla - Step by step procedure
- Symfony Framework - Introduction
- A step by step procedure to develop wordpress plugin
