开发者

CodeIgniter - Singleton pattern not allowed?

开发者 https://www.devze.com 2023-02-19 14:37 出处:网络
I\'m trying to use a singleton pattern in a class I\'ve created.I\'m using CodeIgniter and it seems to require the the constructor of all model objects be public.

I'm trying to use a singleton pattern in a class I've created. I'm using CodeIgniter and it seems to require the the constructor of all model objects be public.

Is there a way around this? What's the best approach if I can't use the Singleton pattern?

My Class:

class RakebackSites extends CI_Model {

    private $allSites = array(); 

    private function __construct() {
        parent::__construct();
        self::initAllSites();
    }

    public static function getInstance() {
        if(empty(self::$instance)) {
            self::$instance = new CurrencyTypes();
        }
        return self::$instance;
    }

    private function initAllSites() {
        $sql = "SELECT * FROM rakeback_sites";
        $this->db->query($sql);
        foreach ($q->resul开发者_StackOverflowt() as $row) {
            $allSites[] = new RBSite($row->id, $row->name, $row->logo, $row->rakeback, $row->sign_up_bonus, $row->sign_up_bonus_currency, $row->referral_code, $row->id);
        }
    }

    public function getAllSites() {
        return $this->allSites;
    }
}

And the error I get:

Fatal error: Access level to RakebackSites::__construct() must be public (as in class CI_Model) in /home/.../application/models/rakebacksites.php on line 29


If I recall correctly, CI automatically effectively creates Singletons if you load via $this->load->model('Your_model'). Obviously, it would still be possible to instantiate directly but then... just don't do it. Alternatively, don't inherit from CI_Model.


Does it let you declare the constructor as protected instead of private? Not exactly singleton but would that still work for your purposes?


Making a constructor private or protected does not have anything to do with the singleton pattern. All you are doing is defining an abstract class that cannot be directly instantiated.

To produce a singleton you need to override the new() method or implement a class factory.

0

精彩评论

暂无评论...
验证码 换一张
取 消