Romanovich095

Classes usage example

Sep 16th, 2020 (edited)
782
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2.  
  3. /**
  4.  * Class Master
  5.  * @property integer id
  6.  * @property string name
  7.  * @property string city;
  8.  * @property bool delivery
  9.  * @property array services
  10.  */
  11. class Master
  12. {
  13.     private $id;
  14.     private $name;
  15.     private $city;
  16.     private $delivery = false;
  17.     private $services = [];
  18.  
  19.     public function __construct(int $id, string $name, string $city, bool $delivery = false)
  20.     {
  21.         $this->id = $id;
  22.         $this->name = $name;
  23.         $this->city = $city;
  24.         $this->delivery = $delivery;
  25.     }
  26.  
  27.     public function getId(): int
  28.     {
  29.         return $this->id;
  30.     }
  31.  
  32.     public function setServices(array $services = [])
  33.     {
  34.         $this->services = $services;
  35.     }
  36.  
  37.     public function getServices(): array
  38.     {
  39.         return $this->services;
  40.     }
  41.  
  42.     public function formatServices(): array
  43.     {
  44.         return array_map(function ($service) {
  45.             return \sprintf(
  46.                 '%s - %s - %d',
  47.                 $service['title'],
  48.                 $this->name,
  49.                 $service['price']
  50.             );
  51.         }, $this->getServices());
  52.     }
  53. }
  54.  
  55. $equalsRow = str_repeat('=', 10);
  56.  
  57. $masters = [
  58.     new Master(2, 'Nick', 'Moscow', true),
  59.     new Master(10, 'Cheburashka', 'Chelyabinsk', false),
  60. ];
  61.  
  62. $services = [
  63.     ['master_id' => 2, 'title' => 'Concrete', 'price' => 200],
  64.     ['master_id' => 2, 'title' => 'Tile', 'price' => 80],
  65.     ['master_id' => 10, 'title' => 'Square', 'price' => 799],
  66. ];
  67.  
  68. array_map(function (Master $master) use ($services) {
  69.     $master->setServices(
  70.         array_filter(
  71.             $services,
  72.             function ($service) use ($master) {
  73.                 return $service['master_id'] === $master->getId();
  74.             }
  75.         )
  76.     );
  77. }, $masters);
  78.  
  79. echo \sprintf('%s %s %s' . PHP_EOL, $equalsRow, 'Товары', $equalsRow);
  80.  
  81. array_map(function (Master $master) {
  82.     array_map(function ($service) {
  83.         echo \sprintf("%s" . PHP_EOL, $service);
  84.     }, $master->formatServices());
  85. }, $masters);
RAW Paste Data