, . , : DI , , ? , -, ( )? , , ? , ... - , " DI", , SO:) ( DI)
, , , PHP. , Guice ( Java- Google, DI):
- "" ( "" ) , . . . , AngularJS - JS Google, - "" " " "..." : , " " , , " " DIC .
, -, ( ).
:
IMO, , DI, " " , , callin. , , , root. .
, PHP-DI DIC. , .
interface HomePageTrivialFactoryInterface {
public function __construct(
DI\Container $container
);
public function __invoke(
): HomePage;
}
class PageFactory {
private $homePageTrivialFactory;
private $contactPageTrivialFactory;
public function __construct(
HomePageTrivialFactoryInterface $homePageTrivialFactory,
ContactPageTrivialFactoryInterface $contactPageTrivialFactory
) {
}
public function createPage(
$pagename
) {
switch ($pagename) {
case HomePage::name:
return ($this->homePageTrivialFactory)(
);
case ContactPage::name:
return ($this->contactPageTrivialFactory)(
);
default:
return null;
}
}
}
$containerDefinitions = [
HomePageTrivialFactoryInterface::class => DI\factory(
function (DI\Container $container): HomePageTrivialFactoryInterface
{
return new class($container)
implements HomePageTrivialFactoryInterface
{
private $container;
public function __construct(
DI\Container $container
) {
}
public function __invoke(
): HomePage
{
return $this->container->make(HomePage::class, [
]);
}
};
}
),
];
$container = (new DI\ContainerBuilder)
->addDefinitions($containerDefinitions)
->build();
$pageFactory = $container->get(PageFactory::class);
$pageFactory->createPage($pageName);
, DI, , , inon anonimous classes ( PHP 7). , , , . . , 1, 2 4 : # 1 , , 2 4 , , PageFactory, . , , - 3- , :
$containerDefinitions = [
PageFactory::class => DI\object()
->constructorParameter('homePageTrivialFactory', DI\factory(
function (
DI\Container $container
// list of other dependencies that are already known at
// design time also goes here
) {
function (
// list of run time dependencies
) use($container): HomePage
{
return $container->make(HomePage::class, [
]);
}
}
))
,
];
, , , ( , , ), , . HomePage ( ), , , , . IMO , : , .
, @SinistraD, ?