Quantcast
Channel: Recent posts across whole site
Viewing all articles
Browse latest Browse all 49199

Class extension / Mixins via Code Generation?

$
0
0

[UPDATE]
The technique outlined in this post is now published as a module,
http://drupal.org/project/stapler
[/UPDATE]

As chx said it in another discussion in this group:

I would love to see more OO used in Drupal, as it simplifies the syntax, makes it easier to comprehend, but without sacrifices to the modularity which we have now.

You can't do that because PHP does not let extend a class once it's defined. This is the fundamental problem and going around it requires a drastically different design to what we have now.

Is this a problem for us? Would we gain a lot of we had extensible classes?
I'm not going to answer this question here, just brainstorm different ways to achieve extensible classes in PHP.
Maybe we really don't need it in the end.

--------

One way to get around this is magic methods. These have a performance cost if compared to direct method calls, but might still be faster than other ways to gain the same flexibility.

--------

Another way is code generation.
Is this scary? Yes, a bit.

<?php
class somemodule_mixin_SomeClass {
  function
someMethod() {}
}

class
anothermodule_mixin_SomeClass {
  function
anotherMethod() {}
}
?>

By code generation, this becomes:

<?php
class SomeClass {
  function
someMethod() {}
  function
anotherMethod() {}
}
?>

-----------

There are different ways this code generation can work:
1. Reflection or parsing on the given mixin classes provided by different modules, then assemble as a new class, and store the code in a file somewhere.
2. The same, but store the code in the database to execute with eval(). Not sure why we would do that, but it is a technical possibility.
3. Let the mixin classes indirectly inherit from each other, in a big chain. The code generation would only declare the joints.

The third version requires a slightly different syntax in the source files:

<?php
class somemodule_mixin_SomeClass extends somemodule_mixinBase_SomeClass  {
  function
someMethod() {}
}

class
anothermodule_mixin_SomeClass extends anothermodule_mixinBase_SomeClass {
  function
anotherMethod() {}
}
?>

Generated code:

<?php
class somemodule_mixinBase_SomeClass {}
class
anothermodule_mixinBase_SomeClass extends somemodule_mixin_SomeClass {}
class
SomeClass extends anothermodule_mixin_SomeClass {}
?>

The code can be generated ad-hoc and then eval()'d, or it can be stored in a file.

-------

Anything that involves code generation into a file needs some extra thinking about when this code generation needs to happen. In every request? When a new module is enabled / disabled?


Viewing all articles
Browse latest Browse all 49199

Trending Articles