Monday 15 June 2015

php - Dependency Injection / LoD -



php - Dependency Injection / LoD -

i understand basic principles of dependency injection advice on how handle classes instantiated within other classes methods; go against dependency injection pattern?

moreover, write object (class) db (mongo in object form) , don't want bloated other dependencies.

to improve explain mean here example:

lets have user class gets injected server class -

class user{ public $user_id public $user_name; public function __construct(server $server){ $this->server = $server; } public function delete(){ //...delete user code // send mail service user $mailer = new mailer($this->server); $mailer->sendmail(); } }

so 2 things this

this means user class gets bloated contains server class also does break law of demeter? user class doesn't need server class other pass onto mailer class..

i understand way around inject mailer class delete function when called outside controller, meaning user class never has injected server class:

$server = new server(); $mailer = new mailer($server); $user = new user(); $user->delete($mailer); class user{ public $user_id public $user_name; public function __construct(){ // other code } public function delete(mailer $mailer){ //...delete user code // send mail service user $mailer->sendmail(); } }

but certainly means need know every class needed methods within class, if nesting becomes few levels deep certainly hard maintain track of.

also happens if user->delete private method? wouldn't able phone call outside controller pass in mailer object in first place.

so question what's best way of going this?

for me smell take dependency on object, can build different object.

instead take dependency on object want build instead. in case pass mailer users constructor, don't need create mailer , don't need care server.

here user has dependency on mailer (to mailing) , thing should injected.

you objects should creating new instances of leaf objects/data holders/dtos. provides functionality (ie services) should injected objects need create utilize of functionality.

edit

i don't php think user class should more this:

class user{ public $user_id public $user_name; public function __construct(mailer $mailer){ $this->mailer = $mailer; } public function delete(){ //...delete user code // send mail service user $this->mailer->sendmail(); } }

as injecting via constructor vs passing in method, comes downwards whether reasonable expect user of user provider mailer when want delete user. me doesn't sound is, pass through constructor.

php class object dependency-injection

No comments:

Post a Comment