Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading