Skip to content

Instantly share code, notes, and snippets.

@JeroenDeDauw
Last active August 20, 2018 07:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JeroenDeDauw/a0a5b0a210143bf2a33c2439c3445cbe to your computer and use it in GitHub Desktop.
Save JeroenDeDauw/a0a5b0a210143bf2a33c2439c3445cbe to your computer and use it in GitHub Desktop.
<?php
class SharedObjectFactory {
private $container;
private $config;
public function __construct( array $config ) {
$this->container = [];
$this->config = $config;
}
private function getSharedObject( string $id, callable $factory ) {
if( !isset( $this->container[$id] ) ) {
$this->container[$id] = $factory();
}
return $this->container[$id];
}
private function getGreeter(): GreetService {
return $this->getSharedObject(
GreetService::class,
function() {
return new FixedMessageGreeter( $this->config['greeting'] );
}
);
}
public function getPresenter(): Presenter {
return $this->getSharedObject(
GreetingPresenter::class,
function() {
return new GreetingPresenter(
$this->getGreeter(),
$this->newLogger()
);
}
);
}
/**
* Example of a non-shared service
*/
public function newLogger(): Logger {
return new SuchLogger();
}
}
@JeroenDeDauw
Copy link
Author

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