Tuesday, 15 July 2014

php - Dependency Injection and passing arguments -



php - Dependency Injection and passing arguments -

i have question dependency injection in php.

i have 3 classes:

staff.php

<?php class staff { public function name($id) { homecoming 'returning staff id ' . $id; } }

projects.php

<?php class projects { ..... projects related functions }

projectsmanager.php

<?php class projectsmanager { private $staff = null; private $projects = null; public function __construct(staff $staff, projects $projects) { $this->staff = $staff; $this->projects = $projects; } public function staff() { homecoming $this->staff; } public function projects() { homecoming $this->projects; } }

those classes instantiated this:

$staff = new staff; $projects = new projects; $app = new projectsmanager($staff, $projects); echo $app->staff()->name(5);

the above working, this:

$employee = $app->staff(5); echo $employee->name(); echo $employee->position(); echo $employee->email();

how can handle dependency accomplish this?

you can add together set function in staff class , phone call in projectsmanager:

<?php class staff { private $id = null; public function name() { homecoming 'returning staff id ' . $this->id; } public function setid($id) { $this->id = $id; } } class projects { //..... projects related functions } class projectsmanager { private $staff = null; private $projects = null; public function __construct(staff $staff, projects $projects) { $this->staff = $staff; $this->projects = $projects; } public function staff($id = null) { $this->staff->setid($id); homecoming $this->staff; } public function projects($val = null) { homecoming $this->projects; } } $staff = new staff; $projects = new projects; $app = new projectsmanager($staff, $projects); $employee = $app->staff(5); echo $employee->name();

php dependency-injection

No comments:

Post a Comment