gins.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. // Package gins provides instances and core components management.
  7. package gins
  8. import (
  9. "github.com/gogf/gf/container/gmap"
  10. )
  11. var (
  12. // instances is the instance map for common used components.
  13. instances = gmap.NewStrAnyMap(true)
  14. )
  15. // Get returns the instance by given name.
  16. func Get(name string) interface{} {
  17. return instances.Get(name)
  18. }
  19. // Set sets a instance object to the instance manager with given name.
  20. func Set(name string, instance interface{}) {
  21. instances.Set(name, instance)
  22. }
  23. // GetOrSet returns the instance by name,
  24. // or set instance to the instance manager if it does not exist and returns this instance.
  25. func GetOrSet(name string, instance interface{}) interface{} {
  26. return instances.GetOrSet(name, instance)
  27. }
  28. // GetOrSetFunc returns the instance by name,
  29. // or sets instance with returned value of callback function <f> if it does not exist
  30. // and then returns this instance.
  31. func GetOrSetFunc(name string, f func() interface{}) interface{} {
  32. return instances.GetOrSetFunc(name, f)
  33. }
  34. // GetOrSetFuncLock returns the instance by name,
  35. // or sets instance with returned value of callback function <f> if it does not exist
  36. // and then returns this instance.
  37. //
  38. // GetOrSetFuncLock differs with GetOrSetFunc function is that it executes function <f>
  39. // with mutex.Lock of the hash map.
  40. func GetOrSetFuncLock(name string, f func() interface{}) interface{} {
  41. return instances.GetOrSetFuncLock(name, f)
  42. }
  43. // SetIfNotExist sets <instance> to the map if the <name> does not exist, then returns true.
  44. // It returns false if <name> exists, and <instance> would be ignored.
  45. func SetIfNotExist(name string, instance interface{}) bool {
  46. return instances.SetIfNotExist(name, instance)
  47. }