Mandate array key in method parameter

So I have a method inside my class which will create a new prospect, which has a $fields parameter that users can pass in the fields.

So let’s say that I have the following format:

$new_pardot = new FH_Pardot();
$new_pardot->create_prospect();

The create_prospect() method has $fields param that needs a array passed into it, so an example would be like this:

$new_pardot->create_prospect([
    'email' => $posted_data['email'], // Make key mandatory or throw error on method.
    'firstName' => $posted_data['first-name'],
    'lastName' => $posted_data['last-name'],
]);

Is there a way to make the email key in the $fields mandatory? Users will need to pass in the email key, but then they have the option to pass in additional keys as shown above.

Here is the example method:

public function create_prospect(array $fields)
{
    // Other logic in here.
}

>Solution :

You can take one of many approaches to where the validation takes place. The two obvious ways are doing the validation within the create_prospect function, or doing the validation before/outside calling create_prospect.

The traditional approach is to do your validation before trying to create the entity. It makes collecting and displaying validation errors easier than throwing validation messages from various places.

within

public function create_prospect(array $fields)
{
    if (!isset($fields['email']) {
        throw new ValidationException('Please provide an email');     
    }

    ... carry on with your work
}

Before/Outside

$fields = [
    'email' => $posted_data['email'],
    'firstName' => $posted_data['first-name'],
    'lastName' => $posted_data['last-name'],
];

if (!isset($fields['email']) {
    throw new ValidationException('Please provide an email');     
}

$new_pardot = new FH_Pardot();
$new_pardot->create_prospect($fields);

Leave a Reply