2

在不知道 Laravel 外观如何工作的情况下,基于我的 PHP 知识,我尝试扩展 Storage 外观以添加一些新功能。

我有这个代码:

class MyStorageFacade extends Facade {
    /**
     * Get the binding in the IoC container
     *
     * @return string
     */
    protected static function getFacadeAccessor()
    {
        return 'MyStorage'; // the IoC binding.
    }
}

启动服务提供商时:

$this->app->bind('MyStorage',function($app){
    return new MyStorage($app);
});

门面是:

class MyStorage extends \Illuminate\Support\Facades\Storage{
}

使用时:

use Namespace\MyStorage\MyStorageFacade as MyStorage;
MyStorage::disk('local');

我收到此错误:

Facade.php 第 237 行中的 FatalThrowableError:调用未定义的方法 Namespace\MyStorage\MyStorage::disk()

尝试扩展MyStorage表单Illuminate\Filesystem\Filesystem并以其他方式得到相同的错误:

Macroable.php 第 74 行中的 BadMethodCallException:方法磁盘不存在。

4

2 回答 2

3

您的MyStorage类需要扩展FilesystemManager而不是 Storage 门面类。

class MyStorage extends \Illuminate\Filesystem\FilesystemManager {
    ....
}
于 2017-03-12T06:29:51.987 回答
1

外观只是一个方便类,它将静态调用转换Facade::methodresolove("binding")->method(或多或少)。您需要从 Filesystem 扩展,在 IoC 中注册,保持外观不变,并将外观用作静态。

门面:

class MyStorageFacade extends Facade {      
    protected static function getFacadeAccessor()
    {
        return 'MyStorage'; // This one is fine
    }
}

您的自定义存储类:

class MyStorage extends Illuminate\Filesystem\FilesystemManager {
}

在任何服务提供商(例如AppServiceProvider

$this->app->bind('MyStorage',function($app){
   return new MyStorage($app);
});

然后,当您需要使用它时,将其用作:

MyStorageFacade::disk(); //Should work. 
于 2017-03-12T06:07:34.660 回答