我有以下通知实体:
正如您所看到的,有一个名为" objectId"我想根据通知类型存储相关的对象id。然后我将通知添加到电子邮件队列。处理队列时,我遇到从特定服务类获取对象的问题。例如:
那么如何定义这种关系而不会有麻烦来添加越来越多的通知类型。注入所有需要的服务并通过成千上万的服务处理它感觉很糟糕。如果不是这样的话。 :)
答案 0 :(得分:0)
如果您注入了对象而不是id,则无需在通知中调用其他服务来获取相应的实例。
如果Notification
不需要知道它使用什么类型的对象,只需依赖User
和Company
实现的接口,并将这些对象直接注入Notification
。
E.g:
interface EmailNotifiableEntity {
function getLabel()
function getEmailAddress()
}
class User implements EmailNotifiableEntity {
public function getLabel() {
return $this->getName() . " " . $this->getFullName();
}
public function getEmailAddress() {
return this->getEmailAddress();
}
}
class Company implements EmailNotifiableEntity {
public function getLabel() {
return $this->getCompanyName();
}
public function getEmailAddress() {
return this->getNotificationsEmail();
}
}
class Notification {
public function __construct(EmailNotifiableEntity $entity) {
$this->entity = $entity;
}
public function send() {
$address = $entity->getEmailAddress();
$label = $entity->getLabel();
// do your thing to send your notification
}
(实现有点勉强,所以拿你需要的东西并在它上面构建)。这样,当您实例化Notification
时,您会在不知道具体类型的情况下注入实体。