Reputation: 93
I have a basic problem with following code:
<?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
}
}
?>
The insert method of the UserMapper expects an UserInterface object. So I create one:
<?php
$user = new User(1, "Chris");
$userMapper = new UserMapper();
$userMapper->insert($user);
?>
My problem is, that the user's id is an auto-increment value that is coming from the database after inserting the object. But the object's constructor forces me to define an id because the object would not be complete without an id. How to solve that general problem?
To pass the id as a second parameter to the constructor woth a default value is not an option, because in my understanding the object would be incomplete without having an id.
Thanks for your help.
Upvotes: 1
Views: 805
Reputation: 963
You can pass null
:
$user = new User(null, "Chris");
$_id is not checked for a valid integer and with null
you know that this model has no valid ID yet.
Upvotes: 1