Bean

A Bean Swoft is an object instance of a class. A container is a huge factory for storing and managing the Bean 生命周期 .

Create a bean

Create a bean

  • Direct way to define annotations [@Bean](#@Bean())
  • By configuring it in bean.php ,
  • Defined in AutoLoader.php

@Bean()

 <?php declare(strict_types=1);

namespace SwoftTest\Bean\Testing\Definition;

use Swoft\Bean\Annotation\Mapping\Bean;

/**
 * Class PrototypeClass
 *
 * @since 2.0
 *
 * @Bean(name="prototype", scope=Bean::PROTOTYPE, alias="pro")
 */
class PrototypeClass
{
    // ....
} 
  • Scope

  • Name specifies a name for the bean. Sometimes you may only need to configure a name to write @Bean("xxx") so that the default is the name of the parameter.

  • Alias specifies an alias for the bean, you can get it by alias

@Bean defined in the initialization time if there is a 构造函数 need to inject parameters to the 默认值 , and then through the configuration of the required parameters of the overlay constructor

Scope injection bean type, default singleton

Create a bean in the bean.php configuration file

For example, the following example, I will use the configuration file to add it to the Bean.

 <?php declare(strict_types=1);

namespace SwoftTest\Bean\Testing\Definition;

/**
 * TestBean
 *
 * @since 2.0
 */
class TestBean
{

    /**
     * @var SingletonClass
     */
    private $singleton;

     /**
     * @var \JWT
     */
    private $jwt;

    /**
     * TestBean constructor.
     *
     * @param SingletonClass $singleton
     */
    public function __construct(SingletonClass $singleton = null)
    {
        $this->singleton = $singleton;
    }
} 

How the configuration mode specifies the class

  'testBean'     => [
     'class'    => TestBean::class,
     [\bean('singleton')],
     'jwt'      => \bean('jwt'),
     '__option' => [
         'scope' => Bean::PROTOTYPE,
         'alias' => 'testBean-alias'
     ]
 ], 

testBean key you can understand is the name of a Bean .

  • Which class is used by the specified Bean class parameter
  • The array [\bean('singleton')], is a parameter required by the TestBean class constructor. Construct injection is not recommended. Please use @Inject
  • __option This swoft comes with you can specify:
    • Scope specifies which level the Bean is used, if there is no default 单例模式
    • Alias specifies the alias of the Bean

Swoft's constructor does not automatically cast injections

Of course you can also inject 自己定义的属性 such as:

  • This is above jwt TestBean class attributes defined by the bottom will be 反射 injection config parameters

The Bean configured through the configuration file has the 最高 priority because it is executed last. If the configuration is already a Bean , the configuration of config will overwrite it.

Defined in AutoLoader.php

 <?php declare(strict_types=1);

namespace App;

use Swoft\Db\Database;
use Swoft\SwoftComponent;

/**
 * Class AutoLoader
 *
 * @since 2.0
 */
class AutoLoader extends SwoftComponent
{
    /**
     * @return array
     */
    public function getPrefixDirs(): array
    {
        return [
            __NAMESPACE__ => __DIR__,
        ];
    }

    /**
     * @return array
     */
    public function metadata(): array
    {
        return [];
    }

    /**
     * 使用 beans 方法 和在 bean.php 中配置的一样的使用方式,它的优先级在bean.php定义的 bean 之下
     *    
     * @return array
     */
    public function beans(): array
    {
        return [
            'db' => [
                'class'    => Database::class,
                'dsn'      => 'mysql:dbname=test;host=172.17.0.4',
                'username' => 'root',
                'password' => 'swoft123456',
            ],
        ];
    }
} 

Bean initialization

Every time the Bean initialized, it will automatically check if the init() method exists.

Will be called after the Bean initialized, you can perform some initialization operations in this method, similar to the init method in golang .

Get Bean

@Inject

score is Bean::SINGLETON level bean can @Inject property injection, automatically injected into the bottom by reflection properties.

Bean::PROTOTYPE , Bean::REQUEST bean cannot be injected using @Inject

 /**
 * @Inject("config")
 *
 * @var Config
 */
private $config; 
  • Name defines the bean name injected by the property. If name is empty, the default is the type defined by @var . This name can be a full class name or a bean别名/bean名称 .

    If @Inject does not specify a bean name, it will automatically look up the bean based on the type of @var

Tips: If you want to use the @Inject property injection, you must have 类注解 , otherwise it will not be parsed.

BeanFactory

BeanFactory provides an advanced configuration mechanism to manage any kind of bean.

Get the score as Bean::SINGLETON , Bean::PROTOTYPE

You can use the following to get wsRouter as an example:

 /** @var Router $router */
$router = Swoft::getBean('wsRouter');
$router = BeanFactory::getBean('wsRouter');
$router = Container::$instance->get('wsRouter')
$router = BeanFactory::getContainer()->get('wsRouter') 

Above you can get this in several ways Bean::SINGLETON or Bean::PROTOTYPE type of bean

You can also specify the type to get:

For example: Get a singleton type bean

 /* @var WsDispatcher $dispatcher */
$dispatcher = BeanFactory::getSingleton('wsDispatcher'); 

Note that BeanFactory::getBean can only get the bean that the framework starts to load, and can't get the bean whose scope is request .

The type of the request bean is new to 2.x

Get the score as the request type, you can get it like this

 $requestBean = BeanFactory::getRequestBean(RequestClass::class, (string)Co::tid()); 

The bean general request type is usually bound to the 顶级协程ID .

Determine if a bean exists in the 当前环境

 $exist = BeanFactory::hasBean($name); 

Determine if it is a singleton bean

 $isSingleton = BeanFactory::isSingleton('name') 
/docs/2.x/en/bean/bean.html
progress-bar