【问题标题】:How to extend Laravel Storage facade?如何扩展 Laravel Storage 门面?
【发布时间】:2017-03-12 06:00:06
【问题描述】:

在不知道 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:方法磁盘不存在。

【问题讨论】:

    标签: php laravel laravel-5 laravel-facade


    【解决方案1】:

    您的 MyStorage 类需要扩展 FilesystemManager 而不是 Storage 外观类。

    class MyStorage extends \Illuminate\Filesystem\FilesystemManager {
        ....
    }
    

    【讨论】:

      【解决方案2】:

      外观只是一个便利类,它将静态调用Facade::method 转换为resolove("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. 
      

      【讨论】:

      • 正如我所提到的,我已经对其进行了测试并得到了这个错误:BadMethodCallException in Macroable.php line 74: Method disk does not exist.
      • @Omid disk 并没有真正定义在任何地方。
      • 那么\Storage::disk('local') 在这种情况下是如何工作的? @apokryfos
      • 我认为这是绑定到 FilesystemManager 类而不是 FileSystem 类。更新了代码。
      • 你是对的,它现在正在工作。然而,奇怪的是外观访问器返回filesystem。 @apokryfos
      猜你喜欢
      • 1970-01-01
      • 2017-10-21
      • 2015-05-11
      • 1970-01-01
      • 2017-05-29
      • 2021-11-11
      • 2023-04-11
      • 1970-01-01
      相关资源
      最近更新 更多