You are on page 1of 62

[LEARN MORE IN

Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]

YII2
TROLLER

Object oriented programming and mother fucker

Public: bacpham.wordpress.com
Year: 2015
Author : Longt8x
Support Skype: bacpd89
Email: bacphamvn@gmail.com

Cun sch ny dnh cho ai ?

Cm tit thanh nin cha 18 tui


c rnh rp vo cc trang action ca
Nht v ch em ph n v l do trong bi hng dn c qu nhiu li tc tu v by b
v th nn khng khuyn khch ch em ph n vo xem.

Ch em no vo xem th c hnh vi ng x c vn ha

thng khn nn, d xm


1

cm lng m tc gi l

. cnh bo cn c tnh vo rng chu

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
X.1 Yu cu ti thiu:
hc c yii 2 bn cn phi c kin thc vng v lp trnh hng i tng (OOP)
v ng thi phi hc thm yii1, bootstrap ti getbootstrap.com hoc g google,ng
thi th sn trong mnh dng mu d

Bn c th hc Yii u:
C rt nhiu ni bn c th hc yii trc tuyn nh: tinhdonphuong.com, lauxanh.us,

coithienthai.net t m nhm
yiiframework.com, w3 schools v c
bit.Google. V c bit hoan nghnh bn gh thm trang web ca ti

bacpham.wordpress.com mc d ch my khi ti online

X.2 Cc cng c cn thit


c th lp trnh c yii2 bn cn nhng cng c sau: sextoy, s em rau, s nh

ngh, ln

SERVER : XAMPP,WAMP,APPSERV (Ch PHP t nht phin bn 5.4+ tr ln )


Tool mysql: Mysql workbench

IDE: PHP Storm, netbean, phpED v thnh Notepad


Tm dng t c t tin tc trong ngy: Bo cng an nhn dn, bo an ninh th , bo
th thao, bo php lut v i sng lin tc ng ti cc v git v hip gh rn, ca s
ang gi la phc mc o thot y ma ct trn sn khu - ch em ph n thi nhau hc
theo mt ra ng khng mc g

, ngy no cng hip v git chn ngt.

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]

I. HNG DN V CI T
A.1 Ci t ng dng
u tin bn ti xampp v (hoc phn mm khc k m bn
next next -> finish.

) sau ci t next

Gi s bn ang [E]:/xampp (nu ci mc nh th vo C:/program files file m tm


)
Bn vo trang ch yiiframework.com v ti bn yii 2 honh trng nht v
Gii nn yii file va ti v v i tn folder yii2 thnh yiitroller.. vo th mc :
[E]:/xampp/htdocs/ (i E thnh ng dn th mc ci xampp hoc server khc
(www).

Tip theo ta to virtual host:


Vo E://xampp/apache/conf/http.conf , m file ny bng notepad v nhn Ctrl + F
(Find) find 2 t : rewrite v vhost, nh find next cho ti khi khng th find thm,
B du # ng trc cc dng load v d:
#LoadModule rewrite_module modules/mod_rewrite.so (B #)
Vo [E]://xampp/apache/conf/extra tm httpd-vhosts.conf
Thm on sau vo cui file:
NameVirtualHost *
<VirtualHost yiitroller.com>
DocumentRoot "E:\xampp\htdocs\yiitroller\frontend\web"
ServerName yiitroller.com
ServerAlias www.yiitroller.com
</VirtualHost>
3

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
<VirtualHost yiitroller.com >
DocumentRoot "E:\xampp\htdocs\yiitroller\backend\web"
ServerName backend.yiitroller.com
ServerAlias www.yiitroller.com
</VirtualHost>

Tip theo m window trong C://Windows/System32/drivers/etc/hosts


V chn m bi administrator nu my bn bt phn quyn, thm dng sau vo cui
file:
127.0.0.1 yiitroller.com www.yiitroller.com
127.0.0.1 backend.yiitroller.com
Thc hin xong restart apache trong xampp

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]

Tip theo ta vo th mc E://xampp/htdocs/yiitroller/ to 2 th mc l : frontend v


backend, trong c 2 th mc to thm th mc web.

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]

Tip theo ta to file index.php trong frontend/web c ni dung sau:


<?php
echo '<h1>HELLO WORLD</h1>';
?>

Lu li v vo a ch yiitroller.com ta c kt qu sau

Tip theo to file index.php trong backend/web c ni dung sau:


<?php
Echo 'EM BI DIEN XIN DUNG CHEU EM';
?>
Vo backend.yiitroller.com

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]

Au zia tht khng th tin c

c th lm c nh vy

, chnh chng ti cng khng th tin c mnh

Ci t ng dng t command line path


Bn ti : https://getcomposer.org/Composer-Setup.exe sau setup, ti phn settingcheck tm file php.ext bn tr ti E:/xampp/php tm php.exe.

Cc bn g CMD t windows m ca s lnh command prompt g cc lnh sau :


E: (i ti th mc E)
E:/xampp/php
php -r "readfile('https://getcomposer.org/installer');" | php
Nu li c file th vo php.ini trong E://xampp/php/php.ini tm
php_openssl.dll b ; ng trc enable ssl https. Nu li na sp m server
downfile bn vui lng nm di ch in nc

Ch n download xong v ri g
echo @php "%~dp0composer.phar" %*>composer.bat

cd/ (tr v th mc gc)


E:
Cd xampp/htdocs/yiitroller
composer.install

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]

Ch n t sung sng , cn ta th i ht thuc i n hon thnh


Tip theo ta to project bng dng lnh sau :
composer create-project --prefer-dist yiisoft/yii2-app-advanced

V li nm chro nc
To mi yii2 trong E://xampp/htdocs/ .Copy ton b file trong yii2-app-advanced vo
E://xampp/htdocs/yii2
Quay li command line prompt:
Cd/
E:/xampp/htdocs/yii2/php init

N s yu cu bn chn 1 trong 2 bn l developer hoc production , nhn 0 chn


develop.

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
B. To Database
Sau khi hon thnh xong vic ly code t yii2 ta vo localhost/phpmyadmin v to
database ging nh sau:

Create xong l ok ta vo yii2/common/config/main-local.php


