在Laravel中使用静态方法的门面与类的区别

问题描述 投票:0回答:1

我看了一下Laravel框架和他们的一些产品,我注意到Cashier是用静态方法的Casheir类与Socialite相比,它是作为一个门面使用的。

我想自己建立一些东西, 但我不想开始建立一个有静态方法的类, 如果建立它作为一个门面是一个更好的解决方案.

laravel class static package facade
1个回答
1
投票

当你可能需要多个实现的时候,可以通过门面定义一个接口来简化代码。

把它构建成一个具有静态方法的类。

当你有多个类的时候,你必须做这样的事情。

CashierOne::method, CashierTwo::method ....

用来作为一个门面:

根据你绑定到容器上的东西来切换实现你只需要通过一个接口来调用。

// Define a Cashier Facade
class Cashier extends Facade
{
    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor()
    {
        return 'cashier';
    }
}

// In CashServiceProvider
$this->app->singleton('cashier', function ($app) {
    return new CashierManager ($app);
});

// In CashierManager
public function gateway($name = null)
{
    // get cashier implementation by name
}

public function __call($method, $parameters)
{
    return $this->gateway()->$method(...$parameters);
}

// In Controller
Cashier::method

另外,这个门面更容易测试、检查。

https:/laravel.comdocs5.8facades#how-facades-work

© www.soinside.com 2019 - 2024. All rights reserved.