SoFunction
Updated on 2025-04-12

Introduction to php design pattern value object pattern page 3/5


Detailed examples:

Let's see the functionality of the value object pattern in a more complex example.

Let's start implementing a Monopoly game based on the Dollar class in PHP5.

The framework of the first Monopoly class is as follows:

class Monopoly {
protected $go_amount;
/**
* game constructor
* @return void
*/
public function __construct() {
$this->go_amount = new Dollar(200);
}
/**
* pay a player for passing sweep o?/span>
* @param Player $player the player to pay
* @return void
*/
public function passGo($player) {
$player->collect($this->go_amount);
}
}
At present, Monopoly's functions are relatively simple. The constructor creates an instance of the Dollar class $go_amount, set to 200. The instance go_amount is often called by the passGo() function, which takes a player parameter and makes the function collect of the object player to $200 on the player machine.

For the declaration of the Player class, please refer to the following code. The Monoplay class calls the Player::collect() method with a Dollar parameter. Then add the Dollar value to the Player's cash balance. In addition, by judging the balance returned by the Player::getBalance() method function, we can know whether accessing the current Player and Monopoly object instances is at work.

class Player {
protected $name;
protected $savings;
/**
* constructor
* set name and initial balance
* @param string $name the players name
* @return void
*/
public function __construct($name) {
$this->name = $name;
$this->savings = new Dollar(1500);
}
/**
* receive a payment
* @param Dollar $amount the amount received
* @return void
*/
public function collect($amount) {
$this->savings = $this->savings->add($amount);
}
* return player balance
* @return float
*/
public function getBalance() {
return $this->savings->getAmount();
}
}
A Monopoly and Player class has been given above, and you can now perform some tests based on the currently declared class definitions.

A test instance of MonopolyTestCase can be written like this:

class MonopolyTestCase extends UnitTestCase {
function TestGame() {
$game = new Monopoly;
$player1 = new Player(‘Jason');
$this->assertEqual(1500, $player1->getBalance());
$game->passGo($player1);
$this->assertEqual(1700, $player1->getBalance());
$game->passGo($player1);
$this->assertEqual(1900, $player1->getBalance());
}
}
If you run the MonopolyTestCase test code, there is no problem in running the code. Now some new features can be added.
Previous page12345Next pageRead the full text