1111111111111


เว็บใหม่ที่ผมขอใช้ฟรีครับ ภาวนาอยู่ว่าวันดีคืนดีข้อมูลคงไม่หายเหมือนเว็บอื่น

วันจันทร์ที่ 21 กุมภาพันธ์ พ.ศ. 2554

การเพิ่มข้อมูล User โดยการสร้างคลาสที่ถ่ายทอดมาจาก CWebUser

การเพิ่มข้อมูล User โดยการสร้างคลาสที่ถ่ายทอดมาจาก CWebUser สามารถทำได้ดังนี้

1 ต้องมี User model (class User extends CActiveRecord) เก็บไว้ที่ protected/models/User.php


// this file must be stored in:
// protected/models/User.php

class User extends CActiveRecord
{
/**
* Returns the static model of the specified AR class.
* @return CActiveRecord the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}

/**
* @return string the associated database table name
*/
public function tableName()
{
return 'User';
}
}




2 สร้างคลาส (component) ที่ถ่ายทอดมาจาก CWebUser (จากตัวอย่างใช้ WebUser)

// this file must be stored in:
// protected/components/WebUser.php

class WebUser extends CWebUser {

// Store model to not repeat query.
private $_model;

// Return first name.
// access it by Yii::app()->user->first_name
function getFirst_Name(){
$user = $this->loadUser(Yii::app()->user->id);
return $user->first_name;
}

// This is a function that checks the field 'role'
// in the User model to be equal to 1, that means it's admin
// access it by Yii::app()->user->isAdmin()
function isAdmin(){
$user = $this->loadUser(Yii::app()->user->id);
return intval($user->role) == 1;
}

// Load user model.
protected function loadUser($id=null)
{
if($this->_model===null)
{
if($id!==null)
$this->_model=User::model()->findByPk($id);
}
return $this->_model;
}
}



3 ระบุ config ใน config/main.php ดังนี้

...
...
// application components
'components'=>array(
'user'=>array(
'class' => 'WebUser',
),
),
...
...


เวลาเรียกใช้งาน
Yii::app()->user->first_name - เข้าถึงค่า first_name
Yii::app()->user->isAdmin() - ถามว่าเป็น Admin หรือเปล่า (role = 1 หรือเปล่า)
ถ้าอยากเพิ่ม เช่น


class WebUser extends CWebUser {
...
...
function getDepartmaentName(){
$user = $this->loadUser(Yii::app()->user->id);
return $user->Departmaent_name; // ต้องไปสร้าง Field ชื่อ Departmaent_name เพิ่มในฐานข้อมูลด้วยนะครับ
}
...
...
}



เวลาเรียกใช้ก็



Yii::app()->user->departmaentName



เราก็จะได้ข้อมุลคณะที่ user คนนี้สังกัด

ผมคัดลอกมาจาก http://www.yiiframework.com/wiki/60/add-information-to-yii-app-user-by-extending-cwebuser