1. Go to this page and download the library: Download phpixie/di 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/ */
phpixie / di example snippets
class Container extends \PHPixie\DI\Container\Root
{
public function configure()
{
// Simple value stored by key
$this->value('apiToken', '1234567890');
// Dynamic method definition
$this->callback('addFive', function($a, $b) {
return $a + $b;
});
// This method will be called only once,
// which is perfect for service definitions
$this->build('twitterService', function() {
return new TwitterService($this->apiToken());
// or
return new TwitterService($this->get('apiToken'));
});
// Or you can also use a shortcut.
// Note that the parameters with '@' in their name
// will be replaced by corresponding value in the container
$this->instance('twitterService', TwitterService::class, ['@apiToken']);
// Nested group
$this->group('user', function() {
$this->instance('repository', UserRepository::class, ['@twitterService']);
});
}
}
// initialize the container
$container = new Container();
// Getting by key
$container->get('apiToken');
$container->apiToken();
// Static methods are only allowed
// after the container has been constructed
Container::apiToken();
Container::get('apiToken');
// Dynamic method call
// (also works via static methods)
$container->add(6, 7); // 13
$container->call('add', [6, 7]);
$callable = $container->get('add');
$callable(6, 7);
// Accessing nested definitions
$container->get('user.repository');
$userGroup = $container->user();
$userGroup->repository();
Container::user()->repository();
// etc...
// $container->twitterService()->getTweets();
$container->get('twitterService.getTweets');
// $container->twitterService()->getTweets()->first()->delete(true);
$container->call('twitterService.getTweets.first.delete', [true]);
// The above also works using static methods
Container::call('twitterService.getTweets.first.delete', [true]);
namespace Project\App;
// Note that we are extnding a different class this time
class Container extends \PHPixie\DefaultBundle\Container
{
public function configure()
{
//....your own definitions
parent::configure(); // don't forget this call
}
}
namespace Project\App;
class Builder extends \PHPixie\DefaultBundle\Builder
{
protected function buildContainer()
{
return new Container($this);
}
}