public function __construct($bandName) { $db = mysql_connect("localhost", "root", "root"); mysql_select_db("test"); $sql = "select CD.id, CD.band, CD.title, tracks.tracknum, tracks.title as tracktitle "; $sql .= "from CD left join tracks on CD.id = tracks.cid "; $sql .= "where band = '" . mysql_real_escape_string($bandName) . "' "; $sql .= "order by tracks.tracknum"; $results = mysql_query($sql); $cdID = 0; $cd = NULL; while ($result = mysql_fetch_array($results)) { if ($result["id"] !== $cdID) { if (!is_null($cd)) { $this->_CDs[] = $cd; } $cdID = $result['id']; $cd = new CD($result['band'], $result['title']); } $cd->addTrack($result['tracktitle']); } $this->_CDs[] = $cd; }
foreach ($tracksFroExternalSource as $track) { $myCD->addTrack($track); } print "The CD contains:{$myCD->getTrackList()}\n"; /** * 需求发生小变化: 要求每个输出的参数都采用大写形式. 对于这么小的变化而言, 最佳的做法并非修改基类或创建父 - 子关系, * 而是创建一个基于装饰器设计模式的对象。 * */ class CDTrackListDecoratorCaps { private $_cd; public function __construct(CD $cd) { $this->_cd = $cd; } public function makeCaps() { foreach ($this->_cd->trackList as &$track) { $track = strtoupper($track); } } } $myCD = new CD(); foreach ($tracksFroExternalSource as $track) { $myCD->addTrack($track); } //新增以下代码实现输出参数采用大写形式 $myCDCaps = new CDTrackListDecoratorCaps($myCD); $myCDCaps->makeCaps(); print "The CD contains:{$myCD->getTrackList()}\n";
echo "construct " . $name . "\n"; $this->_name = $name; } public function getName() { return $this->_name; } } class ArtistFactory { private $_artists = array(); public function getArtist($name) { if (isset($this->_artists[$name])) { return $this->_artists[$name]; } else { $this->_artists[$name] = new Artist($name); return $this->_artists[$name]; } } } $objArtistFactory = new ArtistFactory(); $objCD1 = new CD(); $objCD1->setTitle("title1"); $objCD1->setArtist($objArtistFactory->getArtist("artist1")); $objCD2 = new CD(); $objCD2->setTitle("title2"); $objCD2->setArtist($objArtistFactory->getArtist("artist2")); $objCD3 = new CD(); $objCD3->setTitle("title3"); $objCD3->setArtist($objArtistFactory->getArtist("artist1"));
} } public function buy() { //stub actions of buying $this->notifyObserver('purchased'); } } class buyCDNotifyStreamObserver { public function update(CD $cd) { $activity = "The CD named {$cd->title} by "; $activity .= "{$cd->band} was just purchased."; activityStream::addNewItem($activity); } } class activityStream { public static function addNewItem($item) { //stub functions print $item; } } $title = 'Waste of a Rib'; $band = 'Never Again'; $cd = new CD($title, $band); $observer = new buyCDNotifyStreamObserver(); $cd->attachObserver('purchased', $observer); $cd->buy();
<?php require_once __DIR__ . '/../vendor/autoload.php'; require_once __DIR__ . '/../src/CD.php'; session_start(); if (empty($_SESSION['list_of_cds'])) { $_SESSION['list_of_cds'] = array(); } $app = new Silex\Application(); $app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => __DIR__ . '/../views')); $app->get('/', function () use($app) { return $app['twig']->render('home.html.twig'); }); $app->get('/new_cd', function () use($app) { return $app['twig']->render('new_cd.html.twig'); }); $app->post('/cd_inserted', function () use($app) { $cd = new CD($_POST['album'], $_POST['artist']); $cd->save(); $cd_list = CD::getAll(); return $app['twig']->render('home.html.twig', array('cds' => $cd_list)); }); return $app;
{ $this->title = $title; } public function setBand($band) { $this->band = $band; } public function addTrack($track) { $this->tracks[] = $track; } } $title = 'Waste of a Rib'; $band = 'Never Again'; $tracksFromExternalSource = array('What It Means', 'Brrr', 'Goodbye'); $cd = new CD(); $cd->setTitle($title); $cd->setBand($band); foreach ($tracksFromExternalSource as $track) { $cd->addTrack($track); } class enhancedCD { public $title = ''; public $band = ''; public $tracks = array(); public function __construct() { $this->tracks[] = 'DATA TRACK'; } public function setTitle($title)
{ public function visitCD($cd) { $logline = "{$cd->title} by {$cd->band} was purchased for {$cd->price} "; $logline .= "at " . sdate('r') . "\n"; file_put_contents('/logs/purchases.log', $logline, FILE_APPEND); } } $externalBand = 'Never Again'; $externalTitle = 'Waste of a Rib'; $externalPrice = 9.99; $cd = new CD($externalBand, $externalTitle, $externalPrice); $cd->buy(); $cd->acceptVisitor(new CDVisitorLogPurchase()); class CDVisitorPopulateDiscountList { public function visitCD($cd) { if ($cd->price < 10) { $this->_populateDiscountList($cd); } } protected function _populateDiscountList($cd) { //stub connects to sqlite and logs } } $cd = new CD($externalBand, $externalTitle, $externalPrice); $cd->buy(); $cd->acceptVisitor(new CDVisitorLogPurchase()); $cd->acceptVisitor(new CDVisitorPopulateDiscountList());
{ return round($this->price * 0.05, 2); } } class BandEndorsedCaseOfCereal extends SaleItemTemplate { public $band; public function __construct($band, $price) { $this->band = $band; $this->price = $price; } protected function taxAddition() { return 0; } protected function oversizedAddition() { return round($this->price * 0.2, 2); } } $externalTitle = "Waste of a Rib"; $externalBand = "Never Again"; $externalCDPrice = 12.99; $externalCerealPrice = 90; $cd = new CD($externalBand, $externalTitle, $externalCDPrice); $cd->setPriceAdjustments(); print 'The total cost for CD item is: $' . $cd->price . ' < br / > '; $cereal = new BandEndorsedCaseOfCereal($externalBand, $externalCerealPrice); $cereal->setPriceAdjustments(); print 'The total cost for the Cereal case is: $' . $cereal->price;
$app = new Silex\Application(); $app['debug'] = true; $app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => __DIR__ . '/../views')); $app->get("/", function () use($app) { return $app['twig']->render('main_page.html.twig', array('all_cds' => CD::getAll())); }); $app->get("/add_form", function () use($app) { return $app['twig']->render('add_form.html.twig'); }); $app->get("/search_form", function () use($app) { return $app['twig']->render('search_form.html.twig'); }); $app->get("/search_results", function () use($app) { $allCD = CD::getAll(); $foundCD = array(); $artistSearch = $_GET['artist']; foreach ($allCD as $cd) { $actualCD = strtolower($cd->getArtist()); $actualSearch = strtolower($artistSearch); if (strpos($actualCD, $actualSearch) != false) { array_push($foundCD, $cd); } } return $app['twig']->render('search_results.html.twig', array('found' => $foundCD)); }); $app->post("/add", function () use($app) { $newCD = new CD($_POST['artist'], $_POST['album'], $_POST['cover']); $newCD->save(); return $app['twig']->render('added.html.twig', array('newCd' => $newCD)); }); return $app;
$app = new Silex\Application(); $app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => __DIR__ . '/../views')); $app->get('/', function () use($app) { return $app['twig']->render('cds.html.twig', array('albums' => CD::getAll())); }); $app->get('/new_cd', function () use($app) { return $app['twig']->render('new_cd.html.twig'); }); $app->post('/new_cd', function () use($app) { $album = new CD($_POST['title'], $_POST['artist']); $album->save(); return $app['twig']->render('cds.html.twig', array('albums' => CD::getAll())); }); $app->get('/searchbyartist', function () use($app) { return $app['twig']->render('searchbyartist.html.twig'); }); $app->get('/search_results', function () use($app) { $albums = CD::getAll(); $catalog = array(); foreach ($albums as $album) { if ($album->artistSearch($_GET['artist_search'])) { array_push($catalog, $album); } } return $app['twig']->render('search_results.html.twig', array('catalog' => $catalog)); }); $app->post('/delete_cds', function () use($app) { CD::deleteAll(); return $app['twig']->render('delete_cds.html.twig'); }); return $app;
} class json { /** * @param $returnData * @return string */ public function get($returnData) { return json_encode($returnData); } } class xml { /** * @param $returnData * @return string */ public function get($returnData) { $xml = '<?xml version="1.0" encoding="utf-8"?>'; $xml .= '<return>'; $xml .= '<data>' . serialize($returnData) . '</data>'; $xml .= '</return>'; return $xml; } } $cd = new CD('cd1', 'zhu a zhu'); echo $cd->getCd(new json()); echo "<hr>"; echo $cd->getCd(new xml());
<?php class CD { public $title = ''; public $band = ''; public function __construct($title, $band) { $this->title = $title; $this->band = $band; } public function getAsXML() { $doc = new DomDocument(); $root = $doc->createElement('CD'); $root = $doc->appendChild($root); $title = $doc->createElement('TITLE', $this->title); $title = $root->appendChild($title); $band = $doc->createElement('BAND', $this->band); $band = $root->appendChild($band); return $doc->saveXML(); } } $cd = new CD('Never Again', 'Waste of a Rib'); print $cd->getAsXML();
} public function buy() { $this->notifyObserver("purchased"); } } //观察者类 后台处理 class buyCDNotifyStreamObserver { public function update(CD $cd) { $activity = "The CD named {$cd->title} by "; $activity .= "{$cd->band} was just purchased."; activityStream::addNewItem($activity); } } //消息同事类 前台输出 class activityStream { public static function addNewItem($item) { print $item; } } //测试实例 $title = "Waste of a Rib"; $band = "Never Again"; $cd = new CD($title, $band); $observer = new buyCDNotifyStreamObserver(); $cd->attachObserver("purchased", $observer); $cd->buy();
$cd = new CD($_POST['title'], new Artist($_POST['artist'])); $cd->save(); return $app['twig']->render('display.html.twig', array('cds' => CD::getAll())); }); $app->post("/clear", function () use($app) { CD::reset(); return $app['twig']->render('display.html.twig', array('cds' => CD::getAll())); }); $app->get("/cd_search", function () use($app) { $cds = CD::getAll(); $search_return = array(); $search = strtolower($_GET['artist']); foreach ($cds as $cd) { $this_artist = $cd->getArtist(); $artist = strtolower($this_artist->getName()); if ($cd->matchArtist($artist, $search)) { array_push($search_return, $cd); } } return $app['twig']->render('displaysearch.html.twig', array('cds' => $search_return)); }); $app->get("/new", function () use($app) { return $app['twig']->render('new_cd.html.twig'); }); $app->get("/list", function () use($app) { return $app['twig']->render('display.html.twig', array('cds' => CD::getAll())); }); $app->get("/search", function () use($app) { return $app['twig']->render('searchbyartist.html.twig'); }); return $app;
{ $this->_connect(); $query = "update CDs set bought=1 where band='"; $query .= mysql_real_escape_string($this->_band, $this->_handle); $query .= "' and title='"; $query .= mysql_real_escape_string($this->_title, $this->_handle); $query .= "'"; mysql_query($query, $this->_handle); } protected function _connect() { $this->_handle = mysql_connect('localhost', 'user', 'pass'); mysql_select_db('CD', $this->_handle); } } $externalTitle = 'Waste of a Rib'; $externalBand = 'Never Again'; $cd = new CD($externalTitle, $externalBand); $cd->buy(); class DallasNOCCDProxy extends CD { protected function _connect() { $this->_handle = mysql_connect('dallas', 'user', 'pass'); mysql_select_db('CD'); } } $externalTitle = 'Waste of a Rib'; $externalBand = 'Never Again'; $cd = new DallasNOCCDProxy($externalTitle, $externalBand); $cd->buy();
public function getTrackList() { $output = ''; foreach ($this->trackList as $num => $track) { $output .= $num + 1 . ") {$track}. "; } return $output; } } class CDTrackListDecoratorCaps { private $__cd; public function __construct(CD $cd) { $this->__cd = $cd; } public function makeCaps() { foreach ($this->__cd->trackList as &$track) { $track = strtoupper($track); } } } $tracksFromExternalSource = array('What It Means', 'Brr', 'Goodbye'); $myCD = new CD(); foreach ($tracksFromExternalSource as $track) { $myCD->addTrack($track); } $myCDCaps = new CDTrackListDecoratorCaps($myCD); $myCDCaps->makeCaps(); print "The CD contains the following tracks: " . $myCD->getTrackList();
require_once __DIR__ . "/../vendor/autoload.php"; require_once __DIR__ . "/../src/Cd.php"; session_start(); if (empty($_SESSION['list_of_CDs'])) { $_SESSION['list_of_CDs'] = array(); } $app = new Silex\Application(); $app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => __DIR__ . '/../views')); $app->get("/", function () use($app) { $cd_list = $_SESSION['list_of_CDs']; return $app['twig']->render('index.html.twig', array('cds' => $cd_list)); }); $app->get("/add_CD", function () use($app) { return $app['twig']->render('add_CD.html.twig'); }); $app->post("/new_CD", function () use($app) { $newCD = new CD($_POST['title'], $_POST['artist'], $_POST['cover_image']); $newCD->saveCD(); return $app['twig']->render('new_CD.html.twig', array('newCD' => $newCD)); }); $app->post("/search", function () use($app) { $cds = $_SESSION['list_of_CDs']; $search_string = $_POST['searchCDs']; $search_results = CD::searchArtist($cds, $search_string); return $app['twig']->render('search_results.html.twig', array('results' => $search_results)); }); $app->get("/delete", function () use($app) { CD::deleteAll(); return $app['twig']->render('index.html.twig'); }); return $app;
</div> </body> <?php /* if(isset($_POST['cantante'])) { var_dump($_POST); } */ if(isset($_POST['cantante']) && isset($_POST['titulo']) && isset($_POST['anio'])) { require_once("/clases/cd.php"); require_once("/clases/AccesoDatos.php"); $miCD = new CD(); $miCD->cantante = $_POST['cantante']; $miCD->titulo = $_POST['titulo']; $miCD->año = $_POST['anio']; $ultimoID=$miCD->InsertarElCd(); echo "Ultimo ID = ".$ultimoID; }
{ $float_price = (double) $new_price; if ($float_price != 0) { $formatted_price = number_format($float_price, 2); $this->price = $formatted_price; } } function getPrice() { return $this->price; } } $first_cd = new CD("Master of Reality", "Black Sabbath", "images/reality.jpg"); $second_cd = new CD("Electric Ladyland", "Jimi Hendrix", "images/ladyland.jpg"); $third_cd = new CD("Nevermind", "Nirvana", "images/nevermind.jpg"); $fourth_cd = new CD("I don't get it", "Pork Lion", "images/porklion.jpg", 49.99); $fourth_cd->setPrice("1.394"); $cds = array($first_cd, $second_cd, $third_cd, $fourth_cd); ?> <!DOCTYPE html> <html> <head> <link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css'> <title>My CD Store</title> </head> <body> <div class="container"> <?php foreach ($cds as $album) { $cd_price = $album->getPrice(); echo "<div class='row'>\n <div class='col-md-6'>\n <img src='{$album->cover_art}'>\n </div>\n <div class='col-md-6'>\n <p>{$album->title}</p>\n <p>By {$album->artist}</p>\n <p>\${$cd_price}</p>\n </div>\n </div>\n ";
{ $float_price = (double) $new_price; if ($float_price != 0) { $formatted_price = number_format($float_price, 2); $this->price = $formatted_price; } } function getPrice() { return $this->price; } } $first_cd = new CD("Master of Reality", "Black Sabbath", "images/reality.jpg"); $second_cd = new CD("Electric Ladyland", "Jimi Hendrix", "images/ladyland.jpg"); $third_cd = new CD("Nevermind", "Nirvana", "images/nevermind.jpg"); $fourth_cd = new CD("IDGI", "The Internet", "images/default.mp4", 49.99); $fourth_cd->setPrice("\$1.3925"); // instead of declaring the properties and values of each object, within the delcaration, as below, we passsing to the method an argument for each property that we want to set. // $first_cd = new CD(); // $first_cd->title = "Master of Reality"; // $first_cd->artist = "Black Sabbath"; // $first_cd->cover_art = "images/reality.jpg"; // $first_cd->price = 10.99; // // $second_cd = new CD(); // $second_cd->title = "Electric Ladyland"; // $second_cd->artist = "Jimi Hendrix"; // $second_cd->cover_art = "images/ladyland.jpg"; // $second_cd->price = 10.99; // // $third_cd = new CD();
protected $_containers = array(); public function __construct() { $this->_containers[] = "CD"; $this->_containers[] = "MP3Archive"; } public function change($originalObject, $newValue) { $title = $originalObject->title; $band = $originalObject->band; foreach ($this->_containers as $container) { if (!$originalObject instanceof $container) { $object = new $container(); $object->title = $title; $object->band = $band; foreach ($newValue as $key => $val) { $object->{$key} = $val; } $object->save(); } } } } //测试实例 $titleFromDB = "Waste of a Rib"; $bandFromDB = "Never Again"; $mediator = new MusicContainerMediator(); $cd = new CD($mediator); $cd->title = $titleFromDB; $cd->band = $bandFromDB; $cd->changeBandName("Maybe Once More125");