Create an instance from another one of different kind/class.
Quick example: you are using an ORM and you store an email queue in your database. Then at some point you have to send bulk emails, using third party library.
Your object (PHP irrelevant here, public properties for simplicity):
class Mail
{
/**
* @var string
*/
public $senderText;
/**
* @var My\App\Entity\User
*/
public $user;
/**
* @var \Doctrine\ORM\ArrayCollection
*/
public $attachments;
}
… while your third party “mail” object is far different. For example, you may need to do something like:
$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()));
}
Is this a pattern? Something like object converter, like a class responsible of creating/converting one instance from another…
I’m not aware of a single widely used name for this pattern, but some common names are “translator” and “converter” — a class that translates between two different classes representing similar entities.
A related pattern is the adapter pattern: if the third-party message is exposed as an interface, you could create an adapter class that wraps your existing mail object and implements the third-party interface.