PiDiC
, (*1)
PiDiC is an adapter over Nette\Di\Container., (*2)
Install
$ composer require phalette/pidic:dev-master
Dependencies
Configuration
use Nette\DI\Compiler;
use Phalette\Pidic\Configurator;
use Phalette\Pidic\Environment;
use Phalette\Pidic\Extensions\PhalconDefaultsExtension;
use Phalette\Pidic\Extensions\PhalconExtension;
use Phalette\Pidic\PiDi;
$configurator = new Configurator();
$configurator->setMode(Environment::DEVELOPMENT);
$configurator->setCacheDir(__DIR__ . '/cache');
$configurator->onCompile[] = function (Compiler $compiler) {
$compiler->addExtension('phalcon', new PhalconExtension());
$compiler->addExtension('phalconDefaults', new PhalconDefaultsExtension());
};
$container = $configurator->createContainer();
$pidi = $container->getService('pidi');
Learn by working example
This is based on official tutorial., (*3)
use Nette\DI\Compiler;
use Phalette\Pidic\Configurator;
use Phalette\Pidic\Environment;
use Phalette\Pidic\Extensions\PhalconDefaultsExtension;
use Phalette\Pidic\Extensions\PhalconExtension;
use Phalette\Pidic\PiDi;
use Phalcon\Loader;
use Phalcon\Mvc\View;
use Phalcon\Mvc\Application;
use Phalcon\DI\FactoryDefault;
use Phalcon\Mvc\Url as UrlProvider;
use Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter;
try {
// Register an autoloader
$loader = new Loader();
$loader->registerDirs(array(
'../app/controllers/',
'../app/models/'
))->register();
// Create a DI
$configurator = new Configurator();
$configurator->setMode(Environment::DEVELOPMENT);
$configurator->setCacheDir(__DIR__ . '/cache');
$configurator->onCompile[] = function (Compiler $compiler) {
$compiler->addExtension('phalcon', new PhalconExtension());
$compiler->addExtension('phalconDefaults', new PhalconDefaultsExtension());
};
$container = $configurator->createContainer();
$di = $container->getService('pidi');
// Setup the view component
$di->set('view', function () {
$view = new View();
$view->setViewsDir('../app/views/');
return $view;
});
// Setup a base URI so that all generated URIs include the "tutorial" folder
$di->set('url', function () {
$url = new UrlProvider();
$url->setBaseUri('/tutorial/');
return $url;
});
// Handle the request
$application = new Application($di);
echo $application->handle()->getContent();
} catch (\Exception $e) {
echo "PhalconException: ", $e->getMessage();
}
PhalconExtension
It sets self-instance over static Phalcon\Di::setDefault(). Every object extending from Phalcon\Di\InjectionAwareInterface can access PiDiC from $this->getDI()., (*4)
PhalconDefaultsExtension
This extension replace Phalcon\DI\FactoryDefault. It register to the container 22 base services (more in docs)., (*5)
Phalcon\Di
PiDiC implements Phalcon\DiInterface and then you can change DI without any changes., (*6)
How to work with DI in Phalcon, you can read here., (*7)
Nette\DI
Please read articles at Nette documentation:, (*8)
But the main article is:, (*9)