php - Why is it wrong to tie a depencency into a Business Object? -
in general, has been told me dependencies should injected. concerns should separated. control should inverted. why?
for example, if use separation of concerns don't inversion of control. why wrong? i.e. see code below discussion..
class businessfunctionality { public $motor; function dostuff() { //i.e. @ creation time not injecting data //into motor. create empty motor set data later $this->motor = new motor(); //motor loads data $this->motor->loadmotor(); } } class motor { public $motordata; function loadmotor() { $motordata = new motordata(); //motordata class created //separate concerns of motor functionality //from database details //we load data acquired motordata, motor $this->motordata = $motordata->loadmotor(); } } class motordata { function loadmotor() { //mock database $type = "industrial";//$db->query("select... .. "); return $type; } } //invocation $business = new businessfunctionality(); $business->dostuff(); print "motor type " . $business->motor->motordata;
question: problems make approach above prone issues?
datamapper pattern
for comparison purposes, more advocated way ios if use dependency injection , inversion of control , separation of concerns, have implemented datamapper
pattern this:
//business object class mymotor { private $data; function __construct(motordatatype $data) { $this->data = $data; } function gettype() { return $this->data->gettype(); } } //data mapper object class mymotormapper { function getmotorwithdata() { //get data. i.e whatever source $data = (new databasemock())->getdata(); //inject data object $motor = new mymotor($data); //return motor caller return $motor; } } class motordatatype { private $motortype; function gettype() { return $this->motortype; } function setmotortype($type) { $this->motortype = $type; } } //database object class databasemock { function getdata() { $data = new motordatatype(); $data->setmotortype("industrial"); return $data; } } //invocation $motor = (new mymotormapper())->getmotorwithdata(); print "motor type " . $motor->gettype();
not entirely sure way turned out, demonstrates principles trying show (di, soc, iofc)
Comments
Post a Comment