mercredi 17 juin 2020

PHP Status class : pattern or anti-pattern

I want to abstract some code which does a bunch of checks and returns a boolean - since I am using the business logic in several places. But I also want to get back the reason why, if it was returned FALSE. I have this in mind...

class ContactCanBeContactedCheck
{
    public $not_contactable_reason;

    const REASON_DECEASED = 0;
    const REASON_OPTED_OUT = 1;

    public function __invoke(Contact $contact)
    {
        // Deceased
        if ($contact->is_deceased) {
            $this->not_contactable_reason = static::REASON_DECEASED;
            return FALSE;
        }

        // Opted out
        if ($contact->opt_out) {
            $this->not_contactable_reason = static::REASON_OPTED_OUT;
            return FALSE;
        }

        return TRUE;
    }
}

I would then call the code like so...

$contact_can_be_contacted_check = new ContactCanBeContactedCheck;
$contact_can_be_contacted_check($contact);
$reason = $contact_can_be_contacted_check->not_contactable_reason;

I think this must be a well-trodden path. Is this a suitable approach or is there another more widely accepted?

Aucun commentaire:

Enregistrer un commentaire