V thay i vng code li cho ging nh sau:
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=yiitroller',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
],
Chy Migration:
T command promt window:
E:
Cd xampp/htdocs/yii2
Composer install (Ti gi yiisoft)

Sau khi ti xong g : yii migrate ->yes, easy to make

Vo phpmyadmin ta s thy 2 bng mi c khi to :


9

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]

Cu hnh li virtual host cho ng dng mi:


E:\xampp\apache\conf/extra/ httpd-vhosts.conf v thm on di cng:
<VirtualHost yii2.local>
DocumentRoot "E:\xampp\htdocs\yii2\frontend\web"
ServerName yii2.local
ServerAlias www.yii2.local
</VirtualHost>

<VirtualHost yii2.local>
DocumentRoot "E:\xampp\htdocs\yii2\backend\web"
ServerName backend.yii2.local
ServerAlias www.yii2.local
</VirtualHost>
Cp nht assets plugin: G command prompt windows:
composer global require "fxp/composer-asset-plugin:1.0.0"

M Windows/system32/drivers/etc/hosts v thm vo dng sau :


127.0.0.1 yii2.local www.yii2.local
10

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
127.0.0.1 backend.yii2.local
Vo compose.json i dng bower-asset-library li thnh : "bower-assetlibrary": "vendor/bower" .

Vo trnh duyt lm pht honh trng no


yii2.local

Rc r qu ! T sng pht

:
B.1 Loi b kch bn index.php v route trong URL
Ti frondent/web v backend/web thm file .htaccess sau:
11

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)\?*$ index.php/$1 [L,QSA]
Bn c th ly file .htaccess t yii 1 sang.
Ti frontent/config/main-local.php v backend/config/main-local.php thm on sau vo
$config:
$config = [
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'LJZm25X7FFaQrNtz6ppVmlUau8W3nnlm',
],
// UrlManager
'urlManager' => [
'class' => 'yii\web\UrlManager',

// Disable index.php
'showScriptName' => false,

// Disable r= routes
'enablePrettyUrl' => true
],

// Caching
'cache' => [
'class' => 'yii\caching\FileCache'

12

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
],
],
];

Vo li Login trong yii2.local : yii2.local/site/login.

II. Lm vic vi User Model v phn quyn user


Trc tin chng ta s to migrate update_user_table bng vic m command prompt
(g CMD) :
13

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]

Nhn y thc hin lnh.


Nu khng g c yii migrate v bo li php.exe not recogniz.fuck fuck fuck th
vo yii2 folder/ yii.bat v thay i on if ging di y:

if "%PHP_COMMAND%" == "" set PHP_COMMAND=E:\xampp\php\php.exe


Xem chi tit hm migrate ti y : http://www.yiiframework.com/doc-2.0/yii-dbmigration.html
Bn vo yii2 folder/ console/migrations/ v chnh sa li file mi to
idx_update_userphp li nh sau:
public function up()
{
$this->addColumn('user', 'role_id', 'tinyint(4) NOT NULL
DEFAULT 0');
$this->addColumn('user', 'user_type_id', 'tinyint(4) NOT
NULL DEFAULT 0');
$this->addColumn('user', 'full_name', 'varchar(400)');
$this->addColumn('user', 'images', 'text');
$this->addColumn('user', 'gender', 'tinyint(4)');
$this->addColumn('user','phone_number','varchar(255)');
$this->alterColumn('user','created_at','datetime');
$this->alterColumn('user','updated_at','datetime');
}
Chu no khng to c migrate th vo phpmyadmin m thm ct ging nh trn

nh ko c t li tm lum li ku khc sai be bt


Vo li cmd g lnh : yii migrate
14

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]

Nhn y thc hin cu truy vn.

II.1 Chnh sa trong User Model


Khi chng ta thm mt lot cc option h tr cho vic ng k v phn quyn chng
ta cn nh ngha v khai bo rules cho chng trong model
Vo yii2/common/models/User.php
/**
* User model
*
* @property integer $id
* @property string $username
* @property string $password_hash
* @property string $password_reset_token
* @property string $email
* @property string $auth_key
* @property integer $status
* @property integer $created_at
* @property integer $updated_at
* @property string $password write-only password
* @property integer $role_id
* @property integer $user_type_id
* @property string $full_name
* @property string $images
* @property integer $gender
* @property string $phone_number
*/
Chnh sa behaviors t ng cp nht ngy gi hin ti khi to mi hoc update record
:
/**
* behaviors
*/

15

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
public function behaviors()
{
return [
'timestamp' => [
'class' => 'yii\behaviors\TimestampBehavior',
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => ['created_at',
'updated_at'],
ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
],
'value' => new Expression('NOW()'),
],
];
}

Chnh sa li Rules
/**
* validation rules
*/
public function rules()
{

return [
['status', 'default', 'value' => self::STATUS_ACTIVE],
['status', 'in', 'range' => [self::STATUS_ACTIVE,
self::STATUS_DELETED]],
['role_id','default','value'=>0],
['username','required'],
['username','unique'],
['username','string','min'=>5,'max'=>255],
['email','required'],
['email','email'],
];
}

Thm label cho atttributes


/* Your model attribute labels */
public function attributeLabels()
{
return [
'status'=>'Status',
'role_id'=>'Vai tr',
'username'=>'User',
'email'=>'Email',
16

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
'password_hash'=>'Mt khu',
'full_name'=>'H v tn',
'gender'=>'Gii tnh',
'phone_number'=>'S in thoi'
];
}
To hng s cho cc phn t role_id,gender:
const
const
const
const
const
const
const

STATUS_DELETED = 0;
STATUS_ACTIVE = 10;
ROLE_ADMIN =20;
ROLE_USER=10;
ROLE_MANAGE=30;
GENDER_MALE=1;
GENDER_FEMALE=0;

II.2 Chnh li form ng k user (SignUp).


Vo yii2/models/SignedUpForm.php v chnh sa :
t m nghe nhc quang l xon quy lun

ng2 ting mi dy, khm lng

https://www.youtube.com/watch?v=shSJbITuMHI
Thm on khai bo attribute :
public
public
public
public
public
public
public

17

