constructor hook
| From: | Rasmus Schultz | Date: | Tue, 18 Sep 2012 12:19:19 +0000 |
| Subject: | constructor hook | ||
| Groups: | php.internals | ||
| Request: | Send a blank email to internals+get-63056@lists.php.net to get a copy of this message | ||
Hey,
I'm going to make this brief, because I suspect a lot of people are going
to jump at the opportunity to cry bloody murder when I suggest this.
I wonder if it would make sense to have a way to globally hook into
__construct() - sort of like how you can hook into the autoloaders with
spl_autoload_register() ...
This could be useful for things like dependency injection and debugging.
Lithium (for one) uses a unified constructor to accomplish something like
this:
http://lithify.me/docs/manual/lithium-basics/architecture.wiki
That's bad for various reasons I won't delve into.
Various DI containers use a replacement for the "new" keyword, e.g.
DI::create('MyClass') which is bad (worse) for other reasons...
So basically, what if you could solve these design patterns by hooking into
constructors directly instead - something like:
<?php
> constructor_hook_register(function($object) {
> echo 'an object of type '.get_class($object).' was constructed!';
> });
> $test = new Foo();
would print:
an object of type Foo was constructed!
One other area where this could help, is in event-driven systems, where
this sort of thing could be used for "co-construction".
Of course, you could accomplish the same thing in a more controlled
fashion, by simply establishing conventions - for example, DI::inject(new
My Class()) would work just as well, it's just inconvenient to type; on the
other hand, it's explicit about what's happening.
So I'm not at all demanding this feature - I'm merely posting this for
debate.
Thanks,
Rasmus Schultz