Creating aliases for your classes in Laravel 5

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' => IlluminateSupportFacadesApp::class,
'Artisan' => IlluminateSupportFacadesArtisan::class,
'Auth' => IlluminateSupportFacadesAuth::class,
'Blade' => IlluminateSupportFacadesBlade::class,
'Broadcast' => IlluminateSupportFacadesBroadcast::class,
'Bus' => IlluminateSupportFacadesBus::class,
'Cache' => IlluminateSupportFacadesCache::class,
'Config' => IlluminateSupportFacadesConfig::class,
'Cookie' => IlluminateSupportFacadesCookie::class,
'Crypt' => IlluminateSupportFacadesCrypt::class,
'DB' => IlluminateSupportFacadesDB::class,
'Eloquent' => IlluminateDatabaseEloquentModel::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'=> IlluminateSupportFacadesApp::class,
'Artisan'=> IlluminateSupportFacadesArtisan::class,
'Auth'=> IlluminateSupportFacadesAuth::class,
'Blade'=> IlluminateSupportFacadesBlade::class,
'Broadcast'=> IlluminateSupportFacadesBroadcast::class,
'Config' => IlluminateSupportFacadesConfig::class,
'Cookie' => IlluminateSupportFacadesCookie::class,
'Crypt' => IlluminateSupportFacadesCrypt::class,
'DB' => IlluminateSupportFacadesDB::class,
'Eloquent' => IlluminateDatabaseEloquentModel::class,
........
'HelloWorld'=> YourPackageNamespaceHelloWorld: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'=> YourPackageNamespaceHelloWorldFacade:class,
]

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

Leave a Reply

Your email address will not be published. Required fields are marked *