$username;
$email;
$password;
$full_name;
$images;
$gender;
$phone_number;

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
Chnh li rules nh sau:
return [
['username', 'filter', 'filter' => 'trim'],
['username', 'required','message'=>'Vui lng nhp tn ng
nhp'],
['username', 'unique', 'targetClass' =>
'\common\models\User', 'message' => 'This username has already
been taken.'],
['username', 'string', 'min' => 2, 'max' => 255],
['email', 'filter', 'filter' => 'trim'],
['email', 'required','message'=>'Vui lng nhp a ch
email'],
['email', 'email'],
['email', 'unique', 'targetClass' => '\common\models\User',
'message' => 'This email address has already been taken.'],
['full_name','string'],
['full_name','required','message'=>'vui lng nhp h v
tn'],
['images','safe'],
['images', 'file', 'extensions' => 'jpg,jpeg, gif,
png,jpeg,bmp'],
['phone_number','required','message'=>'S in thoi khng
th rng'],
['phone_number','string','min'=>9,'tooShort'=>'S in thoi
khng th nh hn 9 s'],
['gender','integer'],
['password', 'required','message'=>'Vui lng nhp mt khu'],
['password', 'string', 'min' => 6],
];

Thm attributes label :


18

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
public function attributeLabels()
{
return [
'username'=>'Tn ng nhp',
'email'=>'Email',
'full_name'=>'H v tn',
'password'=>'Mt khu',
'images'=>'Images',
'gender'=>'Gii tnh',
'phone_number'=>'S in thoi'
];
}

Thm hm sau vo yii2/common/models/User.php


public static $list_gender=[
self::GENDER_FEMALE=>'N',
self::GENDER_MALE=>'Nam',
];

Sa li tn bng cho ng vi CSDL t phpmyadmin:


public static function tableName()
{
return 'user';
}

19

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
Chnh li view yii2/frontend/view/signup.php thay ton b trong th div vi class li nh

sau: ch cn quan tm mc nh n c g , ti v u moa chu


<div class="col-lg-5">
<?php $form = ActiveForm::begin(['id' => 'formsignup','options' => ['enctype'=>'multipart/form-data']]); ?>
<?= $form->field($model, 'username') ?>
<?= $form->field($model, 'password')->passwordInput() ?>
<?= $form->field($model, 'email') ?>
<?= $form->field($model, 'images')->fileInput() ?>
<?= $form->field($model, 'full_name') ?>
<?= $form->field($model, 'phone_number') ?>
<?= $form->field($model, 'gender')>dropDownList(\common\models\User::$list_gender) ?>
<div class="form-group">
<?= Html::submitButton('Signup', ['class' => 'btn
btn-primary', 'name' => 'signup-button']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
Quay li yii2/frontend/models/SignupForm.php v thm on khai bo sau s dng
uploadfile:
use
use
use
use

common\models\User;
yii\base\Model;
yii\web\UploadedFile;
Yii;

Chnh li ton b trong hm signup khi validate xong nh sau ti v u .moa chu

20

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
Trc khi chnh sa bn to thm th mc sau : yii2/frontend/web/upload/user lm ni
cha nh avatar ca user:

if ($this->validate()) {
$user = new User();
$user->username = $this->username;
$user->email = $this->email;
$user->setPassword($this->password);
$user->generateAuthKey();
$user->generatePasswordResetToken();
//add images
if(isset($_FILES['SignupForm'])){
$model=new SignupForm();
$files=UploadedFile::getInstance($model,'images');
if($files){
$images_data=$user>uploadSinglefile($model,'images','/upload/user/');
$user->images=$images_data;
}
}
$user->full_name=$this->full_name;
$user->phone_number=$this->phone_number;
$user->gender=$this->gender;
$user->role_id=10;
$user->created_at=date('Y-m-d H:i:s');
$user->updated_at=date('Y-m-d H:i:s');
$user->status=10;
$user->user_type_id=10;
if ($user->save()) {
return $user;
}
}

21

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
Thm 2 hm sau thc hin vic upload nh vi hm upload n v upload nhiu
nh ti yii2/common/models/User.php
Thm khai bo th vin s dng file input:
use
use
use
use
use
use
use

yii\base\Exception;
yii\base\NotSupportedException;
yii\behaviors\TimestampBehavior;
yii\db\ActiveRecord;
yii\db\Expression;
yii\web\IdentityInterface;
yii\web\UploadedFile;

Thm 2 hm upload multiple v upload single:


public function uploadSinglefile ($model,$attr,$path)
{
$pathitems=Yii::getAlias('@webroot');
$sfile=new UploadedFile();
if($file=UploadedFile::getInstances($model, $attr)){
$tmp_name=$file[0]->tempName;
$formatName=time().'.'.$file[0]->name;
$sfile->save($tmp_name,$pathitems.$path.$formatName);
$ffile=$formatName;
return ($ffile);
}
}
public function uploadMultifile ($model,$attr,$path)
{
$pathitems=Yii::getAlias('@webroot');
$sfile=new UploadedFile();
if($files=UploadedFile::getInstances($model, $attr)){
foreach ($files as $i=>$file){
$tmp_name=$file[$i]->tempName;
$formatName=time().'.'.$file[$i]->name;
$sfile->save($tmp_name,$pathitems.$path.$formatName);
$ffile[$i]=$formatName;
}
return ($ffile);
}
}
22

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]

Ta to params value s dng tr ti ng dn n th mc gc:


Vo yii2/common/config/params-local.php chnh sa li nh sau:
<?php
Yii::setAlias('@webroot',realpath(dirname(__FILE__).'/../../'));
return [
];
Tip theo vo yii2/vendor/yii2soft/yii2/web/UploadFile.php thm
hm sau cnh hm saveAs:
public function save($name,$file, $deleteTempFile = true)
{
if ($deleteTempFile) {
return move_uploaded_file($name,$file);
} elseif (is_uploaded_file($name,$file)) {
return copy($name,$file);
}
return false;
}
Nu bn khng mun vt vo core ca yii bn c th vt vo model
User v chnh tn hm thnh saveImage khi gi ra t signupForm
bn ch cn g:
$user->saveImage($name,$file,$path).
Gi vo http://yii2.local/site/signup s c hnh di y:

23

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]

Cc bn c to ba vi user km ln nh i, nh to thm c admin v email l


admin@gmail.com , manager, guest hc tip chng sau, k to phng m , ct

v qu nh c
,sau khi to xong vo phpmyadmin xem kt qu t bng user
nu bn lm vic chm ch khng quay tay ng gt th s thy hng lot user sau khi
to

V ng nhin l login vo thoi con m n mi


tuy nhin to phn
quyn th mi cc thnh hc phn tip theo vi Role Based Access Control (RBAC).

Khng tin h.s song.. th coi ! bee eeee

24

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]

II.3 Phn quyn truy cp vi RBAC


c bit ch vi cc thnh rng tt c cc hm v hng khai bo u page u cc
k quan trng v th nn chu no chnh mng thy n v ngha mt thi im
(Khai bo nhng cha dng) tin tay xa i th v cng chc mng
phn sau u lin quan ti phn trc.

v nhng

Trc tin chng ta khi to config kt ni vi RBAC qua database, ti


common/config/main-local.php bn thm on sau:
<?php
return [
'components' => [
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=yiitroller',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '@common/mail',
// send all mails to a file by default. You have to
set
// 'useFileTransport' to false and configure a
transport
// for the mailer to send real emails.
'useFileTransport' => true,
],
//Authentication RBAC
'authManager' => [
'class' => 'yii\rbac\DbManager',
'defaultRoles' => ['admin', 'user',
'guest','manager'],
],
25

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
],
];
Tip theo bn vo command prompt (CMD) window v g lnh sau khi to
database rbac:

Nhn y n t chy khi vo phpmyadmin bn s thy mt lot bng mi :

Tip theo ta to cc role phn quyn ban u bao gm cho admin, manager, user
Bn vo migrate v to mi :

Ta thm chnh sa ton b ni dung trong file mi ti console/migrations/


.create_role_user.php: (ch ly trong hm function up(); v khai bo use . )
<?php
use yii\db\Schema;
use yii\db\Migration;
use yii\rbac\DbManager;

26

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
class m150626_074852_create_role_user extends Migration
{
public function up()
{
$rbac = \Yii::$app->authManager;
$guest = $rbac->createRole('guest');
$guest->description = 'Khch vo website ';
$rbac->add($guest);
$user = $rbac->createRole('user');
$user->description = 'User c th ng nhp vo mt s
action ';
$rbac->add($user);
$manager = $rbac->createRole('manager');
$manager->description = 'Qun l ton b website';
$rbac->add($manager);
$admin = $rbac->createRole('admin');
$admin->description = 'Qun l ton b website';
$rbac->add($admin);
$rbac->addChild($manager,$admin);
$rbac->addChild($admin, $user);
$rbac->addChild($user, $guest);
$rbac->assign(
/*** ch user1 l tn ca 1 user bt k nu bn mun lm ht
nh moa ch cn vo trang ng k ri to tn ng nhp = user1
***/
$user, \common\models\User::findOne(['username' =>
'user1'])->id
);
$rbac->assign(
$manager, \common\models\User::findOne(['username' =>
'manager'])->id
);
$rbac->assign(
$admin, \common\models\User::findOne(['username' =>
'admin'])->id
);
}
public function down()
{
$manager = \Yii::$app->authManager;
$manager->removeAll();
}
27

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]

}
Bn update query bng cch g : yii migrate vo command promt v nhn y thi
hnh.
Sau khi thc hin xong bn s thy trong cc bng mi c d liu phn quyn

Ta to tip mt migrate na thc hnh to task/permission cho tng user:

Nhn y thc hin query v chnh li ging nh sau vo file mi to (ch ly trong
hm public function up(); )
<?php
use yii\db\Schema;
use yii\db\Migration;
use yii\rbac\DbManager;
class m150626_091559_create_role_view_about extends Migration
{
public function up()
{
$rbac = \Yii::$app->authManager;
//View About
$viewAbout = $rbac->createPermission('viewRequest');
$viewAbout->description = 'View request';
$rbac->add($viewAbout);
$admin=$rbac->getRole('admin');
$user=$rbac->getRole('user');
$manager=$rbac->getRole('manager');
$rbac->addChild($admin,$viewAbout); //Basic can view
own.
$rbac->addChild($user,$viewAbout); //When view all
fails, check for view own
$rbac->addChild($manager, $viewAbout);
28

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]

}
public function down()
{
echo "m150626_091559_create_role_view_about cannot be
reverted.\n";
return false;
}
}
Tip theo bn g yii migrate vo command prompt thc hin cu truy vn, nhn y
thc thi.
Tip theo ta to folder rbac c cha file AccessRule.php rng trong common folder:

Ti file mi AccessRule.php bn thm ton b dng di y :


<?php
namespace common\rbac;
use yii\rbac\Rule;
use Yii;
class AccessRule extends \yii\filters\AccessRule
{
protected function matchRole($user)
{
$permission='';
if (empty($this->roles)) {
return true;
}
29

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
foreach ($this->roles as $role) {
if (!$user->getIsGuest()) {
$auth = Yii::$app->authManager;
$permissions = $auth->getPermissionsByUser($user>id);
$permission = isset($permissions['viewRequest'])?
$permissions['viewRequest']->name:'';
}
if ($role === '?') {
if ($user->getIsGuest()) {
return true;
}
} elseif ($role === '@') {
if (!$user->getIsGuest()) {
return true;
}
// Check if the user is logged in, and the roles
match
} elseif (!$user->getIsGuest() && $role === $user>identity->role_id) {
return true;
} elseif(\Yii::$app->user->can($permission)) {
return true;
}
}
return false;
}
}
Vo frontend/controller/ SiteController.php v chnh li hm behaviors() ging di
y:
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout', 'signup','about',contact],
'ruleConfig' => [
'class' => 'common\rbac\AccessRule'
],
30

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
'rules' => [
[
'actions' => ['signup'],
'allow' => true,
'roles' => ['?'],
],
[
'actions' => ['about'],
'allow' => true,
'roles' =>
[User::ROLE_MANAGE,User::ROLE_ADMIN],
],
[
'actions' => ['contact'],
'allow' => true,
'matchCallback' => function() {
return \Yii::$app->user->identity->role_id
>= User::ROLE_ADMIN;
}
],
[
'actions' => ['logout'],
'allow' => true,
'roles' =>
['@',User::ROLE_ADMIN,User::ROLE_USER,User::ROLE_MANAGE],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}

By gi anh em bt u check hng

nhm vo Ph C trc.
31

, trc tin ti Trn Duy Hng trc, t m

, a ! sao mnh hay lc li th nh

, thi vo

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
route about trc chng ta ch cho php admin v manager vo n c, cn li chn ht

bt ng ngoi gm xng
. Lu rng hm checkAccess() ca Yii1 vn cn
nguyn tc dng Controller v th nu bn cm thy behaviors khng sch s ro
nc th c th quay li hm ph thng in nc y
Test vi Guest: http://yii2.local/site/about

Bn s phi tr v login nu mun vo trang ny.


Vi User:

Bn c th vo c vi user1 ny bi bn cho php n trong phn permission, nu

bn vo vi user khc th hu qu nh sau

32

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
Cn admin v manager vo c.
Vo http://yii2.local/site/contact th user s c kt qu sau:

V khon phn quyn nu bn thy cc role kiu int khng bo mt


bn c th
dng hm static v dng hm random(..,) random 2 ca n - admin v manager
trong 2 khong thn thnhm bo thng no mun hack role ch c khc tht

Trn y l ton b cch hng dn phn quyn cho cc bn, nu cc bn mun tm


hiu cn k hn t bn ngoi vo bn trong n tn bikini th mi bn vo a ch :
http://www.yiiframework.com/doc-2.0/guide-security-authorization.html xem cho
tng tn, bn thn mnh cng khng dm d lm nn ch mc ci cc cho cc bn

. Cn vic cc bn mun o su hn trong vng ny c l bn c th dng gi


extension ca my thng n khng ngi ri trn mng, cn mnh xin kiu v qu nhiu

vic, xy nt cho cc bn chc mnh ra ng gia nhp ci bang qu

III. To Models vi Gii


Vng,
, hm nay
, ti y
chng ta s chng kin mt xu hng mi
ca th gii cng ngh trn ton cu (mc d hng ca mnh i sau thi i) , tht
33

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]

khng th tin ni

. Chnh chng ti cng khng th tin ni ti sao mnh c th b

r c nh vy

Trc tin c th lm vic to model ta vo trnh duyt gii:


http://www.yii2.local/gii , ai ko vo c th chc mng

vic hc yii 2 ca bn

kt thc mt cch d dng, gi l lc bn nn i ng

t m ang nh ging tip th nhn 2 em tip vin qun caf ngon qu, ngm i 2 em

n t

, cc bc thng cm, em c thy gi l n ro rc ht mt s c quan

on th
34

, bit miu t th no nh, mt xinh da trng, nc bt ngt hay k th

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]

em cha c kh nng th
, c ci nhn 2 tri bi trng mut c ong a
cng thy vui mttt m ht c cm xc lp trnhnh xng vo xin s tht nhin
em thy m b sng
v mt khun mc cc k honh trng
, ang ng
ngc khng hiu chuyn g th mt ging gay ct ln : Hng ny l hng ca b, x xn
l cht vi b con

, ha rach qun =)))))))).

