佳礼资讯网

 找回密码
 注册

ADVERTISEMENT

查看: 2019|回复: 8

用OOP的方法实现PHP购物车类型

[复制链接]
发表于 25-10-2005 05:00 PM | 显示全部楼层 |阅读模式
我没有正式用自己做的Shopping Cart,不过,参考了一些网站的Shopping Cart之后,再加上自己刚刚接触不久的PHP object oriented Programming 的知识,花了两个小时实现了以OO机制运作的Shopping Cart,在这里将源码写出来。基本上我所加入的功能是属于基本的,所以请不要见怪。

在PHP运用OOP的好处很多,虽然看起来复杂,不过debug时却是出乎意料的方便,我花了不到半小时就可以弄好了,这连我自己也没预料到。。而且在延伸功能方面也更方便,可以随心所欲地加入自己所要得功能。

基本上这个购物车的结构很简单,由两个部分组成,一个是购物车本身,另一个是货品。再货品部分先定义一个validator的界面,然后再定义一个抽象特性物件,这个特性物件利用了validator的界面,而且将被货品类本身继承,例子如下:


  1. //saveas class.propertyObject.php

  2. interface validator {
  3.         abstract function validate();
  4. }

  5. abstract class propertyObject implements validator {
  6.         //利用protected让变数能够让子类型利用
  7.         protected $propertyTable = array();
  8.         protected $changedProperties = array();
  9.         protected $data;
  10.         protected $errors = array();
  11.        
  12.         //$arData是数据来源,货品将从这里取得特性数据
  13.         public function __construct($arData){
  14.                 $this->data = $arData;
  15.         }
  16.        
  17. //利用__get函式取得所要的特性
  18.         function __get($propertyName){
  19.                 if(!array_key_exists($propertyName, $this->propertyTable)){
  20.                         throw new Exception("Invalid property "$propertyName"!");
  21.                 }
  22.                 if(method_exists($this,'get'.$propertyName)){
  23.                         return call_user_func(array($this, 'get'.$propertyName));
  24.                 }else{
  25.                         return $this->data[$this->propertyTable[$propertyName]];
  26.                 }
  27.         }

  28. //__set的函式这里将不需要用到,不过有必要的话,你可以修改。
  29.         /*function __set($propertyName, $value){
  30.                 if(!array_key_exists($propertyName, $this->propertyTable)){
  31.                         throw new Exception("Invalid property "$propertyName"!");
  32.                 }
  33.                 if(method_exists($this, 'set'.$propertyName)){
  34.                         return call_user_func(array($this,'set'.$propertyName),$value);
  35.                 }else{
  36.                         if($this->data[$this->propertyTable[$propertyName]] != $value && !in_array($propertyName, $this->changedProperties)){
  37.                                 $this->changedProperties[] = $propertyName;
  38.                         }
  39.                 $this->data[$this->propertyTable[$propertyName]] = $value;
  40.                 }
  41.         }*/
  42.        
  43.         function validate(){
  44.              //由于propertyObject没有直接被利用,所以这里放空
  45.         }
  46. }
复制代码

以上只是一个抽象类,他的功能是管理货品的特性,而且功能可以在延伸至其他的类型。定义为抽象类的原因是我们不要它被实体化,因为它本身只是一个辅助的角色;接下来我们还得制作一个和数据库沟通的界面来管理购物车和数据库的沟通,我们成为DataManager类:

  1. //saveas class.DataManager.php
  2. class DataManager {
  3.         //将DataManager的函式设为静态,以便在不必实体化的情况下运用
  4.         public static function getConnection(){
  5.                 static $hDB;
  6.                
  7.                 if(isset($hDB)){
  8.                         return $hDB;
  9.                 }
  10.                
  11.                 $hDB = mysql_connect("localhost","username","password");
  12.                 return $hDB;
  13.         }
  14.         //从数据库取出货品资料,然后再把mysql_fetch_assoc输出。
  15.         public static function getGoodData($goodid){
  16.                 $sql = "SELECT * FROM goods WHERE goodid = $goodid";
  17.                 $res = mysql_query($sql, DataManager::getConnection());
  18.                 if(!($res && mysql_num_rows($res))){
  19.                         die("Failed to retrieve $goodid data");
  20.                 }
  21.                
  22.                 return mysql_fetch_assoc($res);
  23.         }
  24. }
复制代码

