Re: RFC: spl_autoload_register() should provide kind of entity to load
| From: | Anthony Ferrara | Date: | Sat, 18 Apr 2015 15:08:00 +0000 |
| Subject: | Re: RFC: spl_autoload_register() should provide kind of entity to load | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-85861@lists.php.net to get a copy of this message | ||
Georges,
On Sat, Apr 18, 2015 at 10:24 AM, georges <geolim4@gmail.com> wrote:
> Hi php internals,
>
> Currently spl_autoload_register() pass the name of the class entity to the
> first *Callable* argument, but there is now way (as i far i know) to know
> what kind of entity we're looking for.
> -Class ?
> -Interface ?
> -Trait?
>
>
> A second argument should be added to the *Callable* function describing
> what kind of entity we're looking for.
>
> Example:
>
> <?php
>
> // function __autoload($class) {
> // include 'classes/' . $class . '.class.php';
> // }
>
> function my_autoloader($entity, $kind = "class") {
> // Kind would be: class/interface/trait
> include $kind . '/' . $entity . ".{$kind}.php";
> }
>
> spl_autoload_register('my_autoloader');
>
> // Or, using an anonymous function as of PHP 5.3.0
> spl_autoload_register(function ($entity, $kind = "class") {
> // Kind would be: class/interface/trait
> include $kind . '/' . $entity . ".{$kind}.php";
> });
>
> ?>
>
>
> In fact i think currently that Autoload is too much "class oriented" as per
> reading php docs, whereas that php currently allow the autoload of many
> entities. It can really confuse probies php developers :(
>
> *Pros*:
>
> - -Avoid multiple else if() for testing an existing file to load the
> entity.
> - -As we now know the type of entity to load, it help reduce I/O
> activity, then reduce timespend.
> - -Clarify the code: We now what the autoloader will load
> - -Keep the BC safe
>
>
> *Cons*:
>
> - -None
>
This won't work out of the box due to spl_autoload(). If you use that
default autoloader (by calling spl_autoload_register()), it will
accept an optional second argument as the list of file extensions.
Which means that having spl_autoload_register() pass a second argument
to autoloaders will break the existing core autoloader. Changing the
core autoloader is also not really possible due to BC considerations.
So technically, without introducing a new autoload API, this won't
really be possible.
As far as the feature, I would question why you need to distinguish
the file by the type. The names are in the same symbol table, so you
couldn't possibly have a collision. From there, is the identification
of the type of the definition in the filename that important? Isn't
that just another form of Hungarian Notation?
Anthony