Zf2实体加入

时间:2014-10-19 17:15:56

标签: php zend-framework join zend-framework2 entity

你能帮帮我吗?我无法理解如何加入2个或更多表,每个表都有实体。是否可以像在学说中一样使用?我不想使用学说。

如何加入实体并在视图中使用?

class User
{
    protected $id;
    protected $email;
    protected $password;

    public function getId()
    {
        return $this->id;
    }
    public function setId($value)
    {
        $this->id = $value;
    }
    public function setEmail($value)
    {
        $this->email = $value;
    }
    public function getEmail()
    {
        return $this->email;
    }
    public function setPassword($value)
    {
        $this->password = $value;
    }
    public function getPassword()
    {
        return $this->password;
    }
}

class Info
{
    protected $id;
    protected $lastname;
    protected $firstname;

    public function getId()
    {
        return $this->id;
    }
    public function setId($value)
    {
        $this->id = $value;
    }
    public function setLastname($value)
    {
        $this->lastname = $value;
    }
    public function getLastname()
    {
        return $this->lastname;
    }
    public function setFirstname($value)
    {
        $this->firstname = $value;
    }
    public function getFirstname()
    {
        return $this->firstname;
    }
}

1 个答案:

答案 0 :(得分:1)

class User
{
    ...
    protected $info;

    ...
    public function readInfo()
    {
        return $this->info;
    }

    public function writeInfo(Info $entity)
    {
        $this->info = $entity;
        return $this;
    }
}

class ModelUser
{
    public function get()
    {
        $query = 'query for user with info';
        $adapter = Zend\Db\TableGateway\Feature\GlobalAdapterFeature::getStaticAdapter();
        $result = $adapter->query($query, \Zend\Db\Adapter\Adapter::QUERY_MODE_EXECUTE);

        /* Or use tableGateway */ 

        /* Class methods hydrator */
        $hydrator = new \Zend\Stdlib\Hydrator\ClassMethods;
        /* Hydrate User entity from result */
        $userEntity = $hydrator->hydrate($result->toArray(), new User);
        /* Hydrate Info entity from result */
        $infoEntity = $hydrator->hydrate($result->toArray(), new Info);
        /* Write Info entity to User entity */
        $userEntity->writeInfo($infoEntity);

        return $userEntity;
    }
}

class UserController
{
    public function indexAction()
    {
        $model = new ModelUser();
        $userEntity = $model->get();

        return array(
            'user' => $userEntity
        );
    }
 }