Untuk lebih jelasnya kita langsung saja ke dalam prakteknya Membuat Login di Yii Framework, ikutilah langkah - langkah berikut :
1. Tabel
Buatlah sebuah tabel baru di dalam database anda dengan nama users, dengan struktur tabel seperti berikut :
| Name | Type | Size | Extra | Primary | 
| id | INT | 100 | auto_increment | yes | 
| username | VARCHAR | 100 | ||
| password | VARCHAR | 100 | ||
| level | INT | 11 | 
Kemudian isikan tabel tersebut dengan tiga buah data, anda dapat menambahkan datanya melalui phpMyAdmin, pilih database lalu klik tab SQL, lalu masukan perintah berikut :
INSERT INTO users (username , password, level) VALUES ('jin',md5('jin'),1);
INSERT INTO users (username , password, level) VALUES ('rias',md5('gremory'),2);
INSERT INTO users (username , password, level) VALUES ('shina',md5('mashiro'),2);
INSERT INTO users (username , password, level) VALUES ('jin',md5('jin'),1);
INSERT INTO users (username , password, level) VALUES ('rias',md5('gremory'),2);
INSERT INTO users (username , password, level) VALUES ('shina',md5('mashiro'),2);
Sekarang anda klik tombol "Go" maka akan memasukan ketiga data user dan password tersebut ke dalam database :
2. Model
Buatlah sebuah model baru dengan menggunakan Gii Code Generator dengan nama User dan dengan nama tabel users:
Sekarang buka model User.php yang sudah berhasil di generate yang terdapat dalam direktori Protected\models kemudian tambahkan script berikut :
//digunakan untuk memproses data setelah di validasi
protected function afterValidate() {
parent::afterValidate();
            
//melakukan enkripsi pada passwod yang di input
$this->password = $this->encrypt($this->password);
}
        
