Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1
3

■ ■ ■


CHAPTER 1


Abstract Classes, Interfaces,


and Programming by Contract


In this chapter, you will learn about abstract classes, interfaces, and a technique known as
programming by contract. These are object-oriented programming (OOP) mechanisms that
allow you to write code that does more than just perform calculations or present output. These
constructs give you the ability to define conceptual rules about how classes interact, and they
provide a foundation for extension and customization in your applications.

Abstract Classes


Abstract classes involve the use of a common base class when you want to leave certain details
up to its inheritors—specifically, when you need to create a foundational object whose methods
are not fully defined. You will find that by using abstraction, you can create very extensible
architecture within your development projects.
For example, file-format parsing lends itself particularly well to the abstract approach. In
this case, you know that the object will need a set of methods, like getData() or getCreatedDate(),
in order for it to interoperate with other classes; however, you want to leave the parsing methods
up to inheriting classes that are designed for a specific file format. By using abstract classes,
you can define that a parse() method must exist, without needing to specify how it should
work. You can place this abstract requirement and the fully defined methods in a single class
for easier implementation.
You might think of abstract classes as partial classes because they do not define the imple-
mentation for all the methods they declare. Instead of implementing all methods, an abstract
class has the added ability to define abstract methods, which are method prototypes lacking a
body. These methods will be implemented when the class is derived. However, an abstract class
doesn’t need to consist solely of abstract methods; you’re free to declare fully defined methods
as well.

■Note A method’s prototype is the signature by which it is defined, exclusive of the body. This includes the
access level, the function keyword, the name of the function, and the parameters. It does not contain the brace
({ }) characters or any code inside. An example is public function prototypeName($protoParam);.

McArthur_819-9C01.fm Page 3 Tuesday, December 18, 2007 7:38 AM

Free download pdf