(on Thursday, 04 June 2009, 03:46 PM -0700):
> Did you understand what I said about why you wouldn't put magic
> methods in the interface?
>
> Yes, and I agree with you. I was just stating that it would be unsafe to use
> magic methods at all since they cannot (or should not) be in the interface.
>
> I'm curious, what would be the point of using an interface and an abstract base
> class? Shouldn't all of the derived classes implement the interface, instead of
> extending a base class? Or if all derived classes extend the base class, then
> what is the point of the interface?
An interface defines what must be implemented for an object to be of
that type. Due to PHP's multiple inheritance model, defining an
interface is the only way that you can repurpose a class that extends
another class to also implement a given set of functionality.
As an example, at the framework summit at php|tek, we talked about this
with relation to exceptions. It's useful to have package-level
exceptions that may easily be caught. That said, there are a variety of
useful exception classes already in the SPL that it would be good to be
able to throw -- for example, InvalidArgumentException and
BadMethodCallException. How can you throw an SPL exception *and* a
package-level exception?
The answer is by making the package-level base exception an interface,
and having classes that extend the SPL exceptions and implement the
package level interface:
interface My_Component_Exception
{}
class My_Component_InvalidArgumentException
extends InvalidArgumentException
implements My_Component_Exception
{}
You can then throw My_Component_InvalidArgumentException, and get all
the benefits of the SPL exception class, while still being able to catch
component level exceptions.
An abstract base class then is useful as it actually implements much of
the functionality in the interface in a re-usable way -- so that each
time you need to implement the interface, you don't have to define those
methods. An example here is in the new bootstrap classes. We provide two
interfaces, a Bootstrapper and ResourceBootstrapper. Our base class,
BootstrapAbstract, implements each of these -- so that you, the end
user, do not need to work out the details of the dozen or more methods
defined between the two of them.
--
Matthew Weier O'Phinney
Project Lead | matthew@zend.com
Zend Framework | http://framework.zend.com/
没有评论:
发表评论