วันพฤหัสบดีที่ 27 มกราคม พ.ศ. 2554

Zend Framework ใน CI กัน

เอาล่ะครับ ทิ้งช่วงให้รอมาพักนึง ต้องขอโทษด้วย พอดีเป็นคน ธุระ ทั้ง ราชทั้งหลวง เยอะจัด 555+

ตอนแรกที่จะนำเสนอเกี่ยวกับ Long Story ที่ตั้งชื่อตอนซะเก๋ชื่อ "Beauty Your CI" เป็นการสร้าง Model (M) ที่มีความสามารถมากกว่าเดิมอย่างเห็นได้ชัด ...

เอ่อแล้วก่อนที่จะเริ่มอ่านบทความนี้ขอให้กลับไปอ่าน มาใช้ "Zend Framework ใน CI กันเถอะ" แล้วทำให้ได้ตามตัวอย่างซะก่อน เพราะถ้าทำไม่ได้ บทความนี้ และต่อๆไปก็จะไร้ความหมายไปในทันที เพราะผมใช้ Zend เยอะมากๆ ...

จุดประสงค์หลักของ Beauty your CI ก็คือการสร้างโคด เอนกประสงค์ที่มีคุณสมบัติรองรับ เว็บแอพลิเคชั่น ทุกชนิด โดยออกแบบให้ง่าย และรีดประสิทธิภาพสูงสุด และที่สำคัญและท้าทายที่สุดก็คือ เราจะต้องไม่แตะต้อง โคดอะไรที่อยู่ใน system ทั้งสิ้น ไม่ว่าจะยังไงก็ตาม เพื่อใก้อณาคตเราสามารถอัพเดท Version ได้อย่างไม่เป็นปัญหา

ส่วนจุดประสงค์ของวันนี้ก็คือ การเพิ่มความสามารถให้กับ Model นั่นเอง ถ้าเคยเคยไปเปิด model ตัวเดิมของมันดูก็จะเห็นได้ว่า มันไม่มีตัวช่วยอะไรทั้งนั้น เป็นเหมือน mask ตัวนึงเท่านั้นเอง วันนี้เราจะมาแก้ไขมันซะใหม่ โดยใช้

1. Zend DB
2. Zend Cache

เพื่อให้เป็นตัวช่วยของ MY_Model ของเรา

ก่อนอื่นให้ไปสร้าง ไฟล์ที่
/application/libraries/MY_Controller.php ขึ้นมา ใช่แล้วครับ พิพม์ไม่ผิด MY_Controller จริงๆ


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php  if (!defined(‘BASEPATH’)) exit(‘No direct script access allowed’);
  
require_once(‘Zend/Registry.php’);
  
require_once(‘Zend/Locale.php’);
  
require_once(‘Zend/Cache.php’);
  
require_once(‘Zend/Date.php’);
  
require_once(‘Zend/Session.php’);
  
class MY_Controller extends Controller {
  
  function __construct()
  {
    parent::Controller();
  }
  
}
  
?>


เท่านี้แหละครับ จุดประสงค์ของผมก็คือต้องการให้ MY_Controller.php เป็น Bootstrap แล้วก็เป็นตัว include Zend Lib ที่จะถูกใช้งานโดยรวมเข้ามา ในตอนนี้เราต้องการใช้ Zend Cache ใน MY_Model แต่ก็จะมีจุดอื่นๆ ที่ต้องใช้ Zend_Cache ตัวนี้ด้วยเช่น การ Translate การทำ ACL ดังนั้นเอามันไว้ที่นี่แหละ ดีที่สุด

กลับมาที่ MY_Model ของเรา เราจะเปลี่ยนรูปร่างมันเป็นแบบนี้ .....


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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
 
 
 
require_once('Zend/Db.php');
 
 
 
require_once('Zend/Db/Expr.php');
 
 
 
class MY_Model extends Model {
 
 
 
    public $parent_name = null;
 
 
 
