allenlinatoc / php-container
符合PSR-11规范的容器类,专门为Slim v4构建,基于Pimple。
v1.0.4-RC
2020-02-27 18:53 UTC
Requires
- php: >=5.6
- pimple/pimple: ^3.2
- psr/container: ^1.0
This package is auto-updated.
Last update: 2024-09-28 05:38:36 UTC
README
符合PSR-11规范的容器类,专门为Slim v4构建,基于Pimple。
安装
警告:这还不是生产就绪。
composer require allenlinatoc/php-container "v1.0.1-beta"
使用方法
AppFactory::setContainer(new Allenlinatoc\PhpContainer\Container());
现在就像你习惯使用Pimple容器一样使用它。
假设你有一个名为twig.php
的Twig PHP文件作为服务
<?php
return function ($container) {
return new \Slim\Views\Twig(
\Highdesk\Utils\FileSystem::root("/public/views"),
[
"cache" => \Highdesk\Utils\FileSystem::root("/.twigcache")
]
);
};
你可以在容器内加载它,如下所示
// As array
$container["view"] = (require "twig.php");
// Through "set" method (like PHP-DI's way)
$container->set("view", (require "twig.php"));
// Or as direct property assignment (this is where __set() magic method kicks in)
$container->view = (require "twig.php");
现在在Slim的路由内,你可以这样获取你的Twig服务...
$app->get('/hello/{name}', function (Request $request, Response $response, array $args) {
$name = $args['name'];
// As Array
$this["view"]->render($response, 'index.phtml', compact('name'));
// Through "get" method (like PHP-DI's way)
$this->get("view")->render($response, 'index.phtml', compact('name'));
// Or as property (via __get() magic method)
$this->view->render($response, 'index.phtml', compact('name'));
return $response;
});
说明
因此,我对Slim 4框架相对较新。当我处理依赖注入时,PHP-DI容器并没有像Pimple容器那样满足我的需求。
简而言之,我被PSR-11类型的容器所限制,例如,我无法直接调用任何容器元素的属性
$this->container->set("views", (require_once twig.php));
现在当我尝试将Twig服务作为属性调用...
$this->view->render(...)
它将告诉我view
属性未定义 - 因此我最终得到了这个简单的容器类。
它继承自\Pimple\Container
并实现了ContainerInterface
,因此它可以与Slim 4的新容器加载方式兼容:AppFactory::setContainer($container)