//membuat sebuah fungsi untuk mengenkripsi data
public function encrypt($value){
return md5($value);
}
//digunakan untuk memproses data setelah di validasi
protected function afterValidate() {
parent::afterValidate();
//melakukan enkripsi pada passwod yang di input
$this->password = $this->encrypt($this->password);
}
//membuat sebuah fungsi untuk mengenkripsi data
public function encrypt($value){
return md5($value);
}
Maka sekarang script user anda selengkapnya adalah :
| 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
30 
31 
32 
33 
34 
35 
36 
37 
38 
39 
40 
41 
42 
43 
44 
45 
46 
47 
48 
49 
50 
51 
52 
53 
54 
55 
56 
57 
58 
59 
60 
61 
62 
63 
64 
65 
66 
67 
68 
69 
70 
71 
72 
73 
74 
75 
76 
77 
78 
79 
80 
81 
82 
83 
84 
85 
86 
87 
88 
89 
90 
91 
92 
93 
94 
95 
96 
97 
98 
99 
100 
101 
102 
103 
104 
105 
106 
107 
108 
109 
110 
111 
112 
113 
114 | <?php/** * This is the model class for table "users". * * The followings are the available columns in table 'users': * @property integer $id * @property string $username * @property string $password * @property integer $level */classUser extendsCActiveRecord{ /**  * @return string the associated database table name  */                //digunakan untuk memproses data setelah validasi        protectedfunctionafterValidate() {            parent::afterValidate();                        //melakukan enkripsi pada data yang di input            $this->password = $this->encrypt($this->password);        }                //membuat sebuah fungsi enkripsi        publicfunctionencrypt($value){            returnmd5($value);        }        publicfunctiontableName() {  return'users'; } /**  * @return array validation rules for model attributes.  */ publicfunctionrules() {  // NOTE: you should only define rules for those attributes that  // will receive user inputs.  returnarray(   array('level', 'numerical', 'integerOnly'=>true),   array('username, password', 'length', 'max'=>100),   // The following rule is used by search().   // @todo Please remove those attributes that should not be searched.   array('id, username, password, level', 'safe', 'on'=>'search'),  ); } /**  * @return array relational rules.  */ publicfunctionrelations() {  // NOTE: you may need to adjust the relation name and the related  // class name for the relations automatically generated below.  returnarray(  ); } /**  * @return array customized attribute labels (name=>label)  */ publicfunctionattributeLabels() {  returnarray(   'id'=> 'ID',   'username'=> 'Username',   'password'=> 'Password',   'level'=> 'Level',  ); } /**  * Retrieves a list of models based on the current search/filter conditions.  *  * Typical usecase:  * - Initialize the model fields with values from filter form.  * - Execute this method to get CActiveDataProvider instance which will filter  * models according to data in model fields.  * - Pass data provider to CGridView, CListView or any similar widget.  *  * @return CActiveDataProvider the data provider that can return the models  * based on the search/filter conditions.  */ publicfunctionsearch() {  // @todo Please modify the following code to remove attributes that should not be searched.  $criteria=newCDbCriteria;  $criteria->compare('id',$this->id);  $criteria->compare('username',$this->username,true);  $criteria->compare('password',$this->password,true);  $criteria->compare('level',$this->level);  returnnewCActiveDataProvider($this, array(   'criteria'=>$criteria,  )); } /**  * Returns the static model of the specified AR class.  * Please note that you should have this exact method in all your CActiveRecord descendants!  * @param string $className active record class name.  * @return User the static model class  */ publicstaticfunctionmodel($className=__CLASS__) {  returnparent::model($className); }} | 
3. Components
Selanjutnya sekarang kita akan membuat user yang sudah kita simpan di dalam tabel di tambahkan ke dalam UserIndentitiy.php. Sekarang buka file UserIndentity.php yang terdapat dalam direktori Protected\components kemudian ubah scriptnya menjadi seperti berikut :
Sebenarnya kita hanya menambahkan beberapa baris kode dan merubah strukturnya saja, penjelasan dari script di atas :
$model = new User;
$user= $model->findByAttributes(array('username'=>$this->username));
Memberikan nilai pada $_id;
$this->errorCode=self::ERROR_NONE;
Ini berarti tidak ada error.
public function getId() {
return $this->_id;
Unutk mendapatkan nilai $_id
apabila anda belumn mengubah URL anda masukan seperti ini :
http://localhost/Belajar_Yii/website/index.php?r=site/login
*notes kode yang berwarna merah adalah direktori folder Yii Framework anda di localhost.
Sekarang loginlah denan username dan password yang anda masukan ke dalam database, contoh username "jin" pass "jin". Sekarang cosutum login telah selesai selanjutnya kita akan memberikan hak akses pada setiap user dengan level berbeda - beda.
Login di Yii Framework sekarang sudah selesai, baca juga tutorial belajar Yii Framework lainnya.
| 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
30 
31 
32 
33 
34 
35 
36 
37 
38 
39 | <?php/** * UserIdentity represents the data needed to identity a user. * It contains the authentication method that checks if the provided * data can identity the user. */classUserIdentity extendsCUserIdentity{    private$_id; /**  * Authenticates a user.  * The example implementation makes sure if the username and password  * are both 'demo'.  * In practical applications, this should be changed to authenticate  * against some persistent user identity storage (e.g. database).  * @return boolean whether authentication succeeds.  */ publicfunctionauthenticate() {                $model= newUser;  $user= $model->findByAttributes(array('username'=>$this->username));                if($user===null){                    $this->errorCode=self::ERROR_USERNAME_INVALID;                }else{                    if($user->password !== $user->encrypt($this->password)){                        $this->errorCode=self::ERROR_PASSWORD_INVALID;                    }else{                        $this->_id = $user->id;                        $this->errorCode=self::ERROR_NONE;                    }                }  return!$this->errorCode; }                publicfunctiongetId() {            return$this->_id;        }} | 
Sebenarnya kita hanya menambahkan beberapa baris kode dan merubah strukturnya saja, penjelasan dari script di atas :
$model = new User;
$user= $model->findByAttributes(array('username'=>$this->username));
Digunakan untuk menemukan data user dalam database berdasarkan username.
if($user===null){
$this->errorCode=self::ERROR_USERNAME_INVALID;
if($user===null){
$this->errorCode=self::ERROR_USERNAME_INVALID;
Maksud dari script dia atas adalah jika user tidak ada maka tampilkan pesan error.
if($user->password !== $user->encrypt($this->password)){
$this->errorCode=self::ERROR_PASSWORD_INVALID;
if($user->password !== $user->encrypt($this->password)){
$this->errorCode=self::ERROR_PASSWORD_INVALID;
Maksud dari script dia atas adalah jika passwod salah maka tampilkan pesan error.
this->_id = $user->id;
this->_id = $user->id;
Memberikan nilai pada $_id;
$this->errorCode=self::ERROR_NONE;
Ini berarti tidak ada error.
public function getId() {
return $this->_id;
Unutk mendapatkan nilai $_id
4. Test
Sekarang untuk mencobanya anda buka browser kemudian ketikan alamat berikut :
http://localhost/Belajar_Yii/website/site/login
apabila anda belumn mengubah URL anda masukan seperti ini :
http://localhost/Belajar_Yii/website/index.php?r=site/login
*notes kode yang berwarna merah adalah direktori folder Yii Framework anda di localhost.
Sekarang loginlah denan username dan password yang anda masukan ke dalam database, contoh username "jin" pass "jin". Sekarang cosutum login telah selesai selanjutnya kita akan memberikan hak akses pada setiap user dengan level berbeda - beda.
Login di Yii Framework sekarang sudah selesai, baca juga tutorial belajar Yii Framework lainnya.



 
Tidak ada komentar:
Posting Komentar