godif

package module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 27, 2019 License: MIT Imports: 4 Imported by: 10

README

godif

Go dependency injection for functions (and not only...)

Usage

Provide key-value

  • Declare: var MyMap map[string]int
  • Implement
    • Manually: MyMap = map[string]int{}
      • godif.Provide(&MyMap, map[string]int{}) -> Implementation provided for non-nil error
    • Provide implementation: godif.Provide(&MyMap, map[string]int{})
    • No implementation -> error
  • Provide data: godif.ProvideKeyValue(&MyMap, "key1", 1)
  • Multiple values per key error:
    • godif.ProvideKeyValue(&MyMap, "key1", 1)
    • godif.ProvideKeyValue(&MyMap, "key1", 2)
  • Incompatible types error:
    • godif.ProvideKeyValue(&MyMap, "key1", "str")

Provide key-slice

  • Declare: var MyMap map[string][]int
  • Implement
    • Manually: MyMap = map[string][]int{}
      • godif.Provide(&MyMap, map[string][]int{}) -> Implementation provided for non-nil error
    • Provide implementation: godif.Provide(&MyMap, map[string][]int{})
    • No implementation -> error
  • Add initial data if needed: MyMap["key1"] = append(MyMap["key1"], 42)
    • Further godif.ProvideKeyValue() calls will append data to the existing slice
  • Provide data:
    • godif.ProvideKeyValue(&MyMap, "key1", 1)
    • godif.ProvideKeyValue(&MyMap, "key1", 2)
    • godif.ProvideKeyValue(&MyMap, "key1", []int{3, 4})
  • Incompatible types error:
    • godif.ProvideKeyValue(&MyMap, "key1", "str")

Provide slice element

  • Declare: var MySlice []string
  • Implement: godif.Provide(&MySlice, []string{})
  • Implement
    • Manually: MySlice = []string{}
      • godif.Provide(&MySlice, []string{}) -> Implementation provided for non-nil error
    • Provide implementation: godif.Provide(&MySlice, []string{})
    • No implementation -> Implementation not provided error
  • Add initial data if needed: MySlice = append(MySlice, 42)
    • Further godif.ProvideSliceElement() calls will append data to the existing slice
  • Provide data:
    • godif.ProvideSliceElement(&MySlice, "str1")
    • godif.ProvideSliceElement(&MySlice, []string{"str3", "str4"})

Reset all injections

  • godif.Reset()
  • Provided vars will be nilled
  • Manually inited vars will be kept
  • Data injected into manually inited vars will be kept

Usage Example

Imagine we have a functional interface to work with key-value database. Database has two methods - Put and Get. These methods works with BucketDef.

The following example shows how to:

  1. Declare functional interface
  2. Implement (provide) functions
  3. Use functional interface

1. Declare

package ikvdb

import "context"

// Put saves given key and value to some persistent storage
var Put func(ctx context.Context, bucket *BucketDef, key interface{}, value interface{})

// Get gets the value from some persistent storage
var Get func(ctx context.Context, bucket *BucketDef, key interface{}) (value interface{}, ok bool)

// BucketDef defines the bucket
type BucketDef struct {
	Key string
}

// BucketDefs keeps list of BucketDef
var BucketDefs map[string]*BucketDef

Package declares variables of certain types, these variablesmust be furher provided.

2. Provide


package kvdb

// Declare provides Get/Put functions and map of BucketDef
func Declare() {
	godif.Provide(&ikvdb.Get, Get)
	godif.Provide(&ikvdb.Put, Put)
	godif.Provide(&ikvdb.BucketDefs, map[string]*ikvdb.BucketDef{})
}

var buckets = map[string]map[interface{}]interface{}{}

// Get implements ikvdb.Get
func Get(ctx context.Context, bucket *ikvdb.BucketDef, key interface{}) (value interface{}, ok bool) {
	kv, ok := buckets[bucket.Key]
	if !ok {
		log.Panicln("Bucket not found", bucket.Key)
	}
	val, ok := kv[key]
	return val, ok
}

// Put implements ikvdb.Put
func Put(ctx context.Context, bucket *ikvdb.BucketDef, key interface{}, value interface{}) {
	kv, ok := buckets[bucket.Key]
	if !ok {
		log.Panicln("Bucket not found", bucket.Key)
	}
	kv[key] = value
}

3. Use

package service

var bucketService = &ikvdb.BucketDef{Key: "service"}

