<?php2. app/Facades/Foobar.php
namespace App\Services;
class Foobar {
public function show() {
return 'Hello World';
}
}
<?php3. app/Providers/FoobarServiceProvider.php
namespace App\Facades;
use Illuminate\Support\Facades\Facade;
class Foobar extends Facade {
public static function getFacadeAccessor() {
return 'foobar';
}
}
<?php4. Now, open the file config/app.php and add the service provider to providers array:
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Services\Foobar;
class FoobarServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
$this->app->singleton('foobar', function() {
return new Foobar;
});
}
}
App\Providers\FoobarServiceProvider::class,5. Inside config/app.php add the alias of Foobar to aliases array:
'Foobar' => App\Facades\Foobar::class,6. Add the following route into routes/web.php
Route::get('/foo', function () {7. Now when you go to the '/foo' address you will get a 'Hello World' message.
return Foobar::show();
});
{Here, $name is the key (binding key like 'foobar'). This method checks for $name as an object and returns $name object. The second if condition checks if it is first time or not. if first time the last line is executed which get value from service container using $app[$name]. After the first time second if condition is true.
if (is_object($name)) {
return $name;
}
if (isset(static::$resolvedInstance[$name])) {
return static::$resolvedInstance[$name];
}
return static::$resolvedInstance[$name] = static::$app[$name];
}
Labels: Laravel, Web development