• prototype
    • 原型模式
    • 如何使用

    prototype

    prototype 用的是原型模式, 它会被框架启动时会被自动初始化.

    原型模式

    获取 scoreprototype类型的bean每次都是克隆初始化的bean好的。

    clone 一个对象 比 重新new一个对象更快, 因为它是拷贝操作。

    swoft 中 DB 的collection 就是用的prototype类型

    如何使用

    你可以定义一个 new 方法,替代new关键字

    比如Db使用的Collection Prototype

    实体都是 prototype,类型的bean,所有实体都可以使用new方法。

    1. <?php declare(strict_types=1);
    2. namespace Swoft\Test;
    3. use Swoft\Bean\Annotation\Mapping\Bean;
    4. use Swoft\Bean\Concern\PrototypeTrait;
    5. /**
    6. * Class TestCollection
    7. *
    8. * @Bean(scope=Bean::PROTOTYPE)
    9. *
    10. * @since 2.0
    11. */
    12. class TestCollection
    13. {
    14. use PrototypeTrait;
    15. /**
    16. * @var array
    17. */
    18. private $items;
    19. /**
    20. * Create a new collection.
    21. *
    22. * @param array $items
    23. *
    24. * @return static
    25. */
    26. public static function new(array $items = []): self
    27. {
    28. $self = self::__instance();
    29. $self->items = $items;
    30. return $self;
    31. }
    32. }

    需要引入PrototypeTrait,在PrototypeTrait 中实现了 __instance()方法,该返回的就是一个 clone 的自身对象,你只需更新参数 即可获取一个全新的对象。