Closed almakano closed 3 years ago
It's not really safe and it can lead into future problems.
For example, please.
So, you say that making connection for every query per one host is good?
For example there is a class blog {} and class user {}. In each getList() method there is $db = new medoo($host,$user,$pass,$db); So if i need to get list of blogs and it's users - db connections creating twice.
self::$db - is using only in self class and never be in others if there is a need to make 2 different connections at the same time array self::$connections can help
For me, i found that usefull by saving server resources and site time start.
Yes, this is the common problem but it can be easily fixed with DI (Dependency Injection), your DB will be defined as shared so whatever object you create with dependency DB, your previously created instance of medoo will be included. I recommend Auryn DI
What about use a static call to do this? Leaving the __construct as is, but simply adding:
private static $_self = null; /** * @return medoo */ public static function single($options = null) { if(self::$_self == null) { $class = get_called_class(); self::$_self = new $class($options); } return self::$_self; }
This is what I'm actually using... often I simply call the $db = new Medoo($conf), but in some cases where I need it... I call $db = Medoo::single($conf)
single stand for "single instance"... in my head :+1:
@b3bb0 Why Singleton pattern? - It's anti-pattern
@VeeeneX ...I'm not native English speaker, so I had to look up the meaning of anti-pattern: According to the authors of Design Patterns, there must be at least two key elements present to formally distinguish an actual anti-pattern from a simple bad habit, bad practice, or bad idea:
What's a good alternative to avoid several connections to the database when called medoo from different places/classes, but all in the "same" execution?
You can use Singleton pattern, but it is not so good in php. As @VeeeneX say Dependency Injection is right and better way.
I personally don't think the use of something like Auryn fix the "issue"... I'm using medoo to have something super light and useful... in a small project, Auryn code is almost more lines then the whole project I'm doing, the "evil" singleton fixed my approach... and I'll stick to it, for this case :)
@b3bb0 Maybe you can use simple service locator like this: http://twittee.org/
If connection args sended to "new medoo(array(...))" PDO object can be saved in self::$pdo If no args send to "new medoo()" PDO object can be returned from self::$pdo 1 connection - many queries
same in log: can be saved is self::$queries not $this::$queries