Abstract classes and Interfaces

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

Re: Abstract classes and Interfaces

Post by alex.barylski »

Abstract classes are base classes which occassionally provide some common (lowest common denominator) functionality. Interfaces are very loose contracts that ensure any classes which 'implement' an interface will implement the set methods in the set forth methos signature.

Real world example. Say I have a DB library. The library relies on depenendency injection to 'inject' the required driver (provider/implementation) whether it be mysql, mssql or sqlite.

Code: Select all

$db = new Database(new MySQLProvider('localhost', 'user', 'pass'));
The MySQLProvider class might do one of two things:

1. Inherit from an abstract class
2. Implement an interface

Or both they are not mutually exclusive.

As a DB library author I might define an interface which all 'providers' must implement:

Code: Select all

interface Provider{
  function insert($table, $params);
  function update($table, $id_primary, $params);
  function delete($table, $id_primary);
  function select($table, $fields);
}
No the Database() class might check in it's constructor, whether the injected object implements 'Provider' using reflection and throw an exception to signal an error if the class does not. One way of making your code more bullet proof, because you know if the class does not implement the above four methods exactly according to interface (method name and the parameters or arguments) it may provide the required behavior but the interface or method of communication is not the same, therefore the object provider is incompatible.

So while an interface is a contract, it's not a very strict contract, especially in PHP.

An abstract class on the other hand, is like an interface but it CAN offer some basic functionality which is common to all derived classes. Drawing on the example above.

The implementation of the various providers classes (MySQL, MSSQL, SQLite) might have common functionality which can be reused by all or most providers. Perhaps functionality INSERT, UPDATE and DELETE could be implemented in a abstract class, only because the SQL for every provider for those three operations are identical (I think just an example here).

However each provider class would need to implement (override at least) the SELECT method because that SQL is different across databases.

So an abstract class can save you a lot of work as the example above should tell you, however it's easier said than done. It's usually not worth using abstract classes unless you really have proven functionality to be common. If it applies to 2 providers and NOT 3 or 4 more, then an abstract class is not the right solution for code reuse. Using a composite would make more sense.

Cheers,
Alex
User avatar
papa
Forum Regular
Posts: 958
Joined: Wed Aug 27, 2008 3:36 am
Location: Sweden/Sthlm

Re: Abstract classes and Interfaces

Post by papa »

Thank you for your patience.

That example made it a lot more clear for me!


wieee!
josh
DevNet Master
Posts: 4872
Joined: Wed Feb 11, 2004 3:23 pm
Location: Palm beach, Florida

Re: Abstract classes and Interfaces

Post by josh »

PCSpectra wrote: No the Database() class might check in it's constructor, whether the injected object implements 'Provider' using reflection and throw an exception to signal an error if the class does not.
Good description Alex. I should add when I said "ask for the interface" this is what I meant. Except doing it thru PHP type hinting.

function __construct ( Interface $object ) // PHP will already raise an error if $object doesn't implement Interface ;-)
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Abstract classes and Interfaces

Post by Christopher »

