Reputation: 515
I am creating my first bigger project using doctrine, which by now, I love and hate !
The thing that I don't get about it is this: Why is it totally OK for an entity to be in an invalid state ?
I mean, of course, you can use a validator to check if the entity is valid ( e.g before persistence ), but wouldn't it be so much better if it was just not possible to even be in an invalid state ?
class Author
{
/**
* @Assert\NotBlank
*/
public $name;
}
IMHO it should not be possible to do:
$author = new Author();
as this results in an entity that is not valid. Yes, you could do this:
class Author
{
/**
* @Assert\NotBlank
* @var string
*/
public $name;
public function __construct( string $name )
{
$this->setName($name);
}
/**
* @param string $name
* @throws \Exception
*/
public function setName(string $name)
{
if($name ==''){
throw new \Exception('name must be set');
}
$this->name = $name;
}
}
But then, what is the assertion good for, right ?
So, am I missing something here, or is this just the way it is ?
Upvotes: 0
Views: 290
Reputation: 3123
Oh god. I've talked about it. Too bad it was in french!
Nevermind, I strongly agree with you and see nothing wrong in throwing exceptions if your input data is not good in the entity.
Besides, to me Doctrine has no limitation on this kind of usage. Actually anemic models were documented in the official Doctrine documentation. So yes, it's not obvious that Doctrine support non-anemic model. But thanks to awesome contributors, times change.
I'd like to "resolve" your problem but I don't see any. I hope I gave what you expected.
Upvotes: 1