    public $tbname = null;
 
 
 
    private $_hasLoadConstructor = false;
 
 
 
    private static $_conn = null;
 
 
 
    private static $_cache = null;
 
 
 
    public function __construct()
 
    {
 
        parent::_assign_libraries( (method_exists($this, '__get') OR method_exists($this, '__set')) ? FALSE : TRUE );
 
 
 
        $this->parent_name = strtolower(get_class($this));
 
        if (!$this->_hasLoadConstructor)
        {
 
                if (!isset(parent::$_cache))
            {
 
                $cacheFrontends = array(
 
                    'lifetime' =>  3600,
 
                    'automatic_serialization' => true
 
                );
 
                $cacheBackends = array(
 
                    'cache_dir' => $this->config->site_cache_upload_url('database', true),
 
                    'file_name_prefix' => 'db',
 
                    'hashed_directory_umask' => '0777',
 
                    'cache_file_umask' => '644',
 
                    'hashed_directory_level' => '0',
 
                    'server' => $this->config->item('cache_server'),
 
                    'compression' => true
 
                );
 
 
 
                self::$_cache = Zend_Cache::factory('Core', $this->config->item('cache_method'), $cacheFrontends, $cacheBackends);
 
            }
 
 
 
            $this->_hasLoadConstructor = true;
 
        }
 
 
 
        log_message('debug', "Model Class Initialized");
 
    }
 
 
 
    public function connect($profile=null)
 
    {
 
        require(APPPATH.'config/database.php');
 
 
 
        if (is_null($profile))
 
        {
 
            $profile = $active_group;
 
        }
 
 
 
        $dbConf = $db[$profile];
 
 
 
        $params = array(
 
            'host' => $dbConf['hostname'],
 
            'username' => $dbConf['username'],
 
            'password' => $dbConf['password'],
 
            'dbname' => $dbConf['database']
 
        );
 
        $conn = Zend_Db::factory($dbConf['dbdriver'], $params);
 
 
 
        if ($dbConf['char_set'] && $dbConf['dbcollat'])
 
        {
 
            $conn->Query('SET character_set_results='.$dbConf['char_set']);
 
            $conn->Query('SET collation_connection='.$dbConf['dbcollat']);
 
            $conn->Query('SET NAMES '.$dbConf['char_set']);
 
        }
 
        self::$_conn = $conn;
 
    }
 
 
 
    public function qoute($string)
 
    {
 
        $this->connect('slave');
 
        return self::$_conn->quoteIdentifier($string);
 
    }
 
 
 
    public function select()
 
    {
 
        $this->connect('slave');
 
        return self::$_conn->select();
 
    }
 
 
 
    public function fetchObject($sql, $attrs=null)
 
    {
 
        $this->connect('slave');
 
        return self::$_conn->fetchObject($sql, $attrs);
 
    }
 
 
 
    public function fetchAll($sql, $attrs=null)
 
    {
 
        $this->connect('slave');
 
        return self::$_conn->fetchAll($sql, $attrs);
 
    }
 
 
 
    public function fetchRow($sql, $attrs=null)
 
    {
 
        $this->connect('slave');
 
        return self::$_conn->fetchRow($sql, $attrs);
 
    }
 
 
 
    public function fetchOne($sql, $attrs=null)
 
    {
 
        $this->connect('slave');
 
        return self::$_conn->fetchOne($sql, $attrs);
 
    }
 
 
 
    public function fetchCol($sql, $attrs=null)
 
    {
 
        $this->connect('slave');
 
        return self::$_conn->fetchCol($sql, $attrs);
 
    }
 
 
 
    public function fetchPair($sql, $attrs=null)
 
    {
 
        $this->connect('slave');
 
        return self::$_conn->fetchPair($sql, $attrs);
 
    }
 
 
 
    public function insert($table, $data)
 
    {
 
        $this->connect(null);
 
        if (self::$_conn->insert($table, $data))
 
        {
 
            return self::$_conn->lastInsertId();
 
        }
 
        return false;
 
    }
 
 
 
