首页 文章

如何扩展Laravel Storage外观?

提问于
浏览
2

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

I have this code:

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

While booting service provider:

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

And facade is:

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

When using it:

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

I get this error:

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

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

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

2 回答

  • 2

    您的 MyStorage 类需要扩展 FilesystemManager 而不是Storage facade类 .

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

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

    门面:

    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.
    

相关问题