Created
August 11, 2014 13:00
-
-
Save mdwheele/6759a6c381f82abdf06f to your computer and use it in GitHub Desktop.
An example of how one might implement a pseudo-friend relationship between two PHP 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 | |
class SampleEntity | |
{ | |
private $friend = 'SampleEntityPresenter'; | |
protected $firstName; | |
protected $lastName; | |
public function __construct($firstName, $lastName) | |
{ | |
$this->firstName = $firstName; | |
$this->lastName = $lastName; | |
} | |
public function __get($property) | |
{ | |
if ($this->friend !== $this->getCallingClass()) { | |
throw new Exception("SampleEntity can only be accessed by SampleEntityPresenter."); | |
} | |
return $this->$property; | |
} | |
private function getCallingClass() | |
{ | |
$backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT); | |
$backtrace = end($backtrace); | |
return $backtrace['class']; | |
} | |
} | |
class SampleEntityPresenter | |
{ | |
private $entity; | |
public function __construct(SampleEntity $entity) | |
{ | |
$this->entity = $entity; | |
} | |
public function getFullName() | |
{ | |
return $this->entity->firstName . ' ' . $this->entity->lastName; | |
} | |
} | |
// Sample code. | |
$entity = new SampleEntity('Dustin', 'Wheeler'); | |
$presenter = new SampleEntityPresenter($entity); | |
// Access through presenter succeeds. | |
echo $presenter->getFullName() . PHP_EOL; | |
// Direct-access fails with Exception. | |
echo $entity->firstName . ' ' . $entity->lastName . PHP_EOL; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment