For me, Employee to have dependency on ContactInformation
means that you expect to have ContactInformation
already set with phones, etc. and then passed to employee, i.e.:
$contanctInfo = new ContactInformation();
$contanctInfo->setPhone(820);
$employee1 = new Employee($contanctInfo);
echo $employee1->getContanctInformation()->getPhone(); // 820
However, that means you would need to make as much ContactInformation objects, as Employee objects, before instantiating each Employee, because:
$contanctInfo = new ContactInformation();
$contanctInfo->setPhone(820);
$employee1 = new Employee($contanctInfo);
$employee2 = new Employee($contanctInfo);
$employee1->getContactInformation()->setPhone(123);
$employee2->getContactInformation()->setPhone(666);
echo $employee1->getContactInformation()->getPhone();
echo $employee2->getContactInformation()->getPhone();
Turns into:
666
666
Because you are changing one and the same object.
In your case, you are instantiating ContactInformation
at the same time, when you are instantiating Employee
when makes the dependency a bit useless:
$employee1 = new Employee(new ContactInformation());
$employee2 = new Employee(new ContactInformation());
$employee1->getContactInformation()->setPhone(123);
$employee2->getContactInformation()->setPhone(666);
echo $employee1->getContactInformation()->getPhone();
echo $employee2->getContactInformation()->getPhone();
Results into:
123
666
So, if you don't want to make changes on the dependent object before inject it to another object, you don't need a dependency at all. Even more, in real world ContanctInformation
is bind to an Employee
, not the opposite.
I would make it this way:
class Employee {
private $_contactInformation;
public function __construct() {
$this->_contactInformation = new ContactInformation($this);
}
/**
* @return ContactInformation
*/
public function getContactInformation() {
return $this->_contactInformation;
}
}
class ContactInformation {
private $_employee;
private $email; // Required
private $cellPhone; // Required
private $phone; // Optional
private $address; // Optional
public function __construct(Employee $employee) {
$this->_employee = $employee;
}
public function setPhone($phone) {
$this->phone = $phone;
}
public function getPhone() {
return $this->phone;
}
}
$employee1 = new Employee();
$employee2 = new Employee();
$employee1->getContactInformation()->setPhone(123);
$employee2->getContanctInformation()->setPhone(666);
echo $employee1->getContactInformation()->getPhone();
echo $employee2->getContactInformation()->getPhone();
On the other hand, if Employee has some identificator, so the ContanctInfo
retrieves info based on the ID, you can make the injection the way you want it.