Quay li cng vic thoai, by gi chng ta xng vo hip dmt m nhm


to migrate cho mt bng roles mi gm id,role_name (tn role ), role_value (s) v
tham chiu vi bng user so snh gi tr.
i vi vic thc thi phn quyn ngoi user chng ta khng c g phi bn ci trong
phn trctuy nhin trong phn ny chng ta s lm vic vi backend nhiu hn v
th chng ta .lm ch g th lm ta thch th y
Do mnh lp trnh thay i nn hin gi hin ti s dng l D, nu bn ang xi
E th vui lng chn li ng ng dn ti folder yii2, ng bt chic moa
To mi migrate : yii migrate/create create_table_roles , xong xui nhn y ri vo
console/migrations/.create_table_roles.php
Vo phpmyadmin click vo database yiitroller, click vo bng user -> export bng user
v sa li file sql = notepad.
Chnh li hm function up() li nh sau:
public function up()
{
$this->createTable('roles',array(
'role_value'=>'int(11) not null default 0 primary key'
'role_name'=>'varchar(45)',
),"ENGINE=MYISAM DEFAULT CHARSET=utf8");
//Chng ta insert 4 roles:
$this->insert('roles',array(
'role_name'=>'Guest Access',
'role_value'=>0
));
$this->insert('roles',array(
35

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
'role_name'=>'User Access',
'role_value'=>10
));
$this->insert('roles',array(
'role_name'=>'Admin Access',
'role_value'=>20
));
$this->insert('roles',array(
'role_name'=>'Manager Access',
'role_value'=>30
));
$this>addForeignKey('fk_user_roles','roles','role_value','user','role_
id','cascade','cascade');
}

Nhn yii migrate execute


Vo phpmyadmin xem li bng roles:

36

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]

