How can I work with collections of objects? Or rather, does an object return a collection of similar objects?

I think I get the OOP paradigm at its basic level, but it's hard for me to figure out how to look up records in the database correctly. I suspect this is because I really don't get OOP, as far as I think I'm doing ...

The application I'm trying to write is a shopping cart because it has a lot of good candidates for objects. The object I will work with is the product (yes, this is very primitive).

<?php
    class Product
    {
        public $id = 0;
        public $name = '';
        public $price = 0;

        function __construct($id)
        {
            // if $id exists try to retrieve
            // a product with $id
            // else create a new product
            // and set $this->id
        }
    }

    $product = new Product();
    echo $product->name;
?>

Simple enough. But now I want to find several products (for the search results page), and I'm not sure how to handle this.

, , SQL-, . . .

, , . , , , , . , , .

? - ?

+3
4

, ( , ;)) , .

+2

- . , , (Product) ( , ProductGateway ProductFinder). , , . , .

:

class ProductGateway {
  function getProductById($id) {
    $result = $this->db->query("select * from products where id = ?", $id);
    return new Product($result->next());
  }
  function save($product) {
    if ($product->getId()) {
      return $this->update($product);
    } else {
      return $this->insert($product);
    }
  }
  ...
}

, , . , .

+2

, - , , ( ) .

ProductFinder, , - , - .

, ProductFinder ( ), .. , . ProductFinder , ProductKeeper ProductHome.

, , "" , persistence. , php, .

0

. Zend_Db , Table Gateway/Row Gateway, . TableGateway . .

If you are executing a query for many rows, a separate class representing the table (or even a “virtual” table in the case of some complex join) is the cleanest way to keep the problems of this table and separate rows separate.

0
source

Source: https://habr.com/ru/post/1714682/