1

I know this could be interpreted as a minor or a newbie question but I would like to improve my code. So, in a best coding practice perspective how to call/use plugin parameters? My two code examples will do the same, but which is the proper way of doing it?

$my_parameter = $this->params->get('my_parameter', 'default_value');

if ($my_parameter) 
{
    ...
    $xpto = $my_parameter;
    ...
}

or

if ($this->params->get('my_parameter', 'default_value')) 
{
    ...
    $xpto = $this->params->get('my_parameter', 'default_value');
    ...
}
6

Technically in PHP you can also do this:

if ($my_parameter = $this->params->get('my_parameter', 'default_value')) 
{
    ...
    $xpto = $my_parameter;
    ...
}

This assigns the variable and then checks that the variable is 'true', which in PHP means that it isn't null, false, '', or 0. So depending on your default value, the if statement could be unnecessary.

My recommendation for any code style question is to avoid duplication as much as possible. I don't like the second method, because you've duplicated the default value. If you ever decide to change that default value, you have to remember to update it in two places. (And even if that sounds silly today, you will likely forget to update both places at some time, so save yourself the trouble and only define a default value once!)

The first method allows you to define that value once, in that spot. (You could also do things like add a class constant with the default value and then reference that to avoid duplicating the value.)

On whether you should assign it to a variable or not, the main question is do you use the variable again? If you just need to check that it is true, put the call to get the value in the if statement and don't assign it to a variable. If you want to check that the param is one of several options, maybe try a switch:

switch($this->params->get('my_parameter', 'default_value')) {
    case 'option_a':
         ...
         break;
    case 'option_b':
         ...
         break;
    default:
         ...
}

Finally, if you are actually doing things with that value (either math or printing it to something), store it in a variable!

0

Just to clarify, your if statement is only checking is the parameter has a value which it will do if a default value has been set. It's not checking to see if the parameter has a specific value.

Both code snippets you've provided are doing exactly the same thing, so you can use either one.

Personally, I always define my parameters as a variable like you've done in the first example. Normally (in JS for example) I would only do this if I'm using it more than once however I tend to define each parameter as a variable no matter how many times it's being used to keep everything consistent.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.