I'm wondering if using a Singleton for a storage of discounts is the right way to go. This is because I will be looping over all added discounts in another class.

client code

// Dynamically add new Discounts
$collection = DiscountCollection::getInstance();
$collection->add(new TenPercentDiscount());
$collection->add(new TwentyPercentDiscount());


<?php namespace Notflip\Discount;

use Notflip\Discount\Discounts\Discount;

class DiscountCollection {

    private static $instance;
    private static $discounts;

    final static function getInstance()
        if(static::$instance === null)
            static::$instance = new static();

        return static::$instance;

    public function add(Discount $discount)
        static::$discounts[] = $discount;

    public function count()
        return count(static::$discounts);

    public function show()
        return static::$discounts;
  • \$\begingroup\$ Do you need a single point of access to the object? Do you need to enforce only one instance of the discount data? Could you envisage having multiple threads, or needing more than one for testing, comparing, etc? I would guess, almost certainly, that you don't need a singleton. \$\endgroup\$
    – Peter Wood
    Apr 25, 2016 at 18:48
  • \$\begingroup\$ Thank you for your answer, While there will only ever be one collection, I thought a singleton would be good to ensure that. And to ensure that all adds() end up in the same collection. It will also be accessed from multiple classes in the project. \$\endgroup\$ Apr 25, 2016 at 19:34
  • \$\begingroup\$ Pass it to the objects which need it. \$\endgroup\$
    – Peter Wood
    Apr 25, 2016 at 21:04


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.