III.2 To Roles Model


By ch l ht rili mt in, m ci l cave n nhy
http://www.yii2.local/gii vo gii v click vo Model generator.
Thm vo setting ging hnh dib o v nguy him th Namespace mc nh
nh, t na li nhn n mi sng

37

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]

Vi setting th ny l chng ta to model trong admin v nhn generate l xongcuc


i xung dc khng phanh.
Gi chng ta s vo yii2/backend/models/Roles.php

Thm Relations vo Roles


Thm models User bng vic s dng model User, vit di namespace.
use common\models\User;

Thm hm getUsers() di hm attributesLabel()


public function getUsers()
{
return $this->hasMany(User::className(), ['role_id' =>
'role_value']);
}
38

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]

Vi vic return nh trn chng ta s dng truy vn lc ra user vi role_id= vi


role_value trong quan h kha ngoi. Cn nh rng mt Roles (admin,user, manager)
c th c nhiu ngi dng cng c phn mt vai tr nh vy nn ta s dng hm
hasMany().
Update user Models theo roles
By gi chng ta vo common\models\User.php v thm on sau di namespace:
use backend\models\Roles;
use yii\helpers\ArrayHelper;

Thm hm getRole() nh sau di hm rules():


public function getRole()
{
return $this->hasOne(Roles::className(), ['role_value' => 'role_id']);
}

