I'm playing around with trying to do things in a better way, and in a class I have for sending emails, I have the concept of a recipient. This gets passed into my other classes essentially as a struct that is a little more descriptive than an associative array.
I'd like to know if the Recipient is going to be valid to pass to the rest of my code, and hence want a way to determine if the email address has any basic errors in it. (I'm aware that validating emails can only be done by sending them an email, for the purposes of this, just ignore this fact!)
Anyway, I have this class that looks like this:
class Recipient
{
public $email_address, $name;
public function __construct($email_address, $name) {
$this->email_address = $email_address;
$this->name = $name;
}
function emailIsValid() {
return filter_var($this->email_address, FILTER_VALIDATE_EMAIL);
}
public function isValid() {
return ($this->emailIsValid() && $this->name != '');
}
}
And I'm calling it like:
$recipient = new Recipient('[email protected]', 'Example Name');
then, later when I'm about to send an email to something I can run:
if ($recipient->isValid()) {
// add to the list of recipients
}
I'm interested on all and any feedback on this - I'm not that confident that this is a 'good' way to do things because:
- This class doesn't really do anything, and is really a pretty struct
- The validation isn't specific to this place, I may want to check emails in other places
- Should the validation happen in the constructor? Should it be a separate class? What would that look like?
- Should there be an
interface
for every class? Would that live at the top of this file? - Should I throw exceptions when it's not valid? Should they be an object as well? How?
Thanks a lot - I'd appreciate any comments, even if it's just a 'read this tutorial' type comment.