I have a class called Assembly that hides the implementation of the underlying products. ProductA may have one set of getters; ProductB may have another.
While PHP is pretty forgiving, and if I don't mix products and getters, my code will work, but there is no protection offered when I messed up and populated Assembly with ProductA , but then use the getter from ProductB .
In addition, my IDE knows methods from any class, so there is no automatic completion suggested when I work inside Assembly with getters from Product .
I want to get more bulletproof code where Assembly knows or knows which Product subtype it currently hosts. Is there any way to do this?
Example below
class Assembly { private $product; public function setProduct(Product $product) { $this->product = $product; } public function getA() { return $this->product->getA(); } public function getB() { return $this->product->getB(); } } class Product { } class ProductA extends Product { public function getA() { return "A"; } } class ProductB extends Product { public function getB() { return "B"; } }
Interface Suggestion
interface CompositeProductInterface { public function getA(); public function getB(); }
This gives me autocomplete in my IDE, which is nice, but it doesn't solve my other problems. Also, I'm a little creepy in combining things into a single “composite” product ... It seems to work. In my particular case, I have two very similar products that differ in some minutes in such things as several properties.
Real world example
Both product models A and B have a technical drawing listing variables for defining different product sizes. The named sizes are the same for both products. For example, M1 on product A means the same physical size of product B. However, product A has functions not present on product B, and vice versa.
If this still seems too hypothetical, the actual dimensions of the actual drawing are indicated as B2 and B3. These sizes (B2, B3) are not available on another product model. I want to be able to use the assembly construct to list the variables in the drawing, including M1, B2, B3, etc. I could do it with
print $assembly->getM1(); //works for both products print $assembly->getB2(); //works for one product only print $assembly->getB3(); //same as above
goal
The goal is to have one class (assembly) responsible for listing the named measurement variables, and each product knows only itself. So
- The assembly says: "I know everything about the named variables that I want to list (M1, B2, B3), regardless of the product model."
- Product A says: “I only know what I contained. I use the named dimension A. I don’t know what B is and I don’t care about
- Product B says: "I only know B" ...