Model Best Practices
I have an application that allows users to design different product layouts (the model is called Layout). Each Layout is based on a Rack (that determines number of shelves and product slots per shelf). Each shelf is made up of one to many products. I have models for Rack, Layout and Product. When creating a Layout, each shelf within a Rack must have the products arranged on the shelf in one of several allowed orderings.
For instance, a shelf that has 7 available slots could be filled in any of the following layouts: 4/3, 3/4, 1/5/1, 1/3/2/1, 1/2/3/1 (note that 2/2/3 or 3/2/2 is specifically not allowed). So a shelf could have 4 of Product A and 3 of Product B. Or 1 of Product A, 5 of Product B and 1 of Product C - and so on.
I'm trying to store these available layouts from my Rack model with the following function:
public function productSlotLayouts() {
$layouts[1] = ['4/3', '3/4', '1/5/1', '1/3/2/1', '1/2/3/1'];
$layouts[2] = ['3/2/3', '5/3', '3/5', '4/4'];
return $layouts[$this->id];
}
The problem however, is that in the case of the form to create a new Layout, the user picks for the Rack layout from a dropdown menu - so I can't just do this:
$rack->productSlotLayouts()
I can't do that because I don't actually have an instance of Rack at that point. I thought about allowing that function to take an optional argument like this:
public function productSlotLayouts($rack_id = null) {
$layouts[1] = ['4/3', '3/4', '1/5/1', '1/3/2/1', '1/2/3/1'];
$layouts[2] = ['3/2/3', '5/3', '3/5', '4/4'];
if (!is_null($rack_id)) {
return $layouts[$rack_id];
} else {
return $layouts[$this->id];
}
}
But that doesn't feel right for a few reasons. Not to mention, I still don't have an instance of the Rack model to even be able to call that function.
Do I use a helper function? And if I do, don't I then have two places where those layouts are specified?
In another project with a similar situation, I created a helper function AND a model function. The helper function stored the actual logic while the model function simply called the helper function with the proper ID variable. But that just didn't feel right.
Any thoughts as to a better way to do this?
Please or to participate in this conversation.