Understanding class importation and alias management in Laravel 11's new directory structure

256 Views Asked by At

I seek guidance on importing classes and managing aliases in Laravel 11, which has introduced a new directory structure. In previous Laravel versions, I would handle these tasks in the app.php configuration file. However, Laravel 11 seems to have a different approach to managing class imports and aliases.

I would appreciate any assistance understanding how to import the Alias Class in this new context.

2

There are 2 best solutions below

0
jeremyj11 On

I've just run into the same problem as you.. searching online I can't find any 'new' way to do it, but fyi the 'old' way still works - just add your own 'aliases' array to config/app.php

eg:

'aliases' => Facade::defaultAliases()->merge([
    'MyAlias' => App\SomePath\MyFacade::class,
])->toArray(),

and don't forget to import at the top:

use Illuminate\Support\Facades\Facade;
0
artrz On

You can do it using the Alias Loader or the PHP function class_alias from a service provider. Something like:

use Illuminate\Foundation\AliasLoader;

    public function boot(): void
    {
        ...
        AliasLoader::getInstance([
            'AliasClass' => \Namespace\Class::class,
        ]);
        ...
    }

The alias loader is used by RegisterFacades (here is where the old app.aliases config is being read) which gets bootstraped by the Kernel. Behind de scenes ->load will call class_alias lazily, so, if you're going to always use your alias you can directly register it with class_alias.

https://github.com/laravel/framework/blob/v11.0.0/src/Illuminate/Foundation/Http/Kernel.php#L46

https://github.com/laravel/framework/blob/v11.0.0/src/Illuminate/Foundation/Bootstrap/RegisterFacades.php#L27

https://github.com/laravel/framework/blob/v11.0.0/src/Illuminate/Foundation/AliasLoader.php#L151

https://github.com/laravel/framework/blob/v11.0.0/src/Illuminate/Foundation/AliasLoader.php#L167

https://github.com/laravel/framework/blob/v11.0.0/src/Illuminate/Foundation/AliasLoader.php#L71

https://www.php.net/manual/en/function.class-alias.php