7

In Pimple 1.0 I used to be able to share class instances like this:

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

This now seems to be deprecated and I am unable to find what is the new way of doing this.

yivi
  • 42,438
  • 18
  • 116
  • 138
Adam
  • 3,415
  • 4
  • 30
  • 49

3 Answers3

13

In Pimple 1.0 (Silex 1), you do this:

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

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

In Pimple 3.0 (Silex 2) you do this (which is the opposite!):

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

$app['non_shared_service'] = $app->factory(function () {
    return new Service();
});
Javier Eguiluz
  • 3,987
  • 2
  • 23
  • 44
2

Seems that by pimple 3.0 (which Silex 2.0 uses) by default always returns the same instance of the service. You need to be explicit about it and use the factory function if you don't want this behaviour.

mTorres
  • 3,590
  • 2
  • 25
  • 36
Adam
  • 3,415
  • 4
  • 30
  • 49
1

Depends of the Pimple version!

On Pimple 1.0

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

On Pimple 3.0

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

Remembering, when you create a shared service, what they return will not change. When you create a non shared service, every time you use, the Pimple will provide to you a new instance of it service.

alvescleiton
  • 1,063
  • 11
  • 8