Topic
  • No replies
cmw.osdude
cmw.osdude
34 Posts

Pinned topic Alternative code contribution for "Five more PHP design patterns"

‏2012-06-15T15:47:20Z |

Here is the code contributed by JaeTask from the article   "Five more PHP design patterns", posted here for discussion.

<?php

# an even better solution imo would be to let the shipper itself decide which packages
# should be sent by rail or truck, maybe based on size etc.
# alternative shippers would be in play for different couriers etc

class Package {
    protected $description;
    protected $weight;
    
    function __construct($description) {
        $this->description = $description;
    }
    function setDescription($value) {
        $this->description = $value;
    }
    function getDescription() {
        return $this->description;
    }
    function setWeight($value) {
        $this->weight = $value;
    }
    function getWeight() {
        return $this->weight;
    }
}

class ShippingDelegate {
    protected $package = null;
    
    function __construct($package) {
        $this->package = $package;
    }
    function deliver() {
        if ($this->package->getWeight() > 99)
        {
            echo "Shipping {$this->package->getDescription()} by rail.\n";
        } else {
            echo "Shipping {$this->package->getDescription()} by truck\n";
        }
    }
}

## send a heavy package
$pkg = new Package("Heavy Package");
$pkg->setWeight(100);
$shipper = new ShippingDelegate($pkg);
$shipper->deliver($pkg);

## send a light package
$pkg = new Package("Light Package");
$pkg->setWeight(23);
$shipper = new ShippingDelegate($pkg);
$shipper->deliver($pkg);
?>

 

Updated on 2012-06-15T15:54:11Z at 2012-06-15T15:54:11Z by cmw.osdude