// Declare requires Put function and provides `bucketService` definition
func Declare() {
	godif.Require(&ikvdb.Put)
	godif.ProvideExtension(&ikvdb.BucketDefs, bucketService.Key, bucketService)
}

type ctxKey string

// CtxUserName denotes user name
var CtxUserName = ctxKey("UserName")

// Start something
func Start(ctx context.Context) {
	user := ctx.Value(CtxUserName)
	ikvdb.Put(ctx, bucketService, "startedTime", time.Now())
	ikvdb.Put(ctx, bucketService, "startedBy", user)
}

4. Build App

func main() {
	kvdb.Declare()
	service.Declare()

	errs := godif.ResolveAll()
	if len(errs) != 0 {
		// Non-assignalble Requirements
		// Unresolved dependencies
		// Multiple provisions
		log.Panic(errs)
	}

	ctx := context.WithValue(context.Background(), service.CtxUserName, "Peter")
	service.Start(ctx)
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Provide

func Provide(ref interface{}, funcImplementation interface{})

Provide registers implementation of ref type

func ProvideKeyValue added in v0.2.0

func ProvideKeyValue(pointerToMap interface{}, key interface{}, value interface{})

ProvideKeyValue s.e.

func ProvideSliceElement added in v0.2.0

func ProvideSliceElement(pointerToSlice interface{}, element interface{})

ProvideSliceElement s.e.

func Require

func Require(toInject interface{})

Require registers dep

func Reset

func Reset()

Reset clears all assignations

Types

type EAlreadyResolved added in v0.2.0

type EAlreadyResolved struct {
	// contains filtered or unexported fields
}

EAlreadyResolved occurs on ResolveAll() call if it called already

func (*EAlreadyResolved) Error added in v0.2.0

func (e *EAlreadyResolved) Error() string

type EImplementationNotProvided

type EImplementationNotProvided struct {
	// contains filtered or unexported fields
}

EImplementationNotProvided error occurs if there is no implementation provided for a type

func (*EImplementationNotProvided) Error

type EImplementationProvidedForNonNil added in v0.2.0

type EImplementationProvidedForNonNil struct {
	// contains filtered or unexported fields
}

EImplementationProvidedForNonNil error occurs if target value is not nil but implementation provided

func (*EImplementationProvidedForNonNil) Error added in v0.2.0

type EIncompatibleTypesFunc added in v0.2.0

type EIncompatibleTypesFunc struct {
	// contains filtered or unexported fields
}

EIncompatibleTypesFunc error occurs if type of a requirement (func) is incompatible to provided implementation

func (*EIncompatibleTypesFunc) Error added in v0.2.0

func (e *EIncompatibleTypesFunc) Error() string

type EIncompatibleTypesSlice added in v0.2.0

type EIncompatibleTypesSlice struct {
	// contains filtered or unexported fields
}

EIncompatibleTypesSlice error occurs if type of a requirement (array or slice) is incompatible to provided implementation

func (*EIncompatibleTypesSlice) Error added in v0.2.0

func (e *EIncompatibleTypesSlice) Error() string

type EMultipleImplementations

type EMultipleImplementations struct {
	// contains filtered or unexported fields
}

EMultipleImplementations occurs if there are more than one provided implementation for one type

func (*EMultipleImplementations) Error

func (e *EMultipleImplementations) Error() string

type EMultipleValues

type EMultipleValues struct {
	// contains filtered or unexported fields
}

EMultipleValues error occurs if more than one value is provided per one key by ProvideMapValue() call

func (*EMultipleValues) Error

func (e *EMultipleValues) Error() string

type ENonAssignableRequirement

type ENonAssignableRequirement struct {
	// contains filtered or unexported fields
}

ENonAssignableRequirement error occurs if non-assignable (e.g. not variable) requirement is declared

func (*ENonAssignableRequirement) Error

func (e *ENonAssignableRequirement) Error() string

type EProvidedNotUsed

type EProvidedNotUsed struct {
	// contains filtered or unexported fields
}

EProvidedNotUsed error occurs if something is provided but not required

func (*EProvidedNotUsed) Error

func (e *EProvidedNotUsed) Error() string

type Errors

type Errors []error

Errors is multiple errors container

func ResolveAll

func ResolveAll() Errors

ResolveAll all deps

func (Errors) Error

func (e Errors) Error() string

Directories

Path Synopsis
examples
README command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL