When using the same variables throughout a controller, is it best to set session variables, or repeatedly call the same helper functions? For example, say I have a Ball object with a property of hexColor:
$ball->hexColor;
The Ball table in the database has the following structure:
id | name | hexColor
Now, say there is a lighter version and a darker version of this hex color, and that I don't want to store in the table, to save memory and avoid redundant data:
NOT this:
id | name | hexColor | lightHexColor | darkHexColor
I have a function in the model that lightens or darkens the color:
//second parameter: 1 = darken, 2 = lighten
public static function changeColorBrightness(String $hexColor, int $darkenOrLighten)
{
/* Some code */
return $alteredColor;
}
In my controller, do I call this helper function only twice, once for darken and once for lighten, and store them in a session:
public function someFunction($ballId)
{
$ball = Ball::find($ballId);
$darkColor = Ball::changeColorBrightness($ball->hexColor, 1);
$lightColor = Ball::changeColorBrightness($ball->hexColor, 2);
session()->set('darkColor', $darkColor);
session()->set('lightColor', $lightColor);
}
Or do I go the less efficient route of calling the helper function in every method where I need the altered colors:
public function methodCalledFromRoute_1($ballId)
{
$ball = Ball::get($ballId);
$darkColor = self::changeColorBrightness($ball->hexColor, 1);
$lightColor = self::changeColorBrightness($ball->hexColor, 2);
/* More code */
}
public function methodCalledFromRoute_2($ballId)
{
$ball = Ball::get($ballId);
$darkColor = self::changeColorBrightness($ball->hexColor, 1);
$lightColor = self::changeColorBrightness($ball->hexColor, 2);
/* More code */
}
etc.
I get the feeling that the first method, setting session vars once, is not considered the best coding practice, but I'm not sure why not. What do you guys think, what is the better method and why?
Aucun commentaire:
Enregistrer un commentaire