This is a common question to those who start working with Object Orientation. And, to make matters worse, many people try to explain, but it ends up complicating the explanation so much that the amendment ends up worse than the sonnet.
When in doubt about when to extend a class, use an interface (extra credit) or inject another coming from an object, you should ask yourself if your object is a certain thing, if he can be a certain such thing (besides himself) or he just need of a certain thing to work.
If you answer that an object is another thing, you apply an inheritance.
If you answer that your object can be something other than itself, implement an interface. Even empty, they serve as types, which is great for polymorphism.
If you answer that your object just need from one another, instill it as dependency.
In your particular case, Marketplace is not an object Curl, but he can be, then you should have an interface.
I would suggest, however, something more subjective, because the data can come from anywhere, whether local, from a database, or remote. And if remote, you can use Curl or Stream Sockets:
interface OffersDataAccess {
public function getOffers();
}
class Marketplace implements OffersDataAccess {
public function getOffers() {}
}
And whoever uses that class gets one Offersdataaccess which may be a Marketplace as can also be a Catalog (Catalog of Offers), a Commercialbreak (commercial break) or even a Outdoorannouncement (billboard):
class Catalog implements OffersDataAccess {
public function getOffers() {}
}
class CommercialBreak implements OffersDataAccess {
public function getOffers() {}
}
class OffersController {
public function listOffers( OffersDataAccess $offers ) {
return $offers -> getOffers();
}
}
class OutdoorAnnouncement {
public function listOffers( OffersDataAccess $offers ) {
return $offers -> getOffers();
}
}
$controller = new OffersController;
$marketPlaceOffers = $controller -> listOffers( new Marketplace );
$catalogOffers = $controller -> listOffers( new Catalog );
$commercialBreakOffers = $controller -> listOffers( new CommercialBreak );
$outdoorAnnouncementOffers = $controller -> listOffers( new OutdoorAnnouncement );
Ask yourself:
MarketPlace
adds functionality to the classCurl
or just needs it to function?– Thomas
In fact it will not add new features to
Curl
.– Caio Guedes
So the best choice in this case is addiction, right?
– Caio Guedes
Exactly. From the examples you’ve shown, it’s just a dependency. But it doesn’t mean that if your system grows,
MarketPlace
does not extend a class that may come between this and theCurl
.– Thomas
Don’t forget to mark some answer as resolved. Your question today may be someone else’s tomorrow. ;)
– Bruno Augusto