PCSpectra wrote:Abstract classes are base classes which occassionally provide some common (lowest common denominator) functionality.
Any base class provides "common (lowest common denominator) functionality." I would say that abstract classes are base classes that require you to provide the implementation for one or more methods because the implementation of those methods is not known when the abstract class is implemented. Using an abstract simply to require extension, but not requiring adding implementation is just being a control freak.
PCSpectra wrote:Interfaces are very loose contracts that ensure any classes which 'implement' an interface will implement the set methods in the set forth methos signature.
I am not sure what you mean by 'loose contracts'? Interfaces strictly enforce an interface by checking method names and parameters. That they don't enforce return values (yet) or implementation means they are probably better described as 'incomplete contracts.'
(#10850)
josh
DevNet Master
Posts: 4872
Joined: Wed Feb 11, 2004 3:23 pm
Location: Palm beach, Florida

Re: Abstract classes and Interfaces

Post by josh »

I think the terms are confusing. If you have a base class you would say you "abstracted" behavior out. Other classes then extend this class. But then the word "abstract" is also refers to an actual language feature that works much like interfaces.

If you have a class that doesn't use the language feature "abstract class" I guess it should not be called abstract to avoid to confusion. I kinda already knew that but didn't apply this rule in my own development. I will start today. I have so many classes that are named Abstract.php that aren't abstract, should be renamed to Base.php to make my names better ;-)
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Abstract classes and Interfaces

Post by Christopher »

josh wrote:If you have a class that doesn't use the language feature "abstract class" I guess it should not be called abstract to avoid to confusion. I kinda already knew that but didn't apply this rule in my own development. I will start today. I have so many classes that are named Abstract.php that aren't abstract, should be renamed to Base.php to make my names better ;-)
That is actually a good idea and distinction. That is what I was trying to get to. Perhaps we need to come up with some clear definitions, for example:

- If you want to inherit methods (and properties/consts) then that is a Base class.

- If you not only want to inherit some implementation (methods/properties/consts), but want to require the inheriting class to provide implementation for one or more methods -- then that is an Abstract class. The abstract keyword works specifically in that case because you cannot directly instantiate an abstract class, so unlike a Base class it requires extension.

- If you want to require methods to be implemented in more than one sub-class, but want the inheriting class to provide implementation, then use an Interface.
(#10850)
alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

Re: Abstract classes and Interfaces

Post by alex.barylski »

I would say that abstract classes are base classes that require you to provide the implementation for one or more methods because the implementation of those methods is not known when the abstract class is implemented.
ABC (Abstract Base Class) I never intended to mean anything else. Abstract meaning you cannot use it directly, base class meaning it provides some LCD functionality.
am not sure what you mean by 'loose contracts'? Interfaces strictly enforce an interface by checking method names and parameters. That they don't enforce return values (yet) or implementation means they are probably better described as 'incomplete contracts.
I used the adjective 'loose' to appease Jenk. :P Mostly because the term contract is clearly open to opinion. In Jenk's world, clearly a contract means more than enforcing a method signature, but also includes behavior. This is IMO, outside the scope of an 'interface' contract but obviously to others, this is not the case.

Contract when used on it's own (without adjectives) is extremely vague. A verbal contract is much more easily broken than a legal/document contract, but they are still none-the-less contracts, right? :)
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Abstract classes and Interfaces

Post by Christopher »

PCSpectra wrote:ABC (Abstract Base Class) I never intended to mean anything else. Abstract meaning you cannot use it directly, base class meaning it provides some LCD functionality.
I disagree. It is never intended to mean anything else ... except in most of the conversations about using the "abstract" keyword in PHP. I was talking about what it actually means, and how it should be used in PHP -- not some they generic definition which leads to confusion in my opinion.
PCSpectra wrote:I used the adjective 'loose' to appease Jenk. :P Mostly because the term contract is clearly open to opinion. In Jenk's world, clearly a contract means more than enforcing a method signature, but also includes behavior. This is IMO, outside the scope of an 'interface' contract but obviously to others, this is not the case.
I guess I agree with Jenk then...
PCSpectra wrote:Contract when used on it's own (without adjectives) is extremely vague. A verbal contract is much more easily broken than a legal/document contract, but they are still none-the-less contracts, right? :)
Agreed, which is why I said that a PHP interface provides an incomplete contract -- not no contract.
(#10850)
User avatar
PHPHorizons
Forum Contributor
Posts: 175
Joined: Mon Sep 14, 2009 11:38 pm

Re: Abstract classes and Interfaces

Post by PHPHorizons »

In law, a contract is a binding legal agreement that is enforceable in a court of law[1] or by binding arbitration. That is to say, a contract is an exchange of promises with a specific remedy for breach.
Removing the law portion of that, and replacing it with the php interpreter, we have the exact definition of contract as applied to interfaces. The binding agreement is that any method listed in the interface must be implemented in a class that implements the interface. The remedy for breaching said contract is a fatal error.

Where in this arrangement is the term contract not used correctly? It fits the definition perfectly...
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Abstract classes and Interfaces

Post by Christopher »

The reason that it does not fit the definition perfectly is that, as PCSpectra re Jenk point out, a contract not only specifies the method name and parameters, but its return value and what it actually does (i.e. errors, side effects, preconditions, postconditions, etc.). Therefore a PHP interface is only a partial contract in the "design by contract" sense ...
(#10850)
User avatar
PHPHorizons
Forum Contributor
Posts: 175
Joined: Mon Sep 14, 2009 11:38 pm

Re: Abstract classes and Interfaces

Post by PHPHorizons »

I don't see that in the definition of contract...
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Abstract classes and Interfaces

Post by Christopher »

Are you talking about in law or in computer science? Talking about the definition in law is a little bit of a waste of time because "contract" has a specific meaning in software design.
(#10850)
josh
DevNet Master
Posts: 4872
Joined: Wed Feb 11, 2004 3:23 pm
Location: Palm beach, Florida

Re: Abstract classes and Interfaces

Post by josh »

There is no definition for a metaphor. Metaphors are subjective by design.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Abstract classes and Interfaces

Post by Christopher »

Unlike most metaphors, this one is trademarked... ;)

http://en.wikipedia.org/wiki/Design_by_contract
(#10850)
User avatar
PHPHorizons
Forum Contributor
Posts: 175
Joined: Mon Sep 14, 2009 11:38 pm

Re: Abstract classes and Interfaces

Post by PHPHorizons »

I've never heard of a specific/trademarked "design by contract"... Can't say I care too much what that is either lol.

What I do know is that when I learned about interfaces, and I read that an interface is like a contract... etc., etc., I read "contract" as "contract".

If the author of whichever tutorial I picked that up from meant something else, then they should have said that.

Contract still seems appropriate to me.

Cheers
Post Reply