容器

    • name 定义 Bean 别名,缺省默认类名
    • scope 注入 Bean 类型,默认单例,Scope::SINGLETON/Scope::PROTOTYPE(每次创建)
    • ref 指定引用 Bean ,用于定义在接口上面,指定使用哪个接口实现。

    @Inject

    • name 定义属性注入的bean名称,缺省属性自动类型名称

    bean有两种方式定义,注解和数组配置

    • 数组中必须要有class字段定义
    • pro1/pro1 和类面的成员变量名称是一一对应
    • 属性值和构造函数参数值,都可以通过 ${xxx} 和 ${config.xx}, 注入Bean和引用properties配置信息

    注解定义

    1. /**
    2. * @\Swoft\Bean\Annotation\Bean("userData")
    3. */
    4. class XxxBean
    5. {
    6. }
    • App/ApplicationContext/BeanFactory都可从容器中得到Bean
    • hasBean 某个bean是否存在
    1. /**
    2. * @\Swoft\Bean\Annotation\Bean("userData")
    3. */
    4. class UserData
    5. {
    6. public function getData()
    7. return [];
    8. }
    9. }
    10. /**
    11. * @\Swoft\Bean\Annotation\Bean()
    12. */
    13. class UserLogic
    14. {
    15. /**
    16. * @\Swoft\Bean\Annotation\Inject("userData")
    17. */
    18. private $userData;
    19. private function getUser()
    20. {
    21. return $this->userData->getData();
    22. }
    23. }

    缺省定义

    • 接口上面指定了使用的实现bean别名
    • 接口使用处,无需指定使用那个别名,会根据接口上面的引用注入不同的实例bean

      1. /**
      2. * @\Swoft\Bean\Annotation\Bean(ref="boy")
      3. */
      4. interface UserInterface
      5. {
      6. public function getData();
      7. }
      8. /**
      9. * @\Swoft\Bean\Annotation\Bean("boy")
      10. */
      11. {
      12. public function getData()
      13. {
      14. return 'boy';
      15. }
      16. }
      17. /**
      18. * @\Swoft\Bean\Annotation\Bean("girl")
      19. */
      20. class UserGirl implements \UserInterface
      21. {
      22. public function getData()
      23. {
      24. return 'girl';
      25. }
      26. }
      27. /**
      28. * @\Swoft\Bean\Annotation\Bean()
      29. */
      30. class UserLogic
      31. {
      32. /**
      33. * @\Swoft\Bean\Annotation\Inject()
      34. * @var \UserInterface
      35. */
      36. private $userData;
      37. private function getUser()
      38. {
      39. return $this->userData->getData();
      40. }#