public function getRoleName()


{
return $this->role ? $this->role->role_name : '0';
}

public static function getRoleList()


{
$droptions = Roles::find()->asArray()->all();
return Arrayhelper::map($droptions, 'role_value',
'role_name');
}
m trng thanh gi mt, ngi trn tng thng mt vi kc, tm hn bay bng nng
nng khng kho ln c xung th l
ba c no, tht g dnh ngp mm.
39

ht i thng b . Ch li mi h hng c

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
TEST RELATIONS
By gi vo backend.yii2.local, vui lng ng nhp bng manager. Thm on sau vo
backend/controllers/SiteController.php
public function actionIndex()
{
$user=User::findOne(array('id'=>Yii::$app->user->id));
$root=new User();
print_r($user->getRoleName());die;
return $this->render('index');
}

Vy l t model User, ta c th d dng truy nhp c Roles thng qua relations v


ngc li ta cng c th ly thng tin ca user t model ca Roles. Test xong phn ny
bn xa ton b phn mu trong action index n hot ng bnh thng.
Bi tp cho bn l phn quyn backend cho h thng backend ca bn.(c li
phn RBAC ti hng dn trong frontend).

III.3 Helpers
cho code gn v sng sa ti cng sa chng ta nn t tt c nhng hm n vo
mt class Helpers va gip chng ta thun li trong vic bo tr chnh sa v d dng
tm kim thay v chng ta lm vic nhiu trong Models tng table.
Chnh v th ti quyt nh i cua gi nhm to class Helper vi tn : DataHelpers
Ti common/models/ ta to class mi DataHelpers.php
<?php
namespace common\models;
class DataHelpers{
40

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
/***
* return role_name
* @param mixed $role_name;
*/
public static function getRoleValue($role_name){
$connection=\Yii::$app->db;
$sql="Select `role_value` FROM `roles` WHERE
role_name=:role_name";
$command=$connection->createCommand($sql);
$command->bindValue(":role_name",$role_name);
$result=$command->queryOne();
if(!empty($result)){
return $result['role_value'];
}else{
return $result;
}
}
}
s dng Helpers ta c th khai bo bt k u k c view bng vic s dng :
use common\models\DataHelpers;
Ta vo frontend/controllers/SiteController.php thm use bn trn di namespace v
thm on sau vo actionIndex:
public function actionIndex()
{
var_dump(DataHelpers::getRoleValue('Admin Access'));die;
return $this->render('index');
}
Khi m trnh duyt: http://yii2.local/

Vi nhng hm n hoc nhng hm truy vn c ti s dng nhiu ln chng ta


cng nn t vo Helper , d gi d dngm phong cch ca dn Xy Dngkhoa

41

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]

ng gch sn xut em b

. Cc bn hy sng to ht mc c tn vinh ging

sn phm ny

III.4 Lm vic vi User trong Backend


Phi cng nhn vi ci thi tit 39 ci t HN th bn thn ti khng giu ni s
sung sng tt khi khng cn gii php no khc l chui vo qun caf trnh
nng v nhn tin ngm gi

, mc d ti y ch c ca ngon vt l g

th

mi khn nn,
my em tip vin i qua c mi em ngon th n theo b
b cuc chilu vi su
By gi chng ta s lm vic vi CRUD, nu bn s dng yii 1 th s chng cn xa
l vi cng c ny, v th nn ti s ch hng dn ngn gn.
u tin chng ta vo gii: http://backend.yii2.local/gii v nhn vo create CRUD
42

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
in thng s ging di y v nhn preview-> generate
Bn vo backend\models to thm 1 th mc rng tn : search

To thm CRUD vi roles:

43

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]

Phn Widget Used in Index Page ca c 2 bn chn ListView thay v Gridview.


To xong vo check hng

44

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
V chng ta thy 2 cc shit rt to.
Chnh sa layout main.php trong backend/views/layout/main.php
+) Thm use common\models\DataHelpers; vo list use
if (!Yii::$app->user->isGuest && Yii::$app->user->identity>role_id >= $is_admin) {
$menuItems[] = ['label' => 'Users', 'url' => ['user/index']];
$menuItems[] = ['label' => 'Roles', 'url' =>
['/roles/index']];
}
+) Thm hm sau vo common/models/DataHelpers:
public static function getRoleManagement(){
$role_admin='Admin Access';$role_manager='Manage Access';
$connection=\Yii::$app->db;
$sql="Select `role_value` FROM `roles` WHERE
role_name=:role_admin or role_name=:role_manage";
$command=$connection->createCommand($sql);
$command->bindValue(":role_admin",$role_admin);
$command->bindValue(":role_manage",$role_manager);
$result=$command->queryOne();
if(!empty($result)){
return $result['role_value'];
}else{
return $result;
}
}
+) Thm on sau vo trong hm php sau tag <div class="wrap">
$is_admin=DataHelpers::checkManagerRole();
Sau khi hon thnh ng nhp admin bn s thy menu bar thay i nh sau:

Ch l do khng hiu sao h thng b vi kc redirect 1 ng ra 1 no nn bn


phi vo backend/web/backend/views/ li 2 folder user v roles mi to v vt quay
li backend/views/ th mi chy c view nu khng l n bo li k tm thy view ri
li cht nhc.

45

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
Hon thnh xong bn c th xem kt qu;

V models ca roles chng ta vn ly models user nn vic hin th trn roles c th


khng khc so vi user, tuy nhin v vic ny y l cng vic ti giao cho cc bn v
nh lm phn quyn h thng trong backend admin, by gi mnh ln ri ch c phi
tr con u m bt moa phi bt tay ch vic

=))))))))))))))))))))

III.5 Chnh sa CRUD User trong backend.


