server/app/Service/Message/ChannelFactory.php

50 lines
1.2 KiB
PHP

<?php
namespace App\Service\Message;
use App\Service\Message\Channel\EmailChannel;
use App\Service\Message\Channel\WebsocketChannel;
use App\Service\Message\Exception\ChannelNotFoundException;
use App\Service\Message\Interface\ChannelInterface;
use Hyperf\Di\Container;
class ChannelFactory
{
protected Container $container;
/**
* 渠道映射表(可配置)
*/
protected array $channels = [
'email' => EmailChannel::class,
'websocket' => WebsocketChannel::class,
];
public function __construct(Container $container)
{
$this->container = $container;
}
/**
* 获取渠道实例
*/
public function get(string $name): ChannelInterface
{
if (!isset($this->channels[$name])) {
throw new ChannelNotFoundException("Channel [$name] not found");
}
return $this->container->get($this->channels[$name]);
}
/**
* 获取所有可用渠道
*/
public function all(): array
{
$list = [];
foreach ($this->channels as $class) {
$list[] = $this->container->get($class);
}
return $list;
}
}