Professional Documents
Culture Documents
YII2
TROLLER
Public: bacpham.wordpress.com
Year: 2015
Author : Longt8x
Support Skype: bacpd89
Email: bacphamvn@gmail.com
Ch em no vo xem th c hnh vi ng x c vn ha
cm lng m tc gi l
[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
ngh, ln
[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
[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>
[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
Lu li v vo a ch yiitroller.com ta c kt qu sau
[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
c th lm c nh vy
Ch n download xong v ri g
echo @php "%~dp0composer.phar" %*>composer.bat
[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
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
[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:
[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
<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"
[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" .
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
[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
[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
],
],
];
[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
15
[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'],
];
}
[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;
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;
[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],
];
[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'
];
}
19
[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
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
[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
[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;
[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
23
[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
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
24
[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
v nhng
[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:
Tip theo ta to cc role phn quyn ban u bao gm cho admin, manager, user
Bn vo migrate v to mi :
26
[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
[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
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
[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:
[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
[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'],
],
],
];
}
nhm vo Ph C trc.
31
, thi vo
[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
32
[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:
[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
khng th tin ni
r c nh vy
vic hc yii 2 ca bn
t m ang nh ging tip th nhn 2 em tip vin qun caf ngon qu, ngm i 2 em
n t
on th
34
[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
[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');
}
36
[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
37
[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
ht i thng b . Ch li mi h hng c
[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');
}
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
[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/
41
[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
ng gch sn xut em b
sn phm ny
, 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
[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
43
[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
44
[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:
45
[LEARN MORE IN
Yii2 Troller HTTP://BACPHAM.WORDPRESS.COM]
Hon thnh xong bn c th xem kt qu;
=))))))))))))))))))))
[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
[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
[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',
],
]) ?>
[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:
nn cc bn t t thng thc .
[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>
51
[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
[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");
53
[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:
[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
[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
[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
[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
[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
[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 "*"
60
[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
[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();
});
62