    public function update($table, $data, $where)
 
    {
 
        $this->connect(null);
 
        return self::$_conn->update($table, $data, $where);
 
    }
 
 
 
    public function delete($table, $where)
 
    {
 
        $this->connect(null);
 
        return self::$_conn->delete($table, $where);
 
    }
 
    public function expr($string)
 
    {
 
        return new Zend_Db_Expr($string);
 
    }
 
 
 
    public function cacheSave($key, $data, $specificLifetime=false)
 
    {
 
        return self::$_cache->save($data, (string)$key, array(), $specificLifetime);
 
    }
 
 
 
    public function cacheLoad($key)
 
    {
 
        return self::$_cache->load((string)$key);
 
    }
 
    public function cacheRemove($key)
 
    {
 
        return self::$_cache->remove((string)$key);
 
    }
 
 
 
}
 
?>


 โดยในโคดชุดนี้มีสิ่งที่อาจจะทำให้โคดคุณ Error ได้ก็คือ

1. $this->config->site_cache_upload_url('database', true)
ส่วนนี้เป็นส่วนที่ผมใช้กำนหด path upload cache ครับ แต่ผมเขียนไว้รองรับเรื่องการย้าย File Server ด้วย ในกรณี ขอให้ Force เป็น path ที่จะเก็บ Cache ไปเองก่อนเป็นลักษณะของ Server Path นะครับ

2. 'server' => $this->config->item('cache_server'),
ส่วนนี้เป็นส่วนที่ผมต้องการให้ Cache ถูกเก็บใน Memcache ใน config ก็คือ host:port นั่นเอง ตอนนี้ comment ทิ้ง ไปทั้ง line ก่อน

3. $this->config->item('cache_method')
ตรงนี้เป็นส่วนการตั้งค่าครับว่าจะให้ Cache ทำงานด้วยอะไร File, SQLite, Memcached, APC ในตอนนี้ขอให้แก้เป็น File ไปก่อน

ทีนี้ไปดู Config ของผมกัน
Path: /application/config/database.php


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
$active_group = "master";
 
$active_record = TRUE;
 
 
$db['master']['hostname'] = "localhost";
 
$db['master']['username'] = "root";
 
$db['master']['password'] = "123";
 
$db['master']['database'] = "codeigniter";
 
$db['master']['dbdriver'] = "Mysqli";
 
$db['master']['dbprefix'] = "";
 
$db['master']['pconnect'] = TRUE;
 
$db['master']['db_debug'] = TRUE;
 
$db['master']['cache_on'] = FALSE;
 
$db['master']['cachedir'] = "";
 
$db['master']['char_set'] = "utf8";
 
$db['master']['dbcollat'] = "utf8_general_ci";
 
 
 
 
 
$db['slave']['hostname'] = "localhost";
 
$db['slave']['username'] = "root";
 
$db['slave']['password'] = "123";
 
$db['slave']['database'] = "codeigniter";
 
$db['slave']['dbdriver'] = "Mysqli";
 
$db['slave']['dbprefix'] = "";
 
$db['slave']['pconnect'] = TRUE;
 
$db['slave']['db_debug'] = TRUE;
 
$db['slave']['cache_on'] = FALSE;
 
$db['slave']['cachedir'] = "";
 
$db['slave']['char_set'] = "utf8";
 
$db['slave']['dbcollat'] = "utf8_general_ci";


จะเห็นได้ว่าผมมี Config อยู่ 2 ตัวคือ master และ slave โดยเครื่อง master ผมจะให้ทำการ insert, update, delete
ส่วน slave ผมจะให้ทำการ Read อย่างเดียว

โดยที่ slave จะเป็น Replicate DB ของ master (ถ้าใครมี db ตัวเดียว set ให้ทั้ง 2 ตัวเหมือนกันก็จบ)

