ben.artiss wrote:Code: Select all
$db =& app('db');
$db->query('...');
app('db')->query('...');
app()->db->query('...');
All of those examples use the same instance. Am I alone in thinking that's efficient, or am I not understanding something?
One could say that if this makes things easy and fast for you to develop the set of applications that you develop then go wild. One could also say that the something your are "not understanding" is the last 30-40 years of software design theory.
A general answer to the above code is that while they all do the same thing the open you up to different side effects, help or limit your ability to write tests, hinders you ability to make changes without workarounds, etc. Programmers usually think their code looks reasonable because they have agreed to every trade-off made while designing that code. Usually several of those trade-offs are considered bad practice for very good (but often counter intuitive) reasons.
You are asking a key design question for PHP programmers. We start with the good premise and practice of using objects in object-y ways. So you want a database connection object to submit queries to the database:
Code: Select all
$resultObj = $dbObj->query('SELECT...');
So now the question becomes: How do I get that $dbObj? You could do:
Code: Select all
$dbObj = new My_Db_Class($configData);
But then the question is: How do I get that $configData? And so on.
There are a number of answers to these basic PHP application design question. You want to create a magic God object that contains all this information inside so everything just works. It is the first place PHP programmers go in OO. It has a bunch of problems, as people have mentioned above. There are a number of proven patterns that can improve things, like Registries and Dependency Injection, but they require some upfront work to save time later -- and do not cause the problems inherent in static, global solutions.
But this is a very big subject...