Hi
I’ve searched through the topics, but hadn’t found an answer to that.
I’ve been struggling with my domian model for the last few days, trying different patterns. I’ve kinda settled on the DataMapper and friends, but one thing still buffles me - validation.
Let me explain it with some code.
class UserMapper {
function __construct (DB $db) {
$this->db = $db;
}
function find($id) {
// find user in the db
$user = new User;
$user->id = $result->id;
[...]
return $user;
}
public save(User $user) {
// save user
}
}
class User {
public $id,
$name;
}
In my controller I would use something like
class UserController {
function __construct(UserMapper $mapper) {
$this->mapper = $mapper;
}
function action() {
$user = $this->mapper->find(1);
$user->name = 'John';
$this->mapper->save($user);
}
}
There are different approches to validation, some people do not allow their domain objects to become invalid, some people allow and validate before saveing etc. Personally I find the latter approach more practical.
I liked the rails approach to validation - definig rules in the Domain object, but as rails uses AR, I found it a bit of a hack to use in my case.
I could create is_valid method in User class, but this way I would be able to validate only the simple cases like enforce variable type etc.
But what about enforcing uniqueness? I would have to get access to my mapper, which smells.
I also don’t like putting validation logic in my Mapper, somehow it doesn’t feel right. Maybe I should move it to a Validation class like UserValidation and make it a dependency on my Mapper? Or inject the UserValdiation object from a Controller…
But then again, should the UserValidation make queries (like checking unique values), or ask Mapper for db stuff?
I’m totally confused. I’ve read tons of material recently, mostly from Java world, but I feel even more lost than before…
Thanks!