It returns the key for resolving the implementation out of the container. It is empty in the parent because it is (i) a needed method which will be called and (ii) must be implemented in the child classes
What is getFacadeAccessor() ? Why we called it ?
Hey genius,
I watched this video - https://www.youtube.com/watch?v=zD2VJhOdI5c&ab_channel=Bitfumes
actually i cannot understand this function
getFacadeAccessor()
why its empty ?
<?php
class Fish{
public function swim(){
return "Swimming";
}
public function eat(){
return "Eating";
}
}
class Bike{
public function start(){
return "starting";
}
}
app()->bind('fish',function(){
return new Fish();
});
app()->bind('bike',function(){
return new bike();
});
class Facade{
public static function __callStatic($name, $arguments)
{
return app()->make(static::getFacadeAccessor())->$name();
}
protected static function getFacadeAccessor(){
}
}
class BikeFacade extends Facade{
protected static function getFacadeAccessor(){
return 'bike';
}
}
class FishFacade extends Facade{
protected static function getFacadeAccessor(){
return 'fish';
}
}
dd(FishFacade::swim());
@abiman What do you mean, it’s empty? As I’m not watching a 14-minute video.
The getFacadeAccessor method should return the key in the container the facade is a, well, facade for. Each custom facade class you create should implement this method and return a container binding key.
So if you bind this in the container:
$this->app->singleton(PaymentGatewayContract::class, function () {
return new StripePaymentGateway($this->app['config']['services.stripe.secret']);
});
Then you could create a PaymentGateway facade that looks like this:
class PaymentGateway extends Facade
{
protected static function getFacadeAccessor()
{
return PaymentGatewayContract::class;
}
}
So now, any time you call a method on your PaymentGateway facade, the facade will look at the getFacadeAccessor class, realise you’re referring to whatever is bound to the container using the key PaymentGatewayContract, and pass calls on to that object:
// Will actually call StripePaymentGateway::charge(100) under the hood
$charge = PaymentGateway::charge(100);
Facades also have built-in mocking, so you can leverage that in tests:
PaymentGateway::shouldReceive('charge')->once()->with(100);
// A controller that uses PaymentGateway facade
$this
->actingAs($user)
->postJson('/api/charges', ['amount' => 100])
->assertCreated();
Please or to participate in this conversation.