theofidry / PsyshBundle

A command line REPL bundle for Symfony using PsySH.
MIT License
208 stars 28 forks source link

Supports for class aliases #35

Open ed-fruty opened 6 years ago

ed-fruty commented 6 years ago

Can you provide class aliases out of the box? I talk about something like https://github.com/spatie/laravel-tinker-tools It would be very useful when we can do:

bin/console psysh
$entity = new User; // instead of new App\Entity\User;
$slugger = new Slugger; // instead of new App\Acme\Utils\Awesome\Slugger;
theofidry commented 6 years ago

That would be very nice to have, but I couldn't find how it was done last time I checked

ed-fruty commented 6 years ago

In spatie package it had been done by .psysh.php. I suggest to register short class loader directly before the shell execution.

And another one solution is dispatch event before shell execution and register short class loader in the listener.

I can make PR for it.

theofidry commented 6 years ago

Maybe that could do, but rather than doing this directly before the shell execution which implies having an overhead (which is already consequent) before running the command, it would be possible to do that in a Symfony Compiler pass. That way:

I'm a bit concerned however by the side-effects of registering all of those aliases like that, how are conflicts handled?

ed-fruty commented 6 years ago

There are no conflicts. Will be registered a new class loader and when you'll write something like:

bin/console psysh
$entity = new User;

loader will receive User class to autoload. It see all classes in composer class map and find the first one with the base class name User. And after that loader register class_alias for such class.

So imagine that we have two classes App\Services\Loader and App\DependencyInjection\Extension\Loader. And when we write

bin/console psysh
$loader = new Loader;

only the first class from composer class map (vendor/composer/autoload_classmap.php) will be used and aliased to Loader class. And in this case it would be App\DependencyInjection\Extension\Loader, because they are sorts by ASC.

Another loader instance you can create only with full namespace definition.

$loader2 = new App\Services\Loader
ed-fruty commented 6 years ago

And I think it's not pretty good idea to register class loader in the compiler class. In such case it will have side effects for none shell development. We need it only in when we in REPL. Maybe it would be better register class loader in PsyshCommand::initialize() method ?