【问题标题】:Pimple DI share deprecated. Now what?不推荐使用 Pimple DI 共享。怎么办?
【发布时间】:2016-01-12 19:53:52
【问题描述】:

在 Pimple 1.0 中,我曾经能够像这样共享类实例:

$app['some_service'] = $app->share(function () {
    return new Service();
});

这现在似乎已被弃用,我无法找到这样做的新方法。

【问题讨论】:

标签: php symfony silex pimple


【解决方案1】:

在 Pimple 1.0 (Silex 1) 中,您可以这样做:

$app['shared_service'] = $app->share(function () {
    return new Service();
});

$app['non_shared_service'] = function () {
    return new Service();
};

在 Pimple 3.0 (Silex 2) 中,您可以这样做(相反!):

$app['shared_service'] = function () {
    return new Service();
};

$app['non_shared_service'] = $app->factory(function () {
    return new Service();
});

【讨论】:

    【解决方案2】:

    似乎默认情况下,pimple 3.0(Silex 2.0 使用)总是返回相同的服务实例。如果您不想要这种行为,则需要明确说明并使用工厂函数。

    【讨论】:

      【解决方案3】:

      取决于疙瘩版本!

      关于疙瘩 1.0

      $container['shared'] = $container->shared(function(){
          return new Class();
      });
      $container['non_shared'] = function() {
          return new Class();
      };
      

      在疙瘩 3.0 上

      $container['shared'] = function() {
          return new Class();
      };
      $container['non_shared'] = $container->factory(function() {
          return new Class();
      });
      

      请记住,当您创建共享服务时,它们返回的内容不会改变。当您创建非共享服务时,每次使用时,Pimple 都会为您提供一个新的 it 服务实例。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-26
        • 2013-02-10
        相关资源
        最近更新 更多