1. Go to this page and download the library: Download krak/cargo library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
krak / cargo example snippets
use Krak\Cargo;
$c = Cargo\container();
$c = new Container\BoxContainer();
$c = new Container\SingletonContainer($c);
$c = new Container\BoxFactoryContainer($c);
$c = new Container\FreezingContainer($c);
$c = new Container\AliasContainer($c);
$c['a'] = function($c) {
return new ServiceA();
};
// or
$c->add('b', function($c) {
return new ServiceB($c['a']);
});
$c->singleton('a', function() {
return new ServiceA();
});
$c->factory('b', function() {
return new ServiceB();
});
// $c['a'] === $c['a'] - same instance each time
// $c['b'] !== $c['b'] - different instance each time
$func = function() {};
$c->protect('a.closure_parameter', $func);
// it returns the same instance because values are just stored as is.
// $c['a.closure_parameter'] === $func
$c->env('APP_KEY', $alias = 'application.key');
// $c['APP_KEY'] === $c['application.key'] are read from the env
$c['a'] = function() {};
// ok to redefine because we haven't invoked 'a' yet.
$c['a'] = function() {};
$service = $c['a'];
// this will throw an exception because the service was frozen
$c['a'] = function() {};
// the second parameter as true will = true);
$stack = $c->get('SplStack');
// will return an instance of SplStack as a singleton.
// defines 'StdClass' as a factory instance and will set it up for auto-wiring since no definition was given.
$c->factory('StdClass');
// $c['StdClass'] !== $c['StdClass']
interface ServiceProvider {
public function register(Cargo\Container $c);
}
$c->register(new FooProvider(), [
'foo.parameters' => 1,
]); // or Cargo\register($c, new FooProvider(), [])
$interop = Cargo\toInterop($c); // or $c->toInterop
// $interop instanceof Psr\Container\ContainerInterface
$pimple = Cargo\toPimple($c); // or $c->toPimple()
$pimple['a'] = function() {};
$pimple->extend('a', function() {});
$pimple['b'] = $pimple->protect(function() {
});
// $c has access to all services defined in pimple
$c['b'];