依赖注入和传递参数

时间:2014-06-20 15:33:07

标签: php dependency-injection

我对PHP中的依赖注入有疑问。

我目前有3个班级:

Staff.php

<?php
class Staff
{
    public function name($id)
    {
        return 'returning staff with 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()
    {
        return $this->staff;
    }

    public function projects()
    {
        return $this->projects;
    }
}

这些类的实例化如下:

    $staff    = new Staff;
    $projects = new Projects;
    $app      = new ProjectsManager($staff, $projects);

    echo $app->staff()->name(5);

以上是有效的,但我想做的是这样的事情:

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

如何处理依赖关系以实现此目的?

2 个答案:

答案 0 :(得分:0)

$employee = $app->staff()->name(5);
//$app is the ProjectsManager
//$app->staff() returns it's Staff object
//staff()->name(5) Invokes the Staff object's name function
//Returns 'Returning staff with id 5'    

echo $employee->name();
echo $employee->position();
echo $employee->email();

为避免混淆,我还建议使用get(例如$app->getStaff()->getFromId(#)

为其中一些函数添加前缀

另外,请务必将staff()->name(#)修改为实际上返回一个对象,而不是字符串。

答案 1 :(得分:0)

您只需在Staff类中添加set函数并在ProjectsManager中调用它:

<?php

class Staff 
{
    private $id = null;

    public function name()
    {
        return 'returning staff with 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);
        return $this->staff;
    }

    public function projects($val = null)
    {
        return $this->projects;
    }
}


$staff    = new Staff;
$projects = new Projects;
$app      = new ProjectsManager($staff, $projects);

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