จากตัวอย่างนี้เราจะใช้งานยังๆไงต่อ ?

สมมุติผมมี blogs เป็น controller ตัวนึง


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php
  
class Blogs extends MY_Controller{
  
  function __construct()
  {
    parent::__construct();
  }
  
  function index()
  {
    $this->load->model(‘model_blogs’, ‘blogs’);
    $data = $this->blogs->fetchAll();
    print_r($data);
  }
  
}
?>


ส่วน model ของ blogs ล่ะ ทำยังไง ?


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
<?php
  
class model_blogs extends MY_Model {
    
    function __construct()
    {
       parent::__constrct();
    }
  
    function fetchAll()
    {
       $select = parent::select();
       $select->from(‘blogs’)->order(‘id DESC’);
       return parent::fetchAll($select);
    }
  
    function fetch($id)
    {
      if ($row = parent::cacheLoad(‘blog’ . $id))
      {
         $select = parent::select();
         $select->from(‘blogs’)->where(‘id=?’, $id);
         $row = parent::fetchRow($select);
         parent::cacheSave(‘blog’ . $id, $row);
      }
    }
  
    function update($data, $id)
    {
       if (parent::update(‘blogs’, $data, ‘id=’ . $id))
      {
          parent::cacheRemove(‘blogs’ . $id)
      }
      return true;
    }
  
    function delete($id)
    {
       if (parent::delete(‘blogs’, ‘id=’ . $id))
       {
          parent::cacheRemove(‘blog’ . $id);
       }
       returm true;
    }
  
    function insert($data)
    {
       return parent::insert(‘blogs’, $data);
    }
}
  
?>



ให้สังเกตุ method ของ model นะครับ ในส่วนของ การ update delete fetch มีการทำงานของ cache อย่างสมบูณ์ ทำให้ cache ท่จะได้มี data สดอยู่เสมอ

เท่านี้ MY_Model ของเราก็มีตัวช่วยเพิ่มมากขึ้นแล้วครับ ทั้ง Zend_Db และ Zend_Cache ที่มักจะเอามาใช้อยู่ตลอดเวลาใน model โดยเราไม่ต้องเรียกโหลด

สำหรับบทความนี้ทำให้เราลืม
1. CI DB
2. CI Cache

เก็บขึ้นหิ้งไปเลยครับ CI DB อาจจะมีโอกาสใช้ในอีกบางเรื่องเดี๋ยวจะบอก ….

ส่วนเรื่องการใช้ fetch แลพ select ของ Zend ขอให้ไปอ่านที่
http://framework.zend.com/manual/en/zend.db.select.html
http://framework.zend.com/manual/en/zend.db.statement.html

ส่วนเรื่อง Cache มันคงไม่มีมากกว่าที่ผมเขียนเท่าไหร่แล้วสำหรับ Cache DB ลองไล่โคดผมดูคิดว่าน่าจะเข้าใจพอ

จบ แล้วครับสำหรับ บทที่ 1 Beauty My Model ยังไงทำกันให้ได้นะครับ จุดนี้คือ Core ถ้าทำไม่ได้ คงไปต่อไม่ได้ แต่ถ้าติดจริงๆ ส่งเมล์มาขอ Open Source ผมได้ แต่อาจจะงง หนักกว่าเก่า เพราะมันเป็น CI Ready To Code ที่โมจนเสร็จหมดทุกจุดแล้ว

Ps. โคดที่เขียนบางส่วนเพิ่งเขียนสดๆ มันใน บล๊อกนี่ล่ะ แน่นอนมันต้อง error บ้างอยู่แล้ว แต่คงไม่มาก ก็คนมันง่วงนี่หว่า -*-

สำหรับวันนี้ ราตรีสวัสดิ์
บทความดีๆจาก http://www.jquerytips.com/blogs/view/1007/Beauty-Your-CI-Step-1-Beauty-My-Model

ไม่มีความคิดเห็น:

แสดงความคิดเห็น