-
Notifications
You must be signed in to change notification settings - Fork 10
Service
The Service module sports a service locator and a factory container.
This module permits the user to register and retrieve a service manager instance, one (singleton) or multiple times.
You can use the register method to add a service container that will be called and instantiated a single time.
class Greeter {
protected $name;
public function __construct($name){ $this->name = $name; }
public function hi(){ echo "Hello, {$this->name}"; }
}
Service::register('greeter',function() {
return new Greeter("Friend");
});You can now call the greeter service with the Service::<service_name> pattern :
echo Service::greeter()->hi();
// Hello, FriendOnce instantiated the Service register holds the returned value from the passed callback and returns that every time the service is accessed.
In the precedent example the Friend parameter was hard-coded in the init callback.
However if you want to let the user pass the init arguments the first time the service is invoked, you can :
Service::register('greeter',function($whoami) {
return new Greeter($whoami);
});echo Service::greeter("John")->hi();
// Hello, John
echo Service::greeter("Marie")->hi();
// Hello, John
echo Service::greeter()->hi();
// Hello, JohnYou can use the registerFactory method to add a service container that will be called and instantiated every time.
Service::registerFactory('envelope',function($message) {
return (object)[
"type" => "envelope",
"data" => [
"body" => $message,
"length" => strlen($message),
],
];
});Now, every time you call Service::envelope the init callback will be invoked
$a = Service::envelope("This is a test");
$b = Service::envelope("It's over 9000!!!!");
echo json_encode([$a,$b], JSON_PRETTY_PRINT);[
{
"type": "envelope",
"data": {
"body": "This is a test",
"length": 14
}
},
{
"type": "envelope",
"data": {
"body": "It's over 9000!!!!",
"length": 18
}
}
]Core is maintained by using the Semantic Versioning Specification (SemVer).
Copyright 2014-2016 Caffeina srl under the MIT license.
http://caffeina.com