swoft微服务框架之容器IOC和控制器

什么是swoft?

swoft是基于swoole协程2.x的高性能PHP微服务框架,内置http服务器。框架全协程实现,性能优于传统的php-fpm模式。项目地址: https://github.com/swoft-cloud/swoft

全局容器

每一个被swoft管理的PHP对象称之为Bean,swoft提供了一个IoC容器来初始化对象和获取对象,解决对象间的依赖管理。properties.php可以配置容器相关参数。

return [
    ...
    'autoInitBean' => true,// 是否自动初始化bean,如果false,使用bean时创建Bean,默认是false
    'beanScan' => [ // 配置注解自动扫描的命令空间
        'app\controllers',
        'app\models',
        'app\beans',
    ],
    ...
];

注入对象与引用

目前支持两种方式注入对象,数组配置和@Bean注解。

配置规则

  • 必须定义一个数组KEY且为字符串,KEY及是Bean名称,可以通过名称使用
  • 数组值里面必须有KEY为class,class指定需要注入的类名称
  • 其余数组配置项,若KEY=0且值为自然数组(数组个数对应构造函数参数),则是类构造函数配置,反之是类属性配置,KEY及是类成员名称,属性配置只要不是静态属性都可以。
  • base.php配置顺序没有强力要求,建议按使用顺序配置,方便阅读

引用规则

  • 引用properties.php分递归引用和直接引用两种方式
  • ${beanName}这种方式引用Bean对象
  • 构造函数参数和成员属性都可以使用以上引用规则
数组配置
// properties.php
return [
    'config.service.user.maxActive' => 10,
    'service' =>[
        'user' => [
            'timeout' => 21200
        ]
    ]
];

// base.php
return [
    'config'         => [
        'properties' => require_once __DIR__ . '/' . APP_ENV . '/properties.php',
    ],
    'userProvider' => [
        'class' => \swoft\service\ConsulProvider::class
    ],
    "userPool"  => [
        "class"           => \swoft\pool\ServicePool::class, // 
        [
            '${randomBalancer}', // 构造函数参数,通过引用值使用
            [
                'timeout'=>'${config.service.user.timeout}'
            ],
            'refVal',
        ],
        "uri"             => '127.0.0.1:8099,127.0.0.1:8099', 
        "maxIdel"         => 6,
        "maxActive"       => '${config.service.user.maxActive}', // 直接引用方式使用
        "timeout"         => '${config.service.user.timeout}', // 递归引用使用
        "balancer"        => '${randomBalancer}', //引用已经注入的Bean对象 
        "serviceName"     => 'user',
        "useProvider"     => false,
        'serviceprovider' => '${userProvider}'
    ],
];
注解配置

注解配置更加简洁,通过在类和属性上使用@Bean和@Inject注解。

/**
 *
 * 注解注入demo,如下注入一个名为userModel的bean
 *
 * @Bean("userModel")
 * ...
 */
class UserModel
{
    /**
     * 注入logger
     *
     * @Inject("${logger}")
     * @var Logger
     */
    private $property;

    /**
     * 注入logger
     *
     * @Inject(name="${logger}")
     * @var Logger
     */
    private $property2;

    /**
     * 注入IndexLogic.class,默认注入该属性,对应的类型名(包含命令空间)Bean
     *
     * @Inject()
     * @var IndexLogic
     */
    private $property3;

    /**
     * 注入properties.php值
     * 
     * @Inject("${config.service.user.timeout}")
     * @var int
     */
    private $property4;

    /**
     * 注入properties.php值
     *
     * @Inject(name="${config.user.stelin.steln}")
     * @var string
     */
    private $property5;

    /**
     * 未注入,使用默认值
     *
     * @var string
     */
    private $property6 = "default";


    public function getData()
    {
        return $this->data;
    }
}

@Bean注解

@Bean里面只能使用双引号

@Bean("userModel")或@Bean(name="userModel")含义是一样。

@Bean()这种格式含义是注入的bean名称是使用类名(包含命名空间)。

@Bean(name="beanName",scope=Scope::SINGLETON) 默认注入Bean都是单例,可以scope属性设置其类型

@Inject

@Inject使用格式和@Bean基本一样,注意通过注解目前不支持构造函数参数注入

