I’m designing an application that has a general code base, but some parts of it are very specific to certain shopping carts. As the # of carts its designed to accommodate grows, the more methods I find myself adding to the main class. This is making the class rather large and unwieldy.
How can I modularize things so that each specific cart that loads the main class has its own specific methods that are only loaded if the cart make and version match?
For instance, suppose I have things setup in this manner right now:
class Thingy {
public function doStuffMagento16() {...}
public function getMoreMagento16() {...}
public function doStuffOpencart15() {...}
public function getMoreOpencart15() {...}
public function doStuffPrestashop12() {...}
public function getMorePrestashop12() {...}
public function doStuffXcart45() {...}
public function getMoreXcart45() {...}
}
How would I make it look more like this, such that methods just overload the defaults in the main class:
class Thingy {
public function doStuff() {...}
public function getMore() {...}
}
I’m really thinking I need to create child classes to do this that extend the main class and just autoload them when the main interface is called, but I want to make sure this is really the most efficient and easily maintainable option before I try that….or if I should go another direction.
This calls for the adapter pattern; you adapt specific cart interfaces to a generic interface.
Trivial example:
Then a generic cart consuming client:
Usage:
P.S.: you don’t necessarily have to implement the adapters such that you pass the original implementations to their constructors. Something like this could work as well:
Then its usage would simplify to:
You can vary on the actual implementation details, but this should give you a general idea. For instance, there’s a big chance you end up implementing a façade pattern, for some or all original carts, along with it as well, because you may want to wrap multiple method calls to one original implementation into a single method of the adapter interface.