CodeIgniter Forums

Full Version: What is the best way to fill an object with data from a database
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi all

What is the best way to fill an array objects with data from a database

My code
PHP Code:
class ProductsContentComposite extends AbstractContentComposite {
 
   public function addElement(InterfacePrototype $element)
 
   {
 
       $this->elements[] = $element;
 
   }

In Controller
PHP Code:
$productsComposite = new ProductsContentComposite();
/* some logic */
$results $this->product_model->getAll();
$productPrototype = new ProductContentPrototype();
/* some logic */
foreach ($results as $result)
{
$clonePrototype = clone $productPrototype;
/* some logic */
$productsComposite->addElement($clonePrototype);

Is this the right way or not?
(05-28-2017, 12:31 AM)phpforever2017 Wrote: [ -> ]Hi all

What is the best way to fill an array objects with data from a database

My code
PHP Code:
class ProductsContentComposite extends AbstractContentComposite {
 
   public function addElement(InterfacePrototype $element)
 
   {
 
       $this->elements[] = $element;
 
   }

In Controller
PHP Code:
$productsComposite = new ProductsContentComposite();
/* some logic */
$results $this->product_model->getAll();
$productPrototype = new ProductContentPrototype();
/* some logic */
foreach ($results as $result)
{
$clonePrototype = clone $productPrototype;
/* some logic */
$productsComposite->addElement($clonePrototype);

Is this the right way or not?

It might be. You haven't really told us what you are doing, but it seems like you might be overthinking it.

What are you actually trying to do? Why the need for the ProductsContentComposite class, the abstract class it extends, the InterfacePrototype class? I'm just guessing, but I'd think that whatever you are trying to do can be done in a lot less code, and without creating a bunch of OOP spaghetti.
I already found the answer to my question with the pattern Domain Model and Data Mappers. After sending a request from the controller to the model, I get a object product with all attributes, option, image, categories, costs. The client still needs to call the render method and he sees the products.
Sorry for my English