以上两个类是一个很强的工具,可以用在不同的地方。接下来就是真正建造货品类了,有了以上两个工具,你的货品类结构将很简单而且适用:

  1. //saveas class.Good.php
  2. require_once('class.propertyObject.php');
  3. require_once('class.DataManager.php');

  4. //别忘了Good继承了propertyObject的特性和方法
  5. class Good extends propertyObject {

  6.         function __construct($goodid){
  7.                 //利用DataManager从数据库提取资料
  8.                 $arData = DataManager::getGoodData($goodid);
  9.                
  10.                 parent::__construct($arData);
  11.                 //将datafield资料输入propertyObject的propertyTable。
  12.                 //之后如果需要提取任何一个特性,__get函式将自动帮你从propertyTable里搜寻然后输出指定的数据。
  13.                 $this->propertyTable['goodid'] = 'goodid';
  14.                 $this->propertyTable['id'] = 'goodid';
  15.                 $this->propertyTable['name'] = 'gname';
  16.                 $this->propertyTable['category'] = 'gcategory';
  17.                 $this->propertyTable['discount'] = 'gdiscount';
  18.                 $this->propertyTable['price'] = 'gprice';
  19.                 $this->propertyTable['quantity'] = 'gquantity';
  20.                 $this->propertyTable['maxqty'] = 'gmaxqty';
  21.         }

  22.         //由于运用了validator的界面,所以在这里定义validate()函式
  23.         function validate(){
  24.                 if(!$this->name) {
  25.                         $this->errors['name'] = "The name of $this->goodid is missing";
  26.                 }

  27.                 if($this->discount == 100){
  28.                         $this->errors['discount'] = "Invalid Discount";
  29.                 }

  30.                 if($this->price <= 0){
  31.                         $this->errors['price'] = "Invalid Price";
  32.                 }

  33.                 if($this->quantity <= 0){
  34.                         $this->errors['quantity'] = "The good is out of stock!";
  35.                 }

  36.                 if(sizeof($this->errors)){
  37.                         return false;
  38.                 }else{
  39.                         return true;
  40.                 }

  41.         }
  42.         //另加一个toString()以备用(暂时没实际用途)
  43.         function __toString(){
  44.                 return 'Good: '.$this->name. '; Price: '. $this->price . '; Qty: '.$this->quantity;
  45.         }


  46. }
复制代码

货品类完成了!现在如果你已经有数据库的话,可以先进行货品类的测试,不过得先再mysql弄一个表,再自行输入一些数据。

  1. create table goods (
  2. goodid int not null auto_increment primary key,
  3. gname varchar(200),
  4. gcategory varchar(200),
  5. gdiscount int(3),
  6. gprice int(5),
  7. gquantity int(5),
  8. gmaxqty int(5)
  9. )
复制代码


我这里跳过Good的测试,因为在最后购物车类完成时我将会一起进行测试。

待续.....
回复

使用道具 举报


ADVERTISEMENT

 楼主| 发表于 25-10-2005 05:11 PM | 显示全部楼层

实现购物车类

由于购物车本身具有集合体的特性,所以接下来我将利用集合体来作为购物车的蓝图。首先,现制作一个抽象的集合体类 -- GoodsCollection,它将包含了大部分购物车所具有的特性和方法:

  1. //saveas class.GoodsCollection.php

  2. abstract class GoodsCollection {
  3.         //protected以便让子类分享
  4.         protected  $_goodies = array();//这个是集合货品的阵列
  5.         protected  $_curPrice; //目前的价钱总和
  6.       
  7.         //加入货品的函式
  8.         public function addItem(Good $objgoods, $ID=null){
  9.                 if($ID){
  10.                         if(isset($this->_goodies[$ID])){
  11.                                 throw new KeyInUseException("The $ID key is already in user!");
  12.                         }else {
  13.                                 $this->_goodies[$ID] = $objgoods;
  14.                                    
  15.                                 $this->updateprice();//当有影响到货品的数量时,价钱将自动更新
  16.                                 return;
  17.                         }
  18.                 }else{
  19.                         $key = $objgoods->id;
  20.                         $this->_goodies[$key] = $objgoods;
  21.                         $this->updateprice();
  22.                         return;
  23.                 }

  24.         }
  25.          
  26.         //移除货品
  27.         public function removeItem($ID){
  28.                 if(!isset($this->_goodies[$ID])){
  29.                         throw new KeyInvalidException("The $ID key is not exists");
  30.                 }else{
  31.                         unset($this->_goodies[$ID]);
  32.                         $this->updateprice();
  33.                 }
  34.                 return ;
  35.         }
  36.       
  37.         //以下加入几个典型集合体的功能
  38.         public function getQty(){
  39.                 return  sizeof($this->_goodies);
  40.         }

  41.         public function getGoodByID($ID){
  42.                 return $this->_goodies[$ID];
  43.         }

  44.         public function getKey(){
  45.                 return array_keys($this->_goodies);
  46.         }
  47.        
  48.         public function getGoodName(){
  49.                 $goodname = array();
  50.                 foreach($this->_goodies as $good){
  51.                         $goodname[$good->id] = $good->name;
  52.                 }
  53.                 return $goodname;
  54.         }
  55.         

  56.         //更新价钱的方法。只供物件本身调用。
  57.         private function updateprice(){
  58.                 if($this->getQty()!=0){
  59.                         $this->_curPrice = 0;
  60.                         foreach($this->_goodies as $good) {
  61.                                 $price = $good->price;
  62.                                 $discount = $good->discount;
  63.                                 $price = $price - ($price * ($discount/100));
  64.                                 $this->_curPrice += $price;
  65.                         }
  66.                 }
  67.         }

  68.         //清空购物车
  69.        protected function clearAllGoodies(){
  70.                 $this->_goodies = null;
  71.                 $this->_goodies = array();
  72.         }
  73. }

  74. //建立两个Exception的子类以便分开不同的错误
  75. class KeyInUseException extends Exception {}
  76. class KeyInvalidException extends Exception {}
