Dynamic class aliases in package

Posted 2 years ago by dmitry.g.ivanov

Hi!

Let's pretend you have a package. And you want some class from your package would be available in a simple way, through class alias (as facade). The common solution is just to add an alias to config/app.php in aliases array:

    'aliases' => [

       // ...
        'FooBar' => My\SuperPackage\FooBar::class,

    ],

Now you can use FooBar like this:

FooBar::doSomething();

But, the bad thing that people using your package have to add those aliases by themselves.

The good thing is that you can do this automatically in your service provider:

use Illuminate\Foundation\AliasLoader;
use My\SuperPackage\FooBar;

class ServiceProvider extends \Illuminate\Support\ServiceProvider
{
    public function register()
    {
        $this->app->booting(function() {
            $loader = AliasLoader::getInstance();
            $loader->alias('FooBar', FooBar::class);
        });
    }
}

Hope it would be useful for someone! Thanks and have a great day!

Please sign in or create an account to participate in this conversation.