又一个"Is this a pattern and if yes, what's the name"?



从另一个不同种类/类的实例创建实例。

快速示例:您正在使用ORM并将电子邮件队列存储在数据库中。然后在某些时候,您必须使用第三方库发送批量电子邮件。

您的对象(PHP在这里无关紧要,为简单起见,公共属性):

class Mail
{
    /**
     * @var string
     */
    public $senderText;
    /**
     * @var MyAppEntityUser
     */
    public $user;
    /**
     * @var DoctrineORMArrayCollection
     */
    public $attachments;
}

。而您的第三方"邮件"对象则大不相同。例如,您可能需要执行以下操作:

$mail = /* hydrated */;
$user = $mail->getUser();
$mailer = new ThirdPartyMailer();
// Fill message properties
$message = $mailer->createMessage();
$fullName = sprintf('%s %s', $user->getFirst(), $user->getLast());
$message->addFrom(array($fullName => $user->getEmail()))
// Create and add attachments
foreach($mail->getAttachments() as $attachment)
{
    $message->attach($mailer->createAttachment($attachment->getFullPath()));
}

这是一种模式吗?类似于对象转换器的东西,例如负责从一个实例创建/转换另一个实例的类......

我不知道

这种模式有一个广泛使用的名称,但一些常见的名称是"转换器"和"转换器"——一个在代表相似实体的两个不同类之间进行转换的类。

一个相关的模式是适配器模式:如果第三方消息作为接口公开,则可以创建一个适配器类来包装现有邮件对象并实现第三方接口。

最新更新