复制代码


待续。。。。(下班中...)

[ 本帖最后由 苦瓜汤 于 25-10-2005 07:35 PM 编辑 ]
回复

使用道具 举报

 楼主| 发表于 25-10-2005 07:33 PM | 显示全部楼层
以上的抽象GoodsCollection类已经定义了大部分购物车类的特性,所以购物车本身的类型并不需要很多的功能,因为大部分已经继承了GoodsCollection,所以我这里只定义了一个函式 -- checkOut(),checkOut()本身搜集了最后所需要的资料,然后经由一个阵列输出。


  1. //saveas class.Cart.php

  2. require_once('class.GoodsCollection.php');

  3. class Cart extends GoodsCollection  {
  4.         private $_checkOutInfo = array();
  5.                
  6.         function checkOut(){
  7.                 $this->_checkOutInfo['quantity'] = $this->getQty();
  8.                 $this->_checkOutInfo['totalamount'] = $this->_curPrice;
  9.                 $this->_checkOutInfo['goodnamearray'] = $this->getGoodName();
  10.                 $this->_checkOutInfo['checkOutTime'] = date("d/m/Y H:i:s",time());
  11.                 $this->clearAllGoodies();
  12.                 return $this->_checkOutInfo;
  13.         }
  14.        
  15. }
复制代码


checkOut()的同时Cart也会自动清空所有的货品。clearAllGoodies可以不需要,不要考虑到如果要重复使用Cart的话就很重要,因为如果session继续保存Cart的所有资料,那么下一个checkOut()将会连上一次所购买的物品也加入。当然你也可以选择用session_destroy()来摧毁保留在session的Cart物件。

基本上购物车已经完成了,可以开始测试。利用以下的code你就可以看得出在利用OO的方法下,主要编程工作就容易了很多:


  1. <?php

  2. require_once('class.Cart.php');


  3. $shoppingCart = new Cart();


  4. $shoppingCart->addItem(new Good(1));
  5. $shoppingCart->addItem(new Good(2));

  6. $good1 = $shoppingCart->getGoodByID(1);
  7. echo $good1->name."<br>\n";
  8. //将gooid = 1的货品删除
  9. $shoppingCart->removeItem(1);

  10. $info = $shoppingCart->checkOut(); //checkout and clear cart

  11. echo "<pre>\n";
  12. print_r($info);
  13. echo "</pre>";
  14. //由于Cart已经清空,所以PHP将会提醒$good1将不被定义
  15. $good1 = $shoppingCart->getGoodByID(1); //display error
  16. ?>

复制代码


如果一切都正确,你的browser将会显示以下的资料.



  1. Maxtor HDD 60GB

  2. Array
  3. (
  4.     [quantity] => 1
  5.     [totalamount] => 136
  6.     [goodnamearray] => Array
  7.         (
  8.             [2] => Western Digital HDD 80GB
  9.         )

  10.     [checkOutTime] => 25/10/2005 19:25:18
  11. )


  12. Notice: Undefined offset: 1 in C:\Inetpub\wwwroot\Site\ShoppingCart\class.goods.php on line 42
复制代码


由于大部分工作都由物件分担,所以在实际编程或重调源码就变得很容易,只需要生成新的物件来负责工作就可以了。session方面可以直接register整个Cart物件,PHP会自动将Cart物件serialize,然后需要用到时再deserialize。

这个购物车的功能还不很完全,如果需要更多功能的话,可以利用一样的方法加入更多类型,例如:绘图类型,货品资料建设类型等等。

暂时分享到这里,希望各位能给给意见,让我能够改良这个购物车类。

这个是购物车的源码,如果有更新我将会更新此文件:
下载

[ 本帖最后由 苦瓜汤 于 26-10-2005 07:51 PM 编辑 ]
回复

使用道具 举报

