Guest User

Basic_Instinct DBLA View Mapping

a guest
Sep 11th, 2021
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.12 KB | None | 0 0
  1. <?php
  2.  
  3. /* Мой первый трейт в жизни Basic_Instinct )) */
  4. trait ViewTrait
  5. {
  6.     public static function fromArray(array $data = []): self {
  7.  
  8.         foreach (get_object_vars($obj = new self) as $property => $default) {
  9.             $obj->$property = $data[$property] ?? $default;
  10.         }
  11.  
  12.         return $obj;
  13.     }
  14. }
  15.  
  16.  
  17. /* Вьюха, дто, как к не назови */
  18. class View
  19. {
  20.     use ViewTrait;
  21.  
  22.     public ?Ulid $id = null;
  23.     public ?string $name = null;
  24. }
  25.  
  26.  
  27. /* метод DBAL  */
  28. public function getName(): \Generator
  29. {
  30.     $stmt = $this->connection->createQueryBuilder()
  31.         ->select('
  32.                `data`.`id`,
  33.                `data`.`name`
  34.            ');
  35.  
  36.     $stmt->from('`table_name`', '`data`');
  37.  
  38.     $trtr = $stmt->execute();
  39.  
  40.     foreach ($trtr as $row) {
  41.         yield View::fromArray($row);
  42.     }
  43. }
  44.  
  45.  
  46. /* Контроллер, если желаете */
  47. public function index(NameQuery $nameQuery): Response
  48. {
  49.     $name = $nameQuery->getName();
  50.     foreach ($name as $item) {
  51.         dump($item);
  52.     }
  53.  
  54.     return new Response('...');
  55. }
Advertisement
Add Comment
Please, Sign In to add comment