【问题标题】:PHP ORM how to set id in constructorPHP ORM如何在构造函数中设置id
【发布时间】:2013-03-30 10:51:07
【问题描述】:

我对以下代码有一个基本问题:

<?php

interface UserInterface
{
    public function getId();
    public function getName();
}

class User implements UserInterface
{
    private $_id;
    private $_name;

    public function __construct($id, $name)
    {
        $this->_id = $id;
        $this->_name = $name;
    }

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

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

class UserMapper
{
    public function insert(UserInterface $user)
    {
        ... insertion code
    }
}

?>

UserMapper 的插入方法需要一个 UserInterface 对象。所以我创建了一个:

<?php

$user = new User(1, "Chris");
$userMapper = new UserMapper();
$userMapper->insert($user);

?>

我的问题是,用户的 id 是插入对象后来自数据库的自动增量值。但是对象的构造函数迫使我定义一个 id,因为没有 id 的对象是不完整的。如何解决这个普遍问题?

将 id 作为第二个参数传递给构造函数,默认值不是一个选项,因为在我的理解中,如果没有 id,对象将是不完整的。

感谢您的帮助。

【问题讨论】:

    标签: php object orm model constructor


    【解决方案1】:

    你可以传null:

    $user = new User(null, "Chris");
    

    $_id 没有检查一个有效的整数,null 你知道这个模型还没有有效的 ID。

    【讨论】:

      猜你喜欢
      • 2010-10-11
      • 2010-10-09
      • 1970-01-01
      • 2016-09-04
      • 2013-08-17
      • 1970-01-01
      • 1970-01-01
      • 2017-05-15
      • 1970-01-01
      相关资源
      最近更新 更多