发表于 26-10-2005 12:24 AM | 显示全部楼层
应该只有PHP5才能够Run的吧!!!!!! PHP 4好像不能Define Data Type 是属于Public, Private, Protected 等的吧!!

多谢分享.
回复

使用道具 举报

 楼主| 发表于 26-10-2005 09:19 AM | 显示全部楼层
原帖由 belon_cfy 于 26-10-2005 12:24 AM 发表
应该只有PHP5才能够Run的吧!!!!!! PHP 4好像不能Define Data Type 是属于Public, Private, Protected 等的吧!!

多谢分享.

对,要PHP5才能RUN。多谢提醒。
目前要解除两个限制:
1。支持单一货品超过一个数量(已经解决);
2。支持place order的功能;
回复

使用道具 举报

发表于 26-10-2005 05:30 PM | 显示全部楼层
哇~ 好象好容易DEBUG哦~. 看来我也要开始学习OOP了~

谢谢楼主分享!
回复

使用道具 举报

Follow Us
 楼主| 发表于 26-10-2005 07:44 PM | 显示全部楼层
原帖由 地鼠 于 26-10-2005 05:30 PM 发表
哇~ 好象好容易DEBUG哦~. 看来我也要开始学习OOP了~

谢谢楼主分享!

多谢支持。
目前已经大致上解除了以上两个限制。另外附加一个比较完整的测试网页(test2.php, viewcart.php)。我将会更新帖子内的文件连接。P/S:由于已经支持place order,所以需要另外附加一个table。


  1. CREATE TABLE `orders` (
  2.   `transactionid` int(11) NOT NULL auto_increment,
  3.   `orderid` int(12) NOT NULL,
  4.   `goodid` int(11) NOT NULL,
  5.   `price` int(5) default NULL,
  6.   `discount` int(3) default NULL,
  7.   `quantity` int(5) default NULL,
  8.   `orderdate` datetime default NULL,
  9.   `shippen` char(1) default '0',
  10.   PRIMARY KEY  (`transactionid`),
  11.   constraint fk_orders_goodid foreign key (goodid) references goods(goodid)
  12. )
复制代码

[ 本帖最后由 苦瓜汤 于 26-10-2005 07:49 PM 编辑 ]
回复

使用道具 举报

发表于 27-10-2005 09:20 AM | 显示全部楼层

  1. Array
  2. (
  3.     [quantity] => 1
  4.     [totalamount] => 136
  5.     [goodnamearray] => Array
  6.         (
  7.             [2] => Western Digital HDD 80GB
  8.         )

  9.     [checkOutTime] => 25/10/2005 19:25:18
  10. )
复制代码


從這裡看來 GoodsCollection 里的每一個 item 都只有 1 個數量, 可以 / 可能有不同的數量嗎 ?

例入


  1. Array
  2. (
  3.     [quantity] => 1
  4.     [totalamount] => 400
  5.     [goodnamearray] => Array
  6.         (
  7.             Array (
  8.                        [item] => Western Digital HDD 80GB
  9.                        [qty] => 1
  10.                        [price] => 100
  11.             )
  12.             Array (
  13.                        [item] => 256MB DDR
  14.                        [qty] => 2
  15.                        [price] => 150
  16.             )
  17.         )

  18.     [checkOutTime] => 25/10/2005 19:25:18
  19. )
复制代码
回复

使用道具 举报


ADVERTISEMENT

 楼主| 发表于 27-10-2005 09:47 AM | 显示全部楼层
原帖由 flashang 于 27-10-2005 09:20 AM 发表
[code]
Array
(
    [quantity] => 1
    [totalamount] => 136
    [goodnamearray] => Array
        (
            [2] => Western Digital HDD 80GB
        )

    [checkOutTime] =& ...

目前我已经修改了这个限制,完整的源码可以在帖子里的下载点下载。当你加入同一货品物件时,Cart会检查是否有同一类货品在里面,如果有的话,Cart会将该货品的数量特性增加,并不会另外重复将新的货品实体化,以免浪费系统资源。至于checkout 的info只是一个简化的输出阵列,所以资料不多,不过货品类型本身已经拥有所有的资料,看你本身如何整理资料的输出。

[ 本帖最后由 苦瓜汤 于 27-10-2005 09:49 AM 编辑 ]
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

 

ADVERTISEMENT



ADVERTISEMENT



ADVERTISEMENT

ADVERTISEMENT


版权所有 © 1996-2023 Cari Internet Sdn Bhd (483575-W)|IPSERVERONE 提供云主机|广告刊登|关于我们|私隐权|免控|投诉|联络|脸书|佳礼资讯网

GMT+8, 4-3-2025 10:51 PM , Processed in 0.132528 second(s), 25 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表