用惯了Laravel
的Ioc
,对象获取变得那么天然,初用Go
,各struct
,func
都要本身解析
一堆NewFunc
,索性本身搞了个ioc
参见Github(https://github.com/firmeve/firmeve)git
f := NewFirmeve()
f.Bind(`bool`, false)
f.Bind(`string`, "string")
Struct
绑定假设咱们有以下struct
github
type Foo struct { Bar string } func NewFoo(bar string) Foo{ return Foo{Bar:bar} }
咱们将foo
绑定进咱们的容器中函数
f.Bind(`foo`,NewFoo("abc"))
Prt
绑定绑定prt
的struct
类型是咱们最经常使用的一种方式,请看下面的示例\指针
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))
如今,让咱们修改下上面的Person
string
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
不符合struct
的tag
规范,因此Firmeve
都会自动忽略。