Is there any point for interfaces in dynamic languages? - php

In static languages like Java you need interfaces because
otherwise the type system just won't let you do certain things.
But in dynamic languages like PHP and Python you just take
advantage of duck-typing.
PHP supports interfaces.
Ruby and Python don't have them.
So you can clearly live happily without them.
I've been mostly doing my work in PHP and have never really
made use of the ability to define interfaces. When I need a
set of classes to implement certain common interface, then
I just describe it in documentation.
So, what do you think? Aren't you better off without using
interfaces in dynamic languages at all?

I think of it more as a level of convenience. If you have a function which takes a "file-like" object and only calls a read() method on it, then it's inconvenient - even limiting - to force the user to implement some sort of File interface. It's just as easy to check if the object has a read method.
But if your function expects a large set of methods, it's easier to check if the object supports an interface then to check for support of each individual method.

Yes, there is a point
If you don't explicitly use interfaces your code still uses the object as though it implemented certain methods it's just unclear what the unspoken interface is.
If you define a function to accept an interface (in PHP say) then it'll fail earlier, and the problem will be with the caller not with the method doing the work. Generally failing earlier is a good rule of thumb to follow.

Interfaces actually add some degree of dynamic lang-like flexibility to static languages that have them, like Java. They offer a way to query an object for which contracts it implements at runtime.
That concept ports well into dynamic languages. Depending on your definition of the word "dynamic", of course, that even includes Objective-C, which makes use of Protocols pretty extensively in Cocoa.
In Ruby you can ask whether an object responds to a given method name. But that's a pretty weak guarantee that it's going to do what you want, especially given how few words get used over and over, that the full method signature isn't taken into account, etc.
In Ruby I might ask
object.respond_to? :sync
So, yeah, it has a method named "sync", whatever that means.
In Objective-C I might ask something similar, i.e. "does this look/walk/quack like something that synchronizes?":
[myObject respondsToSelector:#selector(sync)]
Even better, at the cost of some verbosity, I can ask something more specific, i.e. "does this look/walk/quack like something that synchronizes to MobileMe?":
[myObject respondsToSelector:#selector(sync:withMobileMeAccount:)]
That's duck typing down to the species level.
But to really ask an object whether it is promising to implement synchronization to MobileMe...
[receiver conformsToProtocol:#protocol(MobileMeSynchronization)]
Of course, you could implement protocols by just checking for the presence of a series of selectors that you consider the definition of a protocol/duck, and if they are specific enough. At which point the protocol is just an abbreviation for a big hunk of ugly responds_to? queries, and some very useful syntactic sugar for the compiler/IDE to use.
Interfaces/protocols are another dimension of object metadata that can be used to implement dynamic behavior in the handling of those objects. In Java the compiler just happens to demand that sort of thing for normal method invocation. But even dynamic languages like Ruby, Python, Perl, etc. implement a notion of type that goes beyond just "what methods an object responds to". Hence the class keyword. Javascript is the only really commonly used language without that concept. If you've got classes, then interfaces make sense, too.
It's admittedly more useful for more complicated libraries or class hierarchies than in most application code, but I think the concept is useful in any language.
Also, somebody else mentioned mixins. Ruby mixins are a way to share code -- e.g., they relate to the implementation of a class. Interfaces/protocols are about the interface of a class or object. They can actually complement each other. You might have an interface which specifies a behavior, and one or more mixins which help an object to implement that behavior.
Of course, I can't think of any languages which really have both as distinct first-class language features. In those with mixins, including the mixin usually implies the interface it implements.

If you do not have hight security constraints (so nobody will access you data a way you don't want to) and you have a good documentation or well trained coders (so they don't need the interpreter / compiler to tell them what to do), then no, it's useless.
For most medium size projects, duck typing is all you need.

I was under the impression that Python doesn't have interfaces. As far as I'm aware in Python you can't enforce a method to be implemented at compilation time precisely because it is a dynamic language.
There are interface libraries for Python but I haven't used any of them.
Python also has Mixins so you could have create an Interface class by defining a Mixin an having pass for every method implementation but that's not really giving you much value.

I think use of interfaces is determined more by how many people will be using your library. If it's just you, or a small team then documentation and convention will be fine and requiring interfaces will be an impediment. If it's a public library then interfaces are much more useful because they constrain people to provide the right methods rather than just hint. So interfaces are definitely a valuable feature for writing public libraries and I suppose that lack (or at least de-emphasis) is one of the many reasons why dynamic languages are used more for apps and strongly-typed languages are used for big libraries.

Rene, please read my answer to "Best Practices for Architecting Large Systems in a Dynamic Language" question here on StackOverflow. I discuss some benefits of giving away the freedom of dynamic languages to save development effort and to ease introducing new programmers to the project. Interfaces, when used properly, greatly contribute to writing reliable software.

In a language like PHP where a method call that doesn't exist results in a fatal error and takes the whole application down, then yes interfaces make sense.
In a language like Python where you can catch and handle invalid method calls, it doesn't.

Python 3000 will have Abstract Base Classes. Well worth a read.

One use of the Java "interface" is to allow strongly-typed mixins in Java. You mix the proper superclass, plus any additional methods implemented to support the interface.
Python has multiple inheritance, so it doesn't really need the interface contrivance to allow methods from multiple superclasses.
I, however, like some of the benefits of strong typing -- primarily, I'm a fan of early error detection. I try to use an "interface-like" abstract superclass definition.
class InterfaceLikeThing( object ):
def __init__( self, arg ):
self.attr= None
self.otherAttr= arg
def aMethod( self ):
raise NotImplementedError
def anotherMethod( self ):
return NotImplemented
This formalizes the interface -- in a way. It doesn't provide absolute evidence for a subclass matching the expectations. However, if a subclass fails to implement a required method, my unit tests will fail with an obvious NotImplemented return value or NotImplementedError exception.

Well, first of all, it's right that Ruby does not have Interface as is, but they have mixin, wich takes somehow the best of both interfaces and abstract classes from other languages.
The main goal of interface is to ensure that your object SHALL implement ALL the methods present in the interface itself.
Of course, interface are never mandatory, even in Java you could imagine to work only with classes and using reflection to call methods when you don't know wich kind of object you're manipulating, but it is error prone and should be discouraged in many ways.

Well, it would certainly be easier to check if a given object supported an entire interface, instead of just not crashing when you call the one or two methods you use in the initial method, for instance to add an object to an internal list.
Duck typing has some of the benefits of interfaces, that is, easy of use everywhere, but the detection mechanism is still missing.

It's like saying you don't need explicit types in a dynamically-typed language. Why don't you make everything a "var" and document their types elsewhere?
It's a restriction imposed on a programmer, by a programmer. It makes it harder for you to shoot yourself in the foot; gives you less room for error.

as a PHP programmer, the way I see it, an Interface is basically used as a contract. It lets you say that everything which uses this interface MUST implement a given set of functions.
I dunno if that's all that useful, but I found it a bit of a stumbling block when trying to understand what Interfaces were all about.

If you felt you had to, you could implement a kind of interface with a function that compares an object's methods/attributes to a given signature. Here's a very basic example:
file_interface = ('read', 'readline', 'seek')
class InterfaceException(Exception): pass
def implements_interface(obj, interface):
d = dir(obj)
for item in interface:
if item not in d: raise InterfaceException("%s not implemented." % item)
return True
>>> import StringIO
>>> s = StringIO.StringIO()
>>> implements_interface(s, file_interface)
True
>>>
>>> fp = open('/tmp/123456.temp', 'a')
>>> implements_interface(fp, file_interface)
True
>>> fp.close()
>>>
>>> d = {}
>>> implements_interface(d, file_interface)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in implements_interface
__main__.InterfaceException: read not implemented.
Of course, that doesn't guarantee very much.

In addition to the other answers I just want to point out that Javascript has an instanceof keyword that will return true if the given instance is anywhere in a given object's prototype chain.
This means that if you use your "interface object" in the prototype chain for your "implementation objects" (both are just plain objects to JS) then you can use instanceof to determine if it "implements" it. This does not help the enforcement aspect, but it does help in the polymorphism aspect - which is one common use for interfaces.
MDN instanceof Reference

Stop trying to write Java in a dynamic language.

Related

PHP: Should I be creating objects of this class, or is static acceptable?

I have a couple questions regarding best practices and performance for this project I am working on. Forgive me for the huge question.
I'm currently building a text-based game with PHP and MySql that is about 2,500 lines in the core file so far. Currently, this is a library of completely modular functions. Some used for data access, some for data manipulation, and so on.
My first question is this: One class, ItemManager, contains dozens of methods specifically for adding, updating, and deleting game items in the database. The only thing these methods have in common in they interact with the database. Currently, the constructor asks for a mysqli object and then uses that in all it's functions. However, once I add MongoDB into the project, some of these functions may be interacting with a different database.
Would it be acceptable or preferable to simply make all of these functions static? I see no reason to instantiate objects when there would only ever be one, and there is no need for it to maintain class members. So, should I use static methods or not? Why?
Second question: Can someone help me understand the benefit of using classes in PHP BESIDES modularity (as I can achieve that same effect with files of functions)? Coming from a Java background, I recognize the benefit of OOP in a persistent environment, as objects maintain data and states throughout the life of the application. However, with PHP, the life span of a script is a fraction of a second and all state information is stored within a database. Almost all functions just manipulate the database, so what's the purpose? Isn't it pointless to instantiate objects when I can merely call functions? Could I just do entirely static classes containing categorized data manipulation classes without instantiating an object of a class? What are the reasons I should use classes over files of functions? Isn't the basically the same? Are completely static functions acceptable?
Thank you for your time, I wasn't sure how to cut that question into less text, so I apologize.
Would it be acceptable or preferable to simply make all of these
functions static? I see no reason to instantiate objects when there
would only ever be one
There is no reason to instantiate objects if all you ever want to do is what this class is capable of doing. By using static methods you are coupling all of your client code with the class by hardcoding the class name throughout your code base. If at some later point you decide that you might want a different item manager service to fulfill your requests you will most certainly have a bad day.
Note that "a different item manager" can be simply code for "a mock manager used to unit test the rest of your code". So even in cases where alternatives will never be supported, using statics like that makes your code practically untestable.
Of course, you have already mentioned that there could very well be a different item manager in place: if the current one accepts a mysqli object then obviously there is no abstraction layer between your manager code and the mysqli interface. If you want to use a different object to connect to Mongo, how is the current item manager code going to support both configurations? Won't you need to write a new item manager class? How are you going to integrate it with the rest of the code if the class name is hardcoded everywhere?
Let's also view the situation from the opposite side: what does static gain you?
Obviously it makes the item manager a "singleton" object, which may sound like a good idea because "there is only one of it". This idea cannot be dismissed out of hand in PHP (as in other languages where multithreading is supported and there are hidden cross-thread dependencies), but it still doesn't hold much water. If you want your item manager to be a singleton, then simply don't create a second instance. If you want to force this for some reason, use a static variable to count instantiations and throw if you try more than one. Finally, make the class final so that this limitation cannot be removed. The result: a singleton that is not static.
This is all that static has going for it, and in light of the above it's awfully weak to stand as an argument.
and there is no need for it to maintain class
members. So, should I use static methods or not? Why?
I 'm not sure what this means -- you say the constructor already requires a database driver object, which has every right to be a class member. This is another obvious hint that static is not the way to go here.
Can someone help me understand the benefit of using classes in PHP
BESIDES modularity (as I can achieve that same effect with files of
functions)?
I 'm not going to present obvious arguments for OOP here, but raise a counter-point instead: you can achieve the same runtime effect, but you most certainly cannot achieve the same levels of maintainability and debugability for your application. Why use an inferior solution?
Coming from a Java background, I recognize the benefit of OOP in a
persistent environment, as objects maintain data and states throughout
the life of the application. However, with PHP, the life span of a
script is a fraction of a second and all state information is stored
within a database. Almost all functions just manipulate the database,
so what's the purpose? Isn't it pointless to instantiate objects when
I can merely call functions?
The life span of a process is a fraction of a second. The life span of the code base is measured in months, years and decades. That's how long people will be maintaining it, and that's why we use OOP in the first place.
Global variables can hold state just as well as class members, and people have been maintaining state long before "object-oriented" was a term. The benefit of OO is managing the complexity of the source-code-level model of the code, a venture I would most certainly not agree to describe as pointless.
So, should I use static methods or not? Why?
Static methods usually access static variables, which are global state (they are no different than global variables in this regard), which are bad, for many reasons.
Also, while an object instance can be replaced by an other object having the same interface, just by passing an other object to functions using it, static methods cannot easily be replaced. As a result, you can not mock them, and code using them is not easily unit-testable.
If you can, don't use static methods.
1) Stick with the object, as it is easily replaceable or extendable by additional db drivers (e.g. you can overwrite some functions to transparently redirect to MongoDB for special getters.) If you are sure that you will use only once instance, use a singleton, or even better, a regitry pattern.
2) PHPs lifespan isn´t that short. Using an MVC pattern it handles bootstrap, routing, models, business logic and output. So while a single request might only take seconds, it can involve hundreds of classes and thousands of methods.
To stick to your RPG example: One day you might decide to make it multiplayer. Now you can either instanciate a second player-object, or adapt about 500 functions. The former one is only possible with classes.
A great reason is human limitation: It is unlikely to keep the meaning of thousands of functions in mind, especially when working in teams. By using objects, you can define slim APIs. If the player-object has the public methods add_item(\item $item) and remove_item(\item $item), there won´t be a need to keep all those checking, calculating and db-handling functions in mind. You can even ask a fellow developer "create a \monster item with nothing but an attack() method". That´s it, you are done, and cooperation worked at it´s best.
Conclusion If you are from Java background and understand OOP, don´t think twice about ditching that habit. PHP is NOT a pre-OO-script to be used by scriptkiddies. It´s a full-fledged OO environment - but it´s up to you if you take advantage of this.

Are Interfaces just "Syntactic Sugar"?

I've been playing mostly with PHP and Python.
I've been reading about Interfaces in OO programming and can't see an advantage in using it.
Multiple objects can implement the same interface, but multiple inheritance doesn't provide this as well?
Why do I need to create an Interface "with no implementation" - mainly a "contract" - if I can just check if a method exists in an object in Python, that inherits from multiple classes?
Do Interfaces were created in another languages because they don't provide multiple inheritance? Or am I missing something more important here?
First, and foremost, try not to compare and contrast between Python and Java. They are different languages, with different semantics. Compare and contrast will only lead to confusing questions like this where you're trying to compare something Python doesn't use with something Java requires.
It's a lot like comparing the number 7 and the color green. They're both nouns. Beyond that, you're going to have trouble comparing the two.
Here's the bottom line.
Python does not need interfaces.
Java requires them.
Multiple objects can implement the same interface, but multiple inheritance doesn't provide this as well?
The two concepts have almost nothing to do with each other.
I can define a large number of classes which share a common interface. In Python, because of "duck typing", I don't have to carefully be sure they all have a common superclass.
An interface is a declaration of "intent" for disjoint class hierarchies. It provides a common specification (that can be checked by the compiler) that is not part of the simple class hierarchy. It allows multiple class hierarchies to implement some common features and be polymorphic with respect to those features.
In Python you can use multiple inheritance with our without interfaces. Multiple inheritance can include interface classes or not include interface classes.
Java doesn't even have multiple inheritance. Instead it uses a completely different technique called "mixins".
Why do I need to create an Interface "with no implementation" - mainly a "contract" - if I can just check if a method exists in an object in Python, that inherits from multiple classes?
If you create an interface in Python, it can be a kind of formal contract. A claim that all subclasses will absolutely do what the interface claims.
Of course, a numbskull is perfectly free to lie. They can inherit from an interface and mis-implement everything. Nothing prevents bad behavior from sociopaths.
You create an interface in Java to allow multiple classes of objects to have a common behavior. Since you don't tell the compiler much in Python, the concept doesn't even apply.
Do Interfaces were created in another languages because they don't provide multiple inheritance?
Since the concepts aren't related, it's hard to answer this.
In Java, they do use "mixin" instead of multiple inheritance. The "interface" allows some mixing-in of additional functionality. That's one use for an interface.
Another use of an Interface to separate "is" from "does". The class hierarchy defines what an objects IS. The interface hierarchy defines what a class DOES.
In most cases, IS and DOES are isomorphic, so there's no distinction.
In some cases, what an object IS and what an object DOES are different.
The usefulness of an interface is directly connected to the usefulness of static typing. If you're working in a dynamically-typed language like PHP or Python, interfaces truly don't add significantly to the expressiveness of the language. That is, any program that can be described as using interfaces can be expressed without significant difference without using interfaces.
As a result, Python has a fairly nebulous concept of a "protocol" (an implementation conforming to a certain pattern, like the iteration protocol) which amounts to essentially the same thing, but without the other benefits of compile-time checking its value is limited.
In a statically-typed language, on the other hand, an interface is essential to allow implementation to be decoupled from implementation. In a static language, the types of all expressions must be resolved at compile time, so normally bindings to implementation must be made at that time, limiting run-time flexibility. An interface defines how to access functionality without defining a specific implementation, which allows a static language to prove that expressions are correct without having access to the implementation.
Without interfaces (or an equivalent formulation like C++'s pure virtual functions), the expressiveness of a statically-typed language would be severely hampered. In fact, many implementations exist (Win32 and COM come immediately to mind) to essentially reproduce much of the functionality of interfaces and virtual dispatch in C by storing function pointers in structures (and thus re-implementing C++'s virtual functions and vtable invocation by hand). In this case there is a big difference in expressiveness, since many changes are required in the program to express the same concepts.
Interfaces are just one example of type polymorphism, and a fairly limited one at that. In languages that support parametric polymorphism (aka generics) you can accomplish much more. (For example, C#'s LINQ would not be possible without generic interfaces.) For a much more powerful form of the same kind of thing, look into Haskell's typeclasses.
Even in duck-typed languages like Python, an interface can be a clearer statement of your intent. If you have a number of implementations, and they share a set of methods, an interface can be a good way to document the external behavior of those methods, give the concept a name, and make the concept concrete.
Without the explicit interface, there's an important concept in your system that has no physical representation. This doesn't mean you have to use interfaces, but interfaces provide that concreteness.
In dynamically typed languages, like PHP and Python, interfaces are only of limited use. You can already attempt to call methods on any object whenever, and you get a run-time error if it doesn't exist.
It's in statically typed languages, like Java and .NET, that interfaces become important, because methods and their arguments are checked at compile-time.
Now, for interfaces:
Java has Lists in addition to arrays. As a general rule, arrays are for primitives (the number types mainly), while Lists are for objects.
I can have a List<String>, which is a list of strings. I know I can add strings to it, and get strings back from it.
I don't know which implementation it is. It could be an ArrayList (list backed by an array), a LinkedList (list backed by a doubly linked list), a CopyOnWriteArrayList (thread-safe version of ArrayList), etc...
Thanks to polymorphism and interfaces, I don't need to know which type of List it is to do List operations on it.
Because you want to program against an interface and not a concrete implementation (GoF 1995:18)
Because sometimes you don't want to provide an implementation.
Java Interface
Java class
Yes. As for PHP, interfaces are just a means to overcome the lack of multiple inheritance. There are minor semantic differences useful for IDEs, and fewer conflicts caused by interfaces clearly aid newbie programmers. But as said before, it's not strictly necessary in dynamic languages.
http://c2.com/cgi/wiki?MultipleInheritance
Please read Twisted Framework article about power of Zope Interfaces in python.
It's generally implemented to replace multiple inheritance (C#).
I think some languages/programmers use them as a way of enforcing requirements for object structure as well.

What is the point of interfaces in a weakly-typed language like PHP?

I've never been able to figure this out. If your language doesn't type-check, what benefits do interfaces provide you?
Interfaces cause your program to fail earlier and more predictably when a subclass "forgets" to implement some abstract method in its parent class.
In PHP's traditional OOP, you had to rely on something like the following to issue a run-time error:
class Base_interface {
function implement_me() { assert(false); }
}
class Child extends Base_interface {
}
With an interface, you get immediate feedback when one of your interface's subclasses doesn't implement such a method, at the time the subclass is declared rather than later during its use.
Taken from this link (sums it up nicely):
Interfaces allow you to define/create
a common structure for your classes –
to set a standard for objects.
Interfaces solves the problem of
single inheritance – they allow you
to inject ‘qualities’ from multiple
sources.
Interfaces provide a flexible
base/root structure that you don’t
get with classes.
Interfaces are great when you have
multiple coders working on a project
; you can set up a loose structure
for programmers to follow and let
them worry about the details.
I personally find interfacing a neat solution when building a DataAccess layer which has to support multiple DBMS's. Each DBMS implementation must implement the global DataAccess-interface with functions like Query, FetchAssoc, FetchRow, NumRows, TransactionStart, TransactionCommit, TransactionRollback etc. So when you're expanding your data-acccess posibilities you are forced to use a generic defined functionschema so you're application won't break at some point because you figured the function Query should now be named execQuery.
Interfacing helps you develop in the bigger picture :)
Types serve three distinct functions:
design
documentation
actual type checking
The first two don't require any form of type checking at all. So, even if PHP did no checking of interfaces, they would still be useful just for those two reasons.
I, for example, always think about my interfaces when I'm doing Ruby, despite the fact that Ruby doesn't have interfaces. And I often wish I could have some way of recording those design decisions in the source code.
On the other hand, I have seen plenty of Java code that used interfaces, but clearly the author never thought about them. In fact, in one case, one could see from the indentation, whitespace and some leftover comments in the interface that the author had actually just copied and pasted the class definition and deleted all method bodies.
Now to the third point: PHP actually does type check interfaces. Just because it type checks them at runtime doesn't mean it doesn't type check them at all.
And, in fact, it doesn't even check them at runtime, it checks them at load time, which happens before runtime. And isn't "type checking doesn't happen at runtime but before that" pretty much the very definition of static type checking?
You get errors if you haven't added the required methods with the exact same signature.
Interfaces often used with unit-testing (test-driven design).
it also offers you more stable code.
the interfaces are also used to support iterators (eg. support for foreach on objects) and comparators.
It may be weakly typed, but there is type hinting for methods: function myFunc(MyInterface $interface)
Also, interfaces do help with testing and decoupling code.
Type hinting in function/method signatures allows you to have much more control about the way a class interfaces with it's environment.
If you'd just hope that a user of your class will only use the correct objects as method parameters, you'll probably run into trouble. To prevent this, you'd have to implement complicated checks and filters that would just bloat your code and definitely have would lower your codes performance.
Type hinting gives you a tool to ensure compatibility without any bloated, hand written checks. It also allows your classes to tell the world what they can do and where they'll fit in.
Especially in complex frameworks like the Zend Framework, interfaces make your live much easier because they tell you what to expect from a class and because you know what methods to implement to be compatible to something.
In my opinion, there's no point, no need and no sense. Things like interfaces, visibility modifiers or type hints are designed to enforce program "correctness" (in some sense) without actually running it. Since this is not possible in a dynamic language like php, these constructs are essentially useless. The only reason why they were added to php is make it look more like java, thus making the language more attractive for the "enterprise" market.
Forgot to add: uncommented downvoting sucks. ;//

Utilities file in php?

What is the best way to deal with "utility" functions in a OOP PHP framework? Right now, we just have a file with several functions that are needed throughout the system. (For example, a distribute() function which accepts a value and an array, and returns an array with the value distributed in the same proportions and same keys as the input array.)
I have always felt "dirty" using that because it's not object-oriented at all. Is it better practice to move these into various classes as static methods, or is that just a semantic workaround? Or is there just going to be a level in a framework where some stuff is going to fall outside of the OOP structure?
I tend to make a Util() class that contains only static methods, has no attributes, and is not inherited from. Essentially, it acts as a "namespace" to a bunch of utility functions. I will allow this class to grow in size, but will occasionally split of methods into their own classes if it is clear that those methods are designed only to work with certain kinds of data or if it is clear that a group of related methods should be grouped into a class along with, perhaps, some attributes.
I think it's perfectly OK to deviate from purely OOP practices so long as the code that deviates is well-organized and is not creating architectural flaws in your system that make it harder to understand and maintain.
I've always been more pragmatic about questions like these.
If you want to go full-OOP, you should obviously stick these into classes. However, these classes are only going to be container classes, because they don't really represent objects of any kind.
Also: using classes would require you to either have an instance of that class, using the singleton pattern or declaring every function static. The first one is slower (okay, might not be that much, but in a large framework things like that get large, too - especially in interpreted languages like PHP), while the second and third ones are just plain useless and simply an OOP wrapper for a set of functions (especially the third approach).
EDIT: Feel free to prove me wrong. I might be. I'm not too experienced and always saw it that way, but I might be wrong.
I always think of utility functions as extensions of the standard php functions. They are not object oriented because you don't really get any benefit from making them OO.

CLOS like object model for PHP

I have returned to php development from Moose and I really miss CLOS like object model for php. Is there some kind of syntaxtic sugar which would allow me to write less code in php when dealing with objects?
Just to stress this requirement a bit more. I don't want to write one thing in several places. I can live with part of code being generated automatically, but in the code that I have to see to develop I don't want to see redundant information which is just clutter (think: LISP macro if you really need more analogy). So this part can be also called DSL if that makes more sense.
I would love to have at least roles (mixins), and some kind of introspection without re-inventing the weel. Code generators and auto-loaders might be one way to solve at least part of this problem.
p.s. For JavaScript there is Joose, so similar API would be very useful.
There are no mixins in php yet but there is an RFC for traits which will work roughly the same. http://wiki.php.net/rfc/traits
Using overloading for __call can allow you to dispatch methods to other classes and have it look like a mixin.
The Symfony project has a mechanism for mixins, allowing aspect oriented programming like in CLOS. Personally, I don't like this kind of hacking in userland spacee (At least not with PHP). I think you would be better off using the features that the language provides, and perhaps wait for something like traits to (maybe) make its way into the language.
There is also new project http://github.com/huberry/phuby which implements roles in php!

Categories