46

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
Trc tin chng ta vo http://backend.yii2.local/user/index c mt cm gic nga mt
nh v nhng field ta cn th k c. Ta chnh sa li ging di y:
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
'username',
//'auth_key',
//'password_hash',
//'password_reset_token',
'full_name',
// 'updated_at',
// 'role_id',
// 'user_type_id',
[
'attribute'=>'images',
'contentOptions' =>[],
'content'=>function($data){
if($data->images){
$urls=(String)Yii::getAlias('@front').'/upload/user/'.$data>images;
return Html::img($urls,
['alt'=>'yii','title'=>'images','width'=>'90','style'=>'maxwidth:100px;']);
}
else return;
}
],
'email:email',
[
'attribute'=>'gender',
'contentOptions' =>[],
'content'=>function($data){
if($data->gender==1) {return
\common\models\User::$list_gender[1];}
if($data->gender==0) {return
\common\models\User::$list_gender[0];}
}
],
47

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
'phone_number',
'created_at',
'status',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
Trong common/config/params-local.php chnh li nh sau:
<?php
Yii::setAlias('@webroot', realpath(dirname(__FILE__).'/../../'));
Yii::setAlias('@back','http://backend.yii2.local');
Yii::setAlias('@front','http://yii2.local');
return [
];
Vo trnh duyt g : http://backend.yii2.local/user/index

+) Sa li views user:
48

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
Thay th li on hin th t widget Detailview li nh sau:
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'id',
'username',
'auth_key',
'password_hash',
'password_reset_token',
'email:email',
['attribute'=>'status','value'=>\common\models\User::
$list_status[$model->status]],
'created_at',
'updated_at',
['attribute'=>'role_id','value'=>\common\models\User::
$list_role[$model->role_id]],
'user_type_id',
'full_name',
[
'attribute'=>'images',
'format'=>'raw',
'value'=>Html::img(Yii::getAlias('@front').'/upload/user/' .
$model->images,
['alt'=>'yii','title'=>'images','width'=>'90','style'=>'maxwidth:100px;'])
],
['attribute'=>'gender','value'=>\common\models\User::
$list_gender[$model->gender]],
'phone_number',
],
]) ?>

Thm 2 function sau vo common/models/User.php


Const ROLE_GUEST=0;
public static $list_status=[
0=>'Not Active',
49

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
1=>'Active'
];
public static $list_role=[
self::ROLE_GUEST=>GUEST,
self::ROLE_USER=>'User',
self::ROLE_ADMIN=>'Admin',
self::ROLE_MANAGE=>'Manager'
];
Vo trnh duyt g : http://backend.yii2.local/user/index click vo biu tng i mt
xem view:

By gi l phn cc k kh, rt kh v qu kh trong CRUD l delete


, vi hm
ny th chng ta ch cn test bt k bn ghi no ri nhn accept xa bn ghi , vy
l xong. Ci kh ca n l ch

nn cc bn t t thng thc .

Cn phn update th d b con m, tt nht bn t sng vui nh, xem li phn


register u ebook xem li cch cp nht v edit vi user v profile.
+) Chnh li update User
50

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
Vo backend/view/user/_form.php v chnh li ni dung trong th div li nh sau:
<div class="user-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'username')->textInput(['maxlength'
=> true]) ?>
<?= $form->field($model, 'email')->textInput(['maxlength' =>
true]) ?>
<?= $form->field($model, 'gender')>dropDownList(\common\models\User::$list_gender, []);?>
<?= $form->field($model, 'status')>dropDownList(\common\models\User::$list_status, []);?>
<?= $form->field($model, 'role_id')>dropDownList(\common\models\User::$list_role, []);?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' :
'Update', ['class' => $model->isNewRecord ? 'btn btn-success' :
'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>

Hon thnh ta vo http://backend.yii2.local/user/update?id=1 xem kt qu:

51

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]

+) User Search
C ch khng khc g yii1, nu bn yu yii2 ch cn quay li yii1 chng ti v cng cm
n nu bn b cng b vic tm sch ti vit

IV Layout , Themes, Render


52

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
IV.1 Tm hiu v Render
Khi chng ta render cc tham s hoc cc bin gi tr t controller sang view chng ta
thng c kiu truyn thng t trong Action bt k :
$this->render(index,[data=>$dataRender]);
Ngoi ra chng ta cng c th tham chiu trc tip thng qua gi tr nh danh hoc cc
directory path:
Yii::setAlias("@token", "some/filesystem/path/to/application");
Yii::$app->view->render("@token/subfolder/view");

C ch render view nh sau: <root_directory>/<views_directory>, khi chng ta nh ngha


index th mc nh hon ton c thit lp directory, v controller v thng ch gi tn
action, khi bn cn ly 1 view t mt folder khc , trong mt controller khc th ch cn ly
ng dn thc ti file view vi cc tham s c nh ngha.

Di y l bng render view theo quy tc :

2 ct trn ti gii thiu cho bn, cn 2 ct di bao gm // v / tng ng vi


vic bn tham chiu trc tip ti file view (ngoi module) v tham chiu ti view file
thng qua controller (trong modules).

IV.2 Custom Layout

53

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
V c ch layout gn nh khng thay i trong action, trong controller, trong view t Yii
1, vo backend/view/layout/main.php chnh sa li on sau trong class container :
<div class="container">
<?= Breadcrumbs::widget([
'links' => isset($this->params['breadcrumbs']) ?
$this->params['breadcrumbs'] : [],
]) ?>
<?php $this->beginContent('@app/views/layouts/base.php');
?>
<?= $content ?>
<?php $this->endContent(); ?>
</div>
Bn to mi base.php cnh layout main.php v thm ni dung nh sau:
<p class="alert-warning">I still loving you</p>
<?= $content ?>
Bn vo li admin s thy kt qu sau:

+) Custom format JSON AJAX


public function actionJson()
{
$models = ServiceRecord::find()->all();
$data = array_map(function ($model) {return $model>attributes;}, $models);
$response = Yii::$app->response;
$response->format = Response::FORMAT_JSON;
$response->data = $data;
return $response;
}

V mt s hm response x l AJAX khi render view


54

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]

+) Lm vic vi Assets
V mt cu trc khng c g khc so vi yii1
Yii:$app->assetManager->publish($path);
Yii::$app->view->assetManager->publish($path);
ng k CSS v JS :
Yii::$app->view->registerCss($css_path)
Yii::$app->view->registerJs($js_path)
Yii::$app->view->registerLinkTag($link_path)