@Inject("name="${logger}")或@Inject("${logger}")注入名称为logger的Bean到属性

@Inject(name="${config.user.stelin.steln}")注入properties里面配置的值,可以层级和直接方式配置。

@Inject()默认注入该属性,对应的类型名(包含命令空间)Bean

控制器

一个继承\swoft\web\Controller的类既是控制器,控制器有两种注解自动注册和手动注册两种方式。建议使用注解自动注册,方便简洁,维护简单。多次注册相同的路由前者会被后者覆盖。

注解自动注册

注解自动注册常用到三个注解@AutoController、@Inject、@RequestMapping.

@AutoController

已经使用@AutoController,不能再使用@Bean注解。

@AutoController注解不需要指定bean名称,统一类为bean名称

@AutoController()默认自动解析controller前缀,并且使用驼峰格式。

@AutoController(prefix="/demo2")或@AutoController("/demo2")功能一样,两种使用方式。

@Inject

使用和之前的一样

@RequestMapping

@RequestMapping(route="/index2")或@RequestMapping("/index2")功能一样两种方式使用,这种默认是支持get和post方式

@RequestMapping(route="/index2", method=RequestMethod::GET)注册支持的方法

不使用@RequestMapping或RequestMapping()功能一样,都是默认解析action方法,以驼峰格式,注册路由。

/**
 * 控制器demo
 *
 * @AutoController(prefix="/demo2")
 *
 * @uses      DemoController
 * @version   2017年08月22日
 * @author    stelin <phpcrazy@126.com>
 * @copyright Copyright 2010-2016 swoft software
 * @license   PHP Version 7.x {@link http://www.php.net/license/3_0.txt}
 */
class DemoController extends Controller
{
    /**
     * 注入逻辑层
     *
     * @Inject()
     * @var IndexLogic
     */
    private $logic;

    /**
     * 定义一个route,支持get和post方式,处理uri=/demo2/index
     *
     * @RequestMapping(route="index", method={RequestMethod::GET, RequestMethod::POST})
     */
    public function actionIndex()
    {
        // 获取所有GET参数
        $get = $this->get();
        // 获取name参数默认值defaultName
        $name = $this->get('name', 'defaultName');
        // 获取所有POST参数
        $post = $this->post();
        // 获取name参数默认值defaultName
        $name = $this->post('name', 'defaultName');
        // 获取所有参,包括GET或POST
        $request = $this->request();
        // 获取name参数默认值defaultName
        $name = $this->request('name', 'defaultName');
        //json方式显示数据


        $this->outputJson("suc");
    }

    /**
     * 定义一个route,支持get,以"/"开头的定义,直接是根路径,处理uri=/index2
     *
     * @RequestMapping(route="/index2", method=RequestMethod::GET)
     */
    public function actionIndex2()
    {
        // 重定向一个URI
        $this->redirect("/login/index");
    }

    /**
     * 没有使用注解,自动解析注入,默认支持get和post,处理uri=/demo2/index3
     */
    public function actionIndex3()
    {
        $this->outputJson("suc3");
    }
}

手动注册

手动注册常用@Bean、@Inject注解,手动注册还要多一步就是在routes.php里面注册自己的路由规则。

手动注册@Bean()只能这样缺省方式。并且不能使用@AutoController注解

/**
 * 控制器demo
 *
 * @Bean()
 *
 * @uses      DemoController
 * @version   2017年08月22日
 * @author    stelin <phpcrazy@126.com>
 * @copyright Copyright 2010-2016 swoft software
 * @license   PHP Version 7.x {@link http://www.php.net/license/3_0.txt}
 */
class DemoController extends Controller
{
    /**
     * 注入逻辑层
     *
     * @Inject()
     * @var IndexLogic
     */
    private $logic;

    /**
     * uri=/demo2/index
     */
    public function actionIndex()
    {
        // 获取所有GET参数
        $get = $this->get();
        // 获取name参数默认值defaultName
        $name = $this->get('name', 'defaultName');
        // 获取所有POST参数
        $post = $this->post();
        // 获取name参数默认值defaultName
        $name = $this->post('name', 'defaultName');
        // 获取所有参,包括GET或POST
        $request = $this->request();
        // 获取name参数默认值defaultName
        $name = $this->request('name', 'defaultName');
        //json方式显示数据


        $this->outputJson("suc");
    }

    /**
     * uri=/index2
     */
    public function actionIndex2()
    {
        // 重定向一个URI
        //        $this->redirect("/login/index");
        $this->outputJson("suc2");
    }

    /**
     */
    public function actionIndex3()
    {
        $this->outputJson("suc3");
    }
}

routes.php手动注册路由

// ...

$router->map(['get', 'post'], '/demo2/index', 'app\controllers\DemoController@index');
$router->get('/index2', 'app\controllers\DemoController@index2');
$router->get('/demo2/index3', 'app\controllers\DemoController@index3');

转载于:https://my.oschina.net/stelin/blog/1522829

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值