Creating aliases for your classes in Laravel 5

Share:
Creating aliases for your classes in Laravel 5

In this post we are going to read about Laravel Class Alias feature.

You might have heard of Laravel Class Alias feature. If you haven’t, here’s a brief description about them. Laravel comes with a feature called, Class Alias, using which you can create an alias for any class you have created. If you look into the app.php file inside the config folder of any Laravel installation, you will see an array at the bottom of the file named aliases which contains an array of Aliases as keys and your Namespaced Classes as values.
'aliases' => [
        'App' => Illuminate\Support\Facades\App::class,
        'Artisan' => Illuminate\Support\Facades\Artisan::class,
        'Auth' => Illuminate\Support\Facades\Auth::class,
        'Blade' => Illuminate\Support\Facades\Blade::class,
        'Broadcast' => Illuminate\Support\Facades\Broadcast::class,
        'Bus' => Illuminate\Support\Facades\Bus::class,
        'Cache' => Illuminate\Support\Facades\Cache::class,
        'Config' => Illuminate\Support\Facades\Config::class,
        'Cookie' => Illuminate\Support\Facades\Cookie::class,
        'Crypt' => Illuminate\Support\Facades\Crypt::class,
        'DB' => Illuminate\Support\Facades\DB::class,
        'Eloquent' => Illuminate\Database\Eloquent\Model::class,
         ........
]
Now, using this feature, whenever you want to reference your class anywhere in your project, you have to just call the alias and not the whole Namespaced ClassName. For example, if you have a class named HelloWorld in your Package, then you can add an alias for your class just like the example given below.
'aliases' => [

        'App'=> Illuminate\Support\Facades\App::class,
        'Artisan'=> Illuminate\Support\Facades\Artisan::class,
        'Auth'=> Illuminate\Support\Facades\Auth::class,
        'Blade'=> Illuminate\Support\Facades\Blade::class,
        'Broadcast'=> Illuminate\Support\Facades\Broadcast::class,
        'Config' => Illuminate\Support\Facades\Config::class,
        'Cookie' => Illuminate\Support\Facades\Cookie::class,
        'Crypt' => Illuminate\Support\Facades\Crypt::class,
        'DB' => Illuminate\Support\Facades\DB::class,
        'Eloquent' => Illuminate\Database\Eloquent\Model::class,
        ........
        'HelloWorld'=> YourPackage\Namespace\HelloWorld:class 
]
Now, Keep in mind that if you want to use any function from your class, it has to be a static function. As you can see, the aliases already defined in Laravel refer to Facades. In Laravel, Facades provides a static way to use instantiated classes. If you want to alias an instance of your class, you have to first define a facade for your class.
'aliases' => [
        ........
        'HelloWorld'=> YourPackage\Namespace\HelloWorldFacade:class, 
]

Article source(https://programmersedge.wordpress.com/2017/05/30/create-aliases-for-your-classes-in-larvel/)

No comments