+ Custom widget
55

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
Trong backend to components/TestWidget.php
<?php
namespace backend\components;
use yii\base\Widget;
use yii\helpers\Html;
class TestWidget extends Widget{
public $message;
public function init(){
parent::init();
if($this->message===null){
$this->message='Wellcome User';
}else{
$this->message='Wellcome '.$this->message;
}
}
public function run(){
return Html::encode($this->message);
}
}

Vo views/site/index.php
Thm use backend\components\TestWidget;
<?= TestWidget::widget(['message'=>' you go to cms ']); ?>
Vo trnh duyt xem kt qu:

+) To custom components
To TestComponent.php trong folder components
56

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
<?php
namespace backend\components;
use Yii;
use yii\base\Component;
use yii\base\InvalidConfigException;
class TestComponent extends Component
{
public function welcome()
{
return "Hello..Welcome to MyComponent";
}
}
Chnh li index trong SiteController
public function actionIndex()
{
$welcome='';
$welcome=Yii::$app->testcom->welcome();
return $this->render('index',['wellcome'=>$welcome]);
}
Thm <?php echo $wellcome;?><br/>
Vo views/index.php

+) To Modules
Chng ta vo http://backend.yii2.local/gii/module v in cc thng tin ging di y:

57

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]

Nhn preview/generate , tip theo vo backend config main-local.php thm dng sau:
'modules' => [
'test' => [
'class' => 'backend\modules\test',
],
],
Vo trnh duyt xem kt qu:
http://backend.yii2.local/test

Cng vic cn li nh thm models, crud trong modules ging ht nh yii1, khng bit
thi vui lng m li sch
58

, o m th thi

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
Cp nht tin tc: Ngy hm nay bo cng an nhn dn bo an ninh th , bo php
lut v i sng ng ti v git ngi gh rn 6 ngi tnh Bnh Phc, ch em vn
phng pht cung vi st th p trai .
, gi h ni cht m cht mt v st th
p trai , ghi nhn 2 n sinh m u vo chn bng t t nhng bt thnh, t m c
ngy zi n c t bn th nghe c cu rao bo phun m ht, ng lng
. M
ot t hi dn vit b vi nhn, yu k c th git c gia nh, ch em no xinh gi, nh
giu hc hi v ny nh, bo yu m o yu li l cng k n u
u ch xin t tit thi.

, n k i qu

+) Caching
V cn bn c ch cache khng thay i my so vi yii1, chng ta ch cn ci t
config.Cc API cache vn tng t :

Cc option:
\yii\caching\DbDependency: D liu cace ph thuc vo csdl

\yii\caching\ExpressionDependency: D liu cache ph thuc vo custom query


59

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
\yii\caching\FileDependency: D liu cache ph thuc vo ln modifier trong h
thng.
\yii\caching\TagDependency: Nhm cc i tng cache vo tag. ng dng c th
validate cached objects vi cng tag gi bi TagDependency::invalidate($
cache, $group) v tr v Cache component and tag c yu cu
\yii\caching\ChainedDependency: This is a special kind of dependency
that groups other dependencies together, allowing you to make complex
conditions to invalidate cached items. (Li o mun dch :v)
Cache component trong Yii 2 l mt class k tha t \yii\caching\Cache, v
framework cung cp 8 caching solutions:
\yii\caching\ApcCache: This uses the APC PHP extension (see http://
php.net/manual/book.apc.php).
\yii\caching\DbCache: S dng bng trong CSDL (Bn c th thit lp kt ni khc
trong config main application's).
\yii\caching\DummyCache:
\yii\caching\FileCache: Lu tr i tng trong file th mc .
\yii\caching\MemCache: S dng memcache
\yii\caching\WinCache: WinCache PHP extension (see
http://www.iis.net/expand/wincacheforphp ).
\yii\caching\XCache: This uses XCache (see http://xcache.lighttpd.net/).
\yii\caching\ZendDataCache: This uses the Zend Data Cache (see
http://www.zend.com/en/products/server/) PHP extension
Ngoi ra bn c th dng Redis or mongoDB nu cn thit:
$ php composer.phar require --prefer-dist yiisoft/yii2-redis "*"

Khai bo thm cache trong config: common/config/main-local.php:

60

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
'components' => [
'cache' => [
'class' => 'yii\redis\Cache',
'redis' => [
'hostname' => 'localhost',
'port' => 6379,
'database' => 0,
]
],
],
Hoc khai bo cache APC
[
components => [
// register "cache" component using a class name
cache => yii\caching\ApcCache,
// register "db" component using a configuration array
db => [
class => yii\db\Connection,
dsn => mysql:host=localhost;dbname=yiitroller,
username => root,
password => ,
],
]
Mem cache:
components => [
cache => [
class => yii\caching\MemCache,
servers => [
[
host => server1,
port => 11211,
weight => 100,
],
[
61

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
host => server2,
port => 11211,
weight => 50,
],
],
],
],
Ch l bn s dng cache no bn phi ci extension ca loi cache , kim tra
trong phpinfo() xem extensions cache.
S dng cache bi Query Caching
Query caching requires yii\db\Connection
$result = $db->cache(function ($db) {
return $db->createCommand(SELECT * FROM customer WHERE id=1)->queryOne();
});

Ngoi ra cn cch hay ho t thi tin s :


$customer = $db->createCommand(SELECT * FROM customer WHERE id=1)->cache(60)>queryOne();

V thi gian c hn nn vi framework yii2 mi ny mnh xin php c theo gi


dng cuc chi
bi hin ti mnh qu bn, tuy nhin nu bn hc yii1 ri th
khi sang yii2 mi gn nh k c s khc bit no c, mnh s vn ngh cc bn c
thm ebook: yii2-guide t nh sn xut tm hiu nhiu hn v cc API hoc ngay
trn trang ch yiiframework.com.
Vi nhng kin thc m mnh hng dn + hc thm yii2-guide th t bn thn cc
bn c th t pht trin c project ca bn thn bn.

Chc khe v thnh cng

62

|Longt8x-Yiivn.com Forum - Learn more in bacpham.wordpress.com

You might also like