Skip to content

Instantly share code, notes, and snippets.

@shadowhand
Created December 10, 2016 02:59
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shadowhand/62364fcb71e3284b29a9ce7131b73a38 to your computer and use it in GitHub Desktop.
Save shadowhand/62364fcb71e3284b29a9ce7131b73a38 to your computer and use it in GitHub Desktop.
Using named constructors for data transfer objects
<?php
namespace Acme;
class DataTransfer
{
public static function forUser(
$user_id
) {
return new static($user_id);
}
public static function forCompany(
$company_id
) {
return new static(null, $company_id);
}
private $user_id;
private $company_id;
public function userId()
{
return $this->user_id;
}
public function companyId()
{
return $this->company_id;
}
private function __construct(
$user_id = null,
$company_id = null
) {
if ($user_id) {
$this->user_id = $user_id;
}
if ($company_id) {
$this->company_id = $company_id;
}
}
}
@shadowhand
Copy link
Author

shadowhand commented Dec 10, 2016

What I love about this is that it hides changes to the constructor and makes it really easy use:

$dto = DataTransfer::forUser($_POST['user_id']);
// or
$dto = DataTransfer::forCompany($_POST['company_id']);

Many named constructors can be added the class to account for different variations in the data, all without worrying about existing code blowing up because the constructor order changed! :shipit:

References: Named Constructors in PHP

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment