在Slim Framework 3中获取类的容器

时间:2018-01-12 18:14:55

标签: containers slim-3

我有DIC配置

$container = $app->getContainer();
$container['renderer'] = function ($c) {
    $settings = $c->get('settings')['renderer'];
    return new Slim\Views\PhpRenderer($settings['template_path']);
};

并在类OrderModel

的construct方法中发送容器
$this->get('setoutsite/{id}', function ($req, $res, $args) {
    $um = new OrderModel($container);
    return $res
    ->withHeader('Content-type', 'application/json')
    ->getBody()
    ->write(
        json_encode(
            $um->SetOrderOutSite($args['id'])
            )
        );
});

但是当构造函数得到

时,参数为null
class OrderModel
{

    private $db;

    private $table = 'orden';

    private $response;

    private $conf_emblue;

    private $emblue;

    private $phpView;

    public function __construct( Container $c = null)
    {
        $this->db = Database::StartUp();
        $this->response = new Response();
        $this->conf_emblue = new ConfigEmblue();
        $this->emblue = new RestEmblue();

    }

2 个答案:

答案 0 :(得分:1)

问题是你没有通过路由功能传递容器来解决这个问题,只需改变你的代码: 使用使用

传递$ container
$this->get('setoutsite/{id}', function ($req, $res, $args) use($container) {
$um = new OrderModel($container);
return $res
->withHeader('Content-type', 'application/json')
->getBody()
->write(
    json_encode(
        $um->SetOrderOutSite($args['id'])
        )
    );
});

答案 1 :(得分:0)

您可以简化代码,如下所示

在依赖注册中,注册OrderModel实例。

$container[OrderModel::class] = function($containerInstance) {
    return new OrderModel($containerInstance);
};

并且在路线中(假设$app是Slim应用程序实例),

$app->get('setoutsite/{id}', function ($req, $res, $args) use($container) {
   $um = $container->get(OrderModel::class);
   return $response->withJson($um->SetOrderOutSite($args['id']));
});