How to solve Denependency one class to another correctly

Notice: This thread is very old.
opravil.jan
Member | 4
+
0
-

How to solve this problem correctly. I have class customer. Each customer has items and i want to load items from database when i need them not when i create instance of Customer from database data.

<script>
class Customer {
	private $idCustomer;
    private $name;

	private $serviceItem;

	public function setServiceItem($serviceItem){
		$this->serviceItem = $serviceItem;
	}

	public function getItems(){
		$this->serviceItem->getByIdCustomer($this->idCustomer);
	}
}
</script>

What is the correct way to create Factory which give me instance of Customer with set service serviceItem.

I thought i use something like the code below and Configuration in config.neon. But I didn't find out how. Is it possible or I'm out. Thank you

<script>
class Factory extends \Nette\Object {
    //put your code here

    private static $serviceItem;

    public static function setServiceItem($serviceItem){
		self::serviceItem = $serviceItem
    }

    public static function createCustomer(){
       $customer = new Customer();
	   $customer->setSeriviceItem(self::$serviceItem);
       return $customer;
    }
}
</script>

Last edited by opravil.jan (2016-03-03 20:00)

CZechBoY
Member | 3608
+
0
-

Make customer as you retrieve it from database. Then if you need dependent data then make another query and save the result.

Make factory for the Customer class then…

class Customer
{
    protected $modelForItems;

    protected $id;
    protected $name;
    protected $items;

    function __construct($customerRow, ModelForItems $modelForItems)
    {
        $this->id =...
        $this->modelForItems = $modelForItems;
    }
    function getItems()
    {
        if ($this->items === null) {
          $this->modelForItems->getItemsByCustomer($this->id);
        }

        return $this->items;
    }
}

Last edited by CZechBoY (2016-03-03 17:54)

opravil.jan
Member | 4
+
0
-

It's clear to me, but how you create the instance of Customer with injection of ModelForItems when the class does not know the ModelForItems. For this situation i wanted the Factory.

<script>

class Test {

	public function create(){
		return new Customer();
	}
}

</script>
CZechBoY
Member | 3608
+
0
-

Yes, you should create the Customer through some CustomerFactory which creates desired object.

Then another problem is where you get factory :D

We are in the same situation now. My idea is that low level model should has factory to create that Customer object when datas are fetched.
So each model class should know how to create its entity.

Are we talking about orm, right?

opravil.jan
Member | 4
+
0
-

I know that ORM solve the problem, but without ORM I'm not sure how to do it right using DI and nette.