Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class Model
- {
- protected $db;
- function __construct($db)
- {
- $this->db = $db;
- }
- }
- class Player extends Model
- {
- private $id;
- function __construct($id, $db)
- {
- parent::__construct($db);
- $this->id = $id;
- }
- }
- class Item extends Model
- {
- private $id;
- private $data = array();
- function __construct($id, $db)
- {
- parent::__construct($db);
- $this->id = $id;
- }
- }
- class PlayerFactory
- {
- private $db;
- function create($id)
- {
- return new Player($id, $this->db);
- }
- }
- class ItemFactory
- {
- private $db;
- function create($id)
- {
- return new Item($id, $this->db);
- }
- }
- class Relation
- {
- private $classes = array();
- protected $db;
- function __construct($db)
- {
- $this->db = $db;
- }
- function __set($k, $v)
- {
- $this->classes[$k] = $v;
- }
- function __get($k)
- {
- return $this->classes[$k];
- }
- }
- class RelationPlayerItem extends Service
- {
- function buyItem()
- {
- if ($this->player->money < $item->price) {
- throw new Exception("not enough money");
- }
- $this->db->beginTransaction();
- $this->player->subtractMoney();
- $this->item->changeOwner($this->player);
- $this->db->commit();
- }
- }
- class Presenter
- {
- // obě proměnné umí Nette automaticky vytvořit
- private $playerFactory;
- private $itemFactory;
- protected $player;
- // startup se zavolá jako první a slouží pro inicializaci vlastnostní
- public function startup()
- {
- // $this->user->id je v Nette ID přihlášeného uživatele
- $this->player = $this->playerFactory->create($this->user->id);
- }
- private function createRelation($name)
- {
- $class = "Relation" . ucFirst($name);
- return new $class($this->context->getService("db"));
- }
- function handleBuyItem($id)
- {
- $relation = $this->createRelation("playerItem");
- $relation->player = $this->player;
- $relation->item = $this->itemFactory->create($id);
- try {
- $relation->buyItem();
- } catch (Exception $e) {
- $this->flashMessage($e->getMessage());
- $this->redirect("default");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement