github.com/goravel/framework@v1.13.9/cache/driver.go (about)

     1  package cache
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/goravel/framework/contracts/cache"
     7  	"github.com/goravel/framework/contracts/config"
     8  )
     9  
    10  //go:generate mockery --name=Driver
    11  type Driver interface {
    12  	New(store string) (cache.Driver, error)
    13  }
    14  
    15  type DriverImpl struct {
    16  	config config.Config
    17  }
    18  
    19  func NewDriverImpl(config config.Config) *DriverImpl {
    20  	return &DriverImpl{
    21  		config: config,
    22  	}
    23  }
    24  
    25  func (d *DriverImpl) New(store string) (cache.Driver, error) {
    26  	driver := d.config.GetString(fmt.Sprintf("cache.stores.%s.driver", store))
    27  	switch driver {
    28  	case "memory":
    29  		return d.memory()
    30  	case "custom":
    31  		return d.custom(store)
    32  	default:
    33  		return nil, fmt.Errorf("invalid driver: %s, only support memory, custom\n", driver)
    34  	}
    35  }
    36  
    37  func (d *DriverImpl) memory() (cache.Driver, error) {
    38  	memory, err := NewMemory(d.config)
    39  	if err != nil {
    40  		return nil, fmt.Errorf("init memory driver error: %v", err)
    41  	}
    42  
    43  	return memory, nil
    44  }
    45  
    46  func (d *DriverImpl) custom(store string) (cache.Driver, error) {
    47  	if custom, ok := d.config.Get(fmt.Sprintf("cache.stores.%s.via", store)).(cache.Driver); ok {
    48  		return custom, nil
    49  	}
    50  	if custom, ok := d.config.Get(fmt.Sprintf("cache.stores.%s.via", store)).(func() (cache.Driver, error)); ok {
    51  		return custom()
    52  	}
    53  
    54  	return nil, fmt.Errorf("%s doesn't implement contracts/cache/store\n", store)
    55  }