Created
December 10, 2016 02:59
-
-
Save shadowhand/62364fcb71e3284b29a9ce7131b73a38 to your computer and use it in GitHub Desktop.
Using named constructors for data transfer objects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What I love about this is that it hides changes to the constructor and makes it really easy use:
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!
References: Named Constructors in PHP