NIUCLOUD是一款SaaS管理后台框架多应用插件+云编译。上千名开发者、服务商正在积极拥抱开发者生态。欢迎开发者们免费入驻。一起助力发展! 广告
有些类在的构造函数除了可以注入的其他类还有一些配置项等需要注入,这时候我们就可以使用构造器的能力了 #### BeanConstrustorMapper ~~~ class MqConnection { //这里省略对应的field定义 public function __construct($host, $port, $user_name, $password, $fetch_count, $exchanges = ['topic_default' => 'topic'], $check = 30000) { $i = 0; foreach ($exchanges as $exchange => $value) { if ($i == 0) { $this->exchange_default = $exchange; } break; } $this->host = $host; $this->port = $port; $this->user_name = $user_name; $this->password = $password; $this->fetch_count = $fetch_count; $this->check = $check; $this->exchanges = $exchanges; } } ~~~ 对应的注入方式 先定义个类实现BeanConstrustorMapper接口,实现mapper方法 反对对应的配置项就可以了,mapper方法可以返回多个类的配置 ~~~ class MyBeanConstructorMapper extends BeanConstrustorMapper { function mapper() { return [[ "class" => MqConnection::class, "constructor" => [ "host" => 'rabbitmq3.7.7', "port" => 5672, "user_name" => 'admin', "password" => 'admin', "fetch_count" => 1, 'exchanges'=>["delayed_exchanges"=>['x-delayed-message','topic']] ], ] ]; } } ~~~ 下面只需要在AppInit是注册下就可以了 ~~~ class AppInit implements Init { public function appInit(AutoFindHandlerMapping $autoMapping, Router $router) { //注册类构造器定义 Ioc::register(MyBeanConstructorMapper::class); //继续其他逻辑 } } ~~~