I was pointed to the http://wiki.php.net/rfc site the other day at the
ATLPHP user group and found the traits and related RFC's.
I just read the RFC on grafts and traits for PHP. Great ideas! There
is one other thing I'd like you to take a look at as well though,
that's very useful.
Objective-C has a construct called a Category. It is similar in
functionality to Traits, but has an important and useful distinction
in the way that the additional functions are "injected" into the
target class in practice.
Categories can be applied to existing classes from outside the class
definition. This is a very useful pattern in that it allows users of
classes to inject functionality without subclassing, AND without
touching the source of the target class.
class Helloworld
{
public function sayHello() { print "HELLO"; }
}
category HelloworldExtras on Helloworld
{
public function sayWorld() { print "World"; }
}
$h = new Helloworld;
$h->sayWorld(); // print "WORLD"
This is extremely beneficial for lightweight "extension" of classes
without subclassing.
Other than this, it is identical to traits.
I was discussing this off-list with Stefan, and he asked me how it
would work with autoloading, which has led me to add one more piece to
the idea, which is a way to tell the compiler to load your category. I
haven't thoroughly read all of the namespace RFCs so this may conflict
with the "use" keyword, but something like:
use HelloworldExtras;
Would be a lightweight way to make sure that the autoloader would add
the category into the runtime.
Looking forward to your comments. Also, I will be at php|works in
Atlanta Thursday and Friday if anyone is interested in discussing this
in person!
Regards,
Alan Pinstein
Regards,
Alan Pinstein
http://phocoa.com
class Helloworld
{
public function sayHello() { print "HELLO"; }
}category HelloworldExtras on Helloworld
{
public function sayWorld() { print "World"; }
}$h = new Helloworld;
$h->sayWorld(); // print "WORLD"This is extremely beneficial for lightweight "extension" of classes
without subclassing.
This feature is identical to the C# .NET "Extension" methods. The best use
of it is for selectively extending the primitive type classes on the fly
with methods you need (string, int, array, etc.).
The irony in this is, in PHP the primitive types are not OOP capable, so
with this in mind I wonder how much this functionality would serve to make
the life of people easier, and how much of it will be just the rope they
need to hang themselves. The concept of categories and extensions is not as
popular to the average developer as say classes and interfaces.
Also we can't overload "use" for this as "use" specifically only imports
symbol names, not actual code, into the environment. It doesn't have the
knowledge of whether something is a namespace, or a class, or a category, so
to know how to trigger autoload.
Regards, Stan Vassilev