golang Ioc

简介

用惯了LaravelIoc,对象获取变得那么天然,初用Go,各struct,func都要本身解析
一堆NewFunc,索性本身搞了个ioc
参见Github(https://github.com/firmeve/firmeve)git

对象绑定

f := NewFirmeve()

标量绑定

f.Bind(`bool`, false)
f.Bind(`string`, "string")

Struct 绑定

假设咱们有以下structgithub

type Foo struct {
    Bar string 
}

func NewFoo(bar string) Foo{
    return Foo{Bar:bar}
}

咱们将foo绑定进咱们的容器中函数

f.Bind(`foo`,NewFoo("abc"))

Prt 绑定

绑定prtstruct类型是咱们最经常使用的一种方式,请看下面的示例\指针

type Baz struct {
    Baz string 
}

func NewBaz() *Baz {
   return &Baz{}
}

f.Bind(`baz`, NewBaz())

函数绑定

func NewFoo() Foo{
   return Foo{Bar:"default string"}
}

f.Bind(`foo`, NewFoo)
使用 Firmeve在绑定的时候暂时不支持参数注入
注意:若是是非函数类型绑定,则会默认为单实例类型

已绑定值覆盖

咱们经过WithBindCover(true)方法能够轻松设定覆盖参数code

f.Bind(`bool`, false)
fmt.Printf("%t",f.Get(`bool`))
f.Bind(`bool`, true, WithBindCover(true))
fmt.Printf("%t",f.Get(`bool`))

对象获取

验证对象是否存在

在不肯定容器中是否包含此对象时,请使用Has方法进行判断对象

f.Has(`foo`)

对象获取

直接获取容器中的值blog

f.Get(`foo`)
注意:若是指的定的 key不存在,则会抛出 panic错误

新对象获取

func NewFoo() Foo{
   return Foo{Bar:"default string"}
}

f.Bind(`foo`, NewFoo)
fmt.Printf("%p\n",f.Get("foo"))
fmt.Printf("%p\n",f.Get("foo"))
fmt.Printf("%p\n",f.Get("foo"))
Firmeve中,若是须要每次从新获得一个新的结构体对象
必须绑定一个函数值,不然获得的将是一个单实例

单例获取

func NewFoo() Foo{
   return Foo{Bar:"default string"}
}

f.Bind(`foo`, NewFoo())
fmt.Printf("%p\n",f.Get("foo"))
fmt.Printf("%p\n",f.Get("foo"))
fmt.Printf("%p\n",f.Get("foo"))

参数解析

函数自动解析

让咱们来看一个简单的示例get

type PersonName struct {
   Name string
}

func NewPersonName() PersonName {
   return PersonName{Name: "Firmeve"}
}

type PersonAge struct {
   Age int
}

func PersonAge() *PersonAge {
   return &PersonAge{Age: 1}
}

type Person struct {
   name PersonName
   age *PersonAge
}

func NewPerson(name PersonName,age *PersonAge) *NewPerson {
    return NewPerson{
       name: name
       age: age
    }
}

f.Bind("PersonName", NewPersonName)
f.Bind("PersonAge", PersonAge)
fmt.Printf("%#v", f.Resolve(NewPerson))

结构体tag自动解析

如今,让咱们修改下上面的Personstring

type Person struct {
   Name PersonName `inject:"PersonName"`
   Age *PersonAge `inject:"PersonAge"`
   age1 *PersonAge `inject:"PersonAge"`
}

而后咱们使用new函数直接建立一个新的结构体指针it

fmt.Printf("%#v", new(NewPerson))
注意:此时 Person中的 Name字段并非指针类型,而 age1不符合 structtag规范,因此 Firmeve都会自动忽略。

来源:https://blog.crcms.cn/2019/09...

相关文章
相关标签/搜索