PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

CHAPTER 9 ■ GENERATING OBJECTS


abstract function encode();
}


class BloggsApptEncoder extends ApptEncoder {
function encode() {
return "Appointment data encode in BloggsCal format\n";
}
}


abstract class CommsManager {
abstract function getHeaderText();
abstract function getApptEncoder();
abstract function getFooterText();
}


class BloggsCommsManager extends CommsManager {
function getHeaderText() {
return "BloggsCal header\n";
}


function getApptEncoder() {
return new BloggsApptEncoder();
}


function getFooterText() {
return "BloggsCal footer\n";
}
}


The BloggsCommsManager::getApptEncoder() method returns a BloggsApptEncoder object. Client
code calling getApptEncoder() can expect an object of type ApptEncoder and will not necessarily know
about the concrete product it has been given. In some languages, method return types are enforced, so
client code calling a method like getApptEncoder() can be absolutely certain that it will receive an
ApptEncoder object. In PHP, this is a matter of convention at present. It is important to document return
types, or otherwise signal them through naming conventions.


■Note At the time of this writing, hinted return types are a feature slated for a future release of PHP.


So when I am required to implement MegaCal, supporting it is simply a matter of writing a new
implementation for my abstract classes. Figure 9-5 shows the MegaCal classes.

Free download pdf