Created
December 6, 2016 10:33
-
-
Save akrabat/7fc4ab58860534a58144085755c9233b to your computer and use it in GitHub Desktop.
Example use of Zend\ServiceManager 3
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 | |
require('vendor/autoload.php'); | |
use Zend\ServiceManager\Factory\InvokableFactory; | |
//-------------------------------------------------------- | |
// classes that we are interested in | |
class Letter { | |
public function __construct($paper, $envelope) { | |
$this->paper = $paper; | |
$this->envelope = $envelope; | |
} | |
public function write($text, $who, $address) { | |
// do clever stuff | |
$price = $this->envelope->stampPrice; | |
echo "I have written a letter! The stamp cost $price!!!!\n"; | |
} | |
} | |
class Paper {} | |
class Envelope { | |
public function __construct() { | |
$this->stampPrice = '50p'; | |
} | |
public function setPriceOfStamp($price) { | |
$this->stampPrice = $price; | |
} | |
} | |
//-------------------------------------------------------- | |
// DIC related classes | |
class LetterFactory { | |
public function __invoke($container) { | |
echo "In the LetterFactory\n"; | |
$paper = $container->get('Paper'); | |
$envelope = $container->get(Envelope::class); | |
return new Letter($paper, $envelope); | |
} | |
} | |
class EnvelopeFactory { | |
public function __invoke($container) { | |
echo "In the EnvelopeFactory\n"; | |
return new Envelope(); | |
} | |
} | |
class FirstPriceStampEnvelopDelegatorFactory { | |
public function __invoke($container, $name, $callback, $options = []) { | |
echo "In the Delegator. name = $name\n"; | |
$envelope = $callback(); | |
$envelope->setPriceOfStamp('75p'); | |
return $envelope; | |
} | |
} | |
//-------------------------------------------------------- | |
// DIC configuration | |
$config = [ | |
'factories' => [ | |
Letter::class => LetterFactory::class, | |
Paper::class => InvokableFactory::class, | |
Envelope::class => EnvelopeFactory::class, | |
], | |
'delegators' => [ | |
Envelope::class => [ | |
FirstPriceStampEnvelopDelegatorFactory::class, | |
], | |
], | |
]; | |
$container = new Zend\ServiceManager\ServiceManager($config); | |
$letter = $container->get(Letter::class); | |
$letter->write("Hi", 'Ben', 'Home'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment