WIKI使用導(dǎo)航
站長百科導(dǎo)航
站長專題
- 網(wǎng)站推廣
- 網(wǎng)站程序
- 網(wǎng)站賺錢
- 虛擬主機(jī)
- cPanel
- 網(wǎng)址導(dǎo)航專題
- 云計(jì)算
- 微博營銷
- 虛擬主機(jī)管理系統(tǒng)
- 開放平臺(tái)
- WIKI程序與應(yīng)用
- 美國十大主機(jī)
PrestaShop ObjectModel講解
ObjectModel 是PrestaShop系統(tǒng)中的一個(gè)非常重要的抽象類(相信了解JAVA,C++等高級(jí)語言的朋友,對(duì)抽象類不陌生),準(zhǔn)確的說它是一個(gè)包含了數(shù)據(jù)表CURD基本操作的工具類。
我愿意稱這個(gè)類是一個(gè)比較別扭的base model,它包含了數(shù)據(jù)表的描述基本描述、CURD操作、常規(guī)的數(shù)據(jù)驗(yàn)證服務(wù)等。
相信有些朋友跟我一樣,已經(jīng)對(duì)Presta學(xué)習(xí)有些日子了,大家都會(huì)發(fā)現(xiàn)只要界面表單中的元素的名稱與表中的字段名稱一致,系統(tǒng)就會(huì)自動(dòng)識(shí)別出入庫數(shù)據(jù)。其實(shí)并不是這樣的。這主要是依賴兩個(gè)重要的方法來完成的,getFields、copyFromPost.
getFields 是 ObjectModel 并無實(shí)現(xiàn)的方法體,繼承ObjectModel的對(duì)象類必須針對(duì)其自身的需求,建立字段數(shù)組,以便系統(tǒng)使用,同時(shí)需要對(duì)字段數(shù)組中的字段作顯式聲明。
class Category extends ObjectModel { public $id_parent = 0; public $name; public $level_depth = 0; public $position; public $active; public $date_add; public $date_upd; .......................... public function getFields() { parent::validateFields (); if (isset ( $this->id )) $fields ['id_category'] = intval ( $this->id ); $fields ['id_parent'] = intval ( $this->id_parent ); $fields ['name'] = pSQL ( $this->name ); $fields ['level_depth'] = intval ( $this->level_depth ); $fields ['date_add'] = pSQL ( $this->date_add ); $fields ['date_upd'] = pSQL ( $this->date_upd ); return $fields; } }
另一個(gè)重要的函數(shù)處于classes/Tools.class.php中,copyFromPost。
copyFromPost負(fù)責(zé)把提交過來的表單數(shù)據(jù),填充至ObjectModel的子類。它的工作原理是非常簡單,遍歷POST中的變量,并判斷 ObjectModel子類中是否存在該變量,存在則賦值。這樣就完成了對(duì)象的數(shù)據(jù)填充,系統(tǒng)再通過getFields方法是提取需要操作的數(shù)據(jù)。
static function copyFromPost(&$object) { /* Classical fields */ foreach ( $_POST as $key => $value ) if (key_exists ( $key, $object )) { /* Do not take care of password field if empty */ if ($key == 'passwd' and Tools::getValue ( $this->identifier ) and empty ( $value )) continue; /* Automatically encrypt password in MD5 */ if ($key == 'passwd' and ! empty ( $value )) $value = Tools::encrypt ( $value ); $object->{$key} = $value; } }
注:# key_exists(PHP內(nèi)置函數(shù)),用于是判斷對(duì)象是否存在是目前屬性。