laravel, php, Uncategorized

Custom Facades in Laravel 4.2.X


// file System

Untitled

 

 

 

 

 

 

 

 

 

 




Name of Custom Facade "Sky"

steps:

1. create a new folder facades inside app folder

2. create a new folder same name as of your custom facade name. [ eg: app/facades/Sky / ]

3 create one more folder inside app / [ your facade folder ] / Facade

4. now create 2 files in the your facade base

app/facades/Sky/
              / Helper.php
              / HelperServiceProvider.php

5. a facade class inside a
app/facades/Sky/Facade/
                     /Helper.php

=============== Contents inside files =================
## app/facades/Sky/Helper.php

namespace Sky;
Class Helper {

	public function fire()
	{
		return 'Fireing ... ';
	}

	public function boom()
	{
		return 'Fireing boom... ';
	}
}

## app/facades/Sky/HelperServiceProvider.php

namespace Sky;
use Illuminate\Support\ServiceProvider;

class HelperServiceProvider extends ServiceProvider {



    public function register()
    {
        // Registering 'helper class'
        $this->app['helper'] = $this->app->share(function($app)
        {
            return new Sky\Helper;
        });

        // dynamic creating Alias, so that you do not have to add an Alias in app/config/app.php
        $this->app->booting(function()
        {
            $loader = \Illuminate\Foundation\AliasLoader::getInstance();
            $loader->alias('SkyHelper', 'Sky\Facade\Helper');
        });
    }

}
?>
## app/facades/Sky/Facade/Helper.php

namespace Sky\Facade;

use Illuminate\Support\Facades\Facade;

class Helper extends Facade {

    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor() { return 'Sky\Helper'; }

}

### this is it all you need for your custom facades ##########

### one more last thing you need to do for autoload the facade classes ####
# GO to composer.json, add new line app/facades for autoloading.

"autoload": {
		"classmap": [
			"app/commands",
			"app/controllers",
			"app/models",
			"app/database/migrations",
			"app/database/seeds",
			"app/facades",
			"app/tests/TestCase.php"
		]
	},

finally RUN " composer dump-autoload "

Cheers enjoy
Advertisements