Friday 15 March 2013

php - Many dependencies in service -



php - Many dependencies in service -

i have problem dependencies in application in service layer.

i have next class:

<?php class userservice{ private $userrepository; private $vocationservice; private $roleservice; public function __construct(userrepository $userrepository, vocationservice $vocationservice, roleservice $roleservice) { $this->userrepository = $userrepository; $this->vocationservice = $vocationservice; $this->roleservice = $roleservice; } }

there 3 dependencies i'm injecting. assume, want add together next dependency, example: nextservice. constructor grow again.

what if wanted pass more dependencies within constructor ?

maybe should solve problem passing ioc container , desirable class? here example:

<?php class userservice{ private $userrepository; private $vocationservice; private $roleservice; public function __construct(containerinterface $container) { $this->userrepository = $container->get('userrepo'); $this->vocationservice = $container->get('vocservice'); $this->roleservice = $container->get('roleservice'); } }

but userservice class depends on ioc container i'm injecting.

how solve problem next practices?

regards, adam

injecting container dependency service considered bad practice multiple reasons. think main point here figure out why , seek understand problem leads think "injecting container" possible solution , how solve problem.

in object oriented programming, it's of import define relations between objects. when you're looking @ given object dependencies, should intuitive understand how object behaves , other objects relies on looking @ public api.

it's bad thought allow object rely on a dependency resolver, in illustration shared object can't live without container provided di component. if want utilize object elsewhere, in application uses framework example, you'll have rethink way object dependencies , refactor it.

the main problem here understand why service needs these dependencies,

in object-oriented programming, single responsibility principle states every context (class, function, variable, etc.) should define single responsibility, , responsibility should exclusively encapsulated context. services should narrowly aligned responsibility. source: wikipedia

based on definition, think should split userservice services handle only one responsability each.

a service fetch users , save them dababase example another service manages roles example ... , on

php symfony2 dependency-injection inversion-of-control symfony-2.5

No comments:

Post a Comment