How to create custom facade in laravel 5.2 – onlinecode

How to create custom facade in laravel 5.2 – onlinecode

In this post we will give you information about How to create custom facade in laravel 5.2 – onlinecode. Hear we will give you detail about How to create custom facade in laravel 5.2 – onlinecodeAnd how to use it also give you demo for it if it is necessary.

How to create custom facade in laravel 5.2

Benefits of creating custom facade in Laravel 5.2 is it that you don’t have to write same function again and again, to avoid repetition you can create a helper class or can say facade class.

Facades basically provide a static interface to a class that give access to an object from the service container.

You will have to simply define single method getFacadeAccessor for a facade class.

Here you will know how to create custom facade in Laravel.

You will only need 3 things to create facade class for your application :

  • Bind class to Service Provider
  • Create facade class
  • Configuration facade alias

Step 1 – Create PHP Class File, AppHelpersGeneralClass.php

In this step, you will have to create a “Helpers” directory within app folder and create PHP class “GeneralClass.php” file within Helpers directory.

We will create this helper class to get gravatar photo/image from gravatar.com using email id.


app/Helpers/GeneralClass.php

  1. <?php
  2. namespace AppHelpers;
  3. class GeneralClass {
  4. // function to get gravatar photo/image from gravatar.com using email id.
  5. public functiongetGravatarURL($email,$s=80,$d='mm',$r='g',$img= false,$atts=array())
  6. {
  7. $url='http://www.gravatar.com/avatar/';
  8. $url.=md5(strtolower(trim($email)));
  9. $url.="?s=$s&d=$d&r=$r";
  10. if($img)
  11. {
  12. $url='<img src="'.$url.'"';
  13. foreach($attsas$key=>$val)
  14. $url.=' '.$key.'="'.$val.'"';
  15. $url.=' />';
  16. }
  17. return$url;
  18. }
  19. }
<?php
namespace AppHelpers;
class GeneralClass {
     // function to get gravatar photo/image from gravatar.com using email id.
    public function getGravatarURL($email, $s = 80, $d = 'mm', $r = 'g', $img = false, $atts = array())
    {
        $url = 'http://www.gravatar.com/avatar/';
        $url .= md5(strtolower(trim($email)));
        $url .= "?s=$s&d=$d&r=$r";
        if ($img)
        {
            $url = '<img src="' . $url . '"';
            foreach ($atts as $key => $val)
                $url .= ' ' . $key . '="' . $val . '"';
            $url .= ' />';
        }
        return $url;
    }
}


Step 2:Bind Class to ServiceProvider

In this step we will create new service provider to bind class.

Execute this command in your terminal :

php artisan make:provider 'GeneralClassServiceProvider'

After running this command you will get message of ‘Provider created successfully’ and new provider file is generated within Providers directory.


app/Providers/GeneralClassServiceProvider.php

  1. <?php
  2. namespace AppProviders;
  3. use IlluminateSupportFacadesApp;
  4. use IlluminateSupportServiceProvider;
  5. class GeneralClassServiceProvider extends ServiceProvider
  6. {
  7. /**
  8. * Bootstrap the application services.
  9. *
  10. * @return void
  11. */
  12. public functionboot()
  13. {
  14. //
  15. }
  16. /**
  17. * Register the application services.
  18. *
  19. * @return void
  20. */
  21. public functionregister()
  22. {
  23. App::bind('generalclass',function()
  24. {
  25. returnnewAppHelpersGeneralClass;
  26. });
  27. }
  28. }
<?php
namespace AppProviders;
use IlluminateSupportFacadesApp;
use IlluminateSupportServiceProvider;

class GeneralClassServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        App::bind('generalclass', function()
        {
            return new AppHelpersGeneralClass;
        });
    }
}


Step 3: Register this ServiceProvider to providers array

In this step we will register the newly generated service provider to provider array in following path Configapp.php.

AppProvidersGeneralClassServiceProvider::class


Step 4: Create facade Class

In this step we will create a directory first where all custom facade class will be created and all custom facade must extends to IlluminateSupportFacadesFacade.

So create Facades directory within app directory and then create your facade class within this directory.


app/Facades/GeneralClass.php

  1. <?php
  2. namespace AppFacades;
  3. use IlluminateSupportFacadesFacade;
  4. class GeneralClass extends Facade{
  5. protected staticfunctiongetFacadeAccessor(){return'generalclass';}
  6. }
<?php
namespace AppFacades;
use IlluminateSupportFacadesFacade;
class GeneralClass extends Facade{
    protected static function getFacadeAccessor() { return 'generalclass'; }
}


Step 5: Register this ServiceProvider to providers array

In this step we will add aliases for this facade class in aliases array in following path Configapp.php

'GeneralClass'=> AppFacadesGeneralClass::class

Now finally you will run composer dump-autoload command to load custom folder and files.

Now you have created a custom facade for your application, you can check, It works or not by following code which i write in routes.php.

  1. Route::get('/',function(){
  2. $img='<img src="'.GeneralClass::getGravatarURL('ajay.agrahari09@gmail.com').'">';
  3. echo$img;
  4. });
Route::get('/', function(){
    $img='<img src="'.GeneralClass::getGravatarURL('ajay.agrahari09@gmail.com').'">';
    echo $img;   
});

You can now try this code in your application to create custom facade in Laravel 5.

Hope this code and post will helped you for implement How to create custom facade in laravel 5.2 – onlinecode. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

Leave a Comment

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

5  +  2  =  

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US