Dependency Injection
Skinny has a built-in resource locator, providing an easy way to inject objects into a Skinny app, or to override any of the Skinny app’s internal objects (e.g. Request, Response, Log).
Injecting Simple Values
If you want to use Skinny as a simple key-value store, it is as simple as this:
<?php
$app = \Skinny\Skinny::newInstance();
$app->foo = 'bar';
Now, you can fetch this value anywhere with $app->foo and get its value bar.
Using the Resource Locator
You can also use Skinny as a resource locator by injecting closures that define how your desired objects will be constructed. When the injected closure is requested, it will be invoked and the closure’s return value will be returned.
<?php
$app = \Skinny\Skinny::newInstance();
// Define method to create UUIDs
$app->uuid = function () {
return exec('uuidgen');
};
// Get a new UUID
$uuid = $app->uuid;
Singleton Resources
Sometimes, you may want your resource definitions to stay the same each time they are requested (i.e. they should be singletons within the scope of the Skinny app). This is easy to do:
<?php
$app = \Skinny\Skinny::newInstance();
// Define log resource
$app->container->singleton('log', function () {
return new \My\Custom\Log();
});
// Get log resource
$log = $app->log;
Every time you request the log resource with $app->log, it will return the same instance.
Closure Resources
What if you want to literally store a closure as the raw value and not have it invoked? You can do that like this:
<?php
$app = \Skinny\Skinny::newInstance();
// Define closure
$app->myClosure = $app->container->protect(function () {});
// Return raw closure without invoking it
$myClosure = $app->myClosure;
Access $app Instance Anywhere
After Skinny has been initialized, you can easily bring the app instance object into any application code that needs it.
<?php
class AppInitializer
{
public function __construct()
{
$app = \Skinny\Skinny::newInstance();
$app->foo = 'bar'; // assign injectable container value
}
}
class SomeClass
{
public function SomeMethod()
{
$app = \Skinny\Skinny::getInstance();
if ($app->foo === 'bar') {
// do something
}
}
}