Вопрос

So i have an ever growing system in PHP where i have a static class that takes care of the database connection stuff.

<?php 
    class Database {
        // ... connection upon construction and ways of escaping the data
        public function query($query) {
            // performs query and returns the data.
        }
    }

    class API { // Not actually called api, but for the purposes of this
        private static $database = false;

        public static function GetDatabase() {
            if (static::$database === false) {
                static::$database = new Database(connection information)
            }
            return static::$database;
        }
    }
?>    

I also have alot of "controllers" or database adapters that perform specific sets of functionality.

<?php 
    class UserDBAdapter {
        public function newUser($info) {
            // validates and builds the query statements

            API::GetDatabase()->query($query);
        }
    }
?>

So the real question is that i need the UserDBAdapter here and there through out the code. Say in a couple different files and possibly in other controllers and i do not want to pass it in as a variable (it can get annoying when every method has it). I also do not want to create 2 of these objects (for speed purposes).

So could i do something the same as i do with $database object. I do not initialize them until they are called, which should be efficient, and they wont need to be recreated throughout an entire process, and no matter the scope. At least thats why i started this idea, but i do not know if its the best idear.

Thanks

Это было полезно?

Решение

I think what you are doing is fine, you're storing the database connection in a registry you can easily access throughout your project.

I guess, ideally, you could overwrite this with setDatabase and getDatabase methods in your other classes too, with API::getDatabase() as a fallback?

Zend Framework has Zend_Db_Adapter::getDefaultAdapter() which I've been known to use.. or I assign an adapter to the registry with Zend_Registry::set('dbAdapter', $dbAdapter). I know you aren't using Zend, but its an example of someone doing something similar.

Другие советы

Usually, the "controllers" you mention are managed as a separate class in a separate file.

Sometimes, are "singletons" one single item used in all application. And sometimes, have several copies, depending of it usage, and are called "entities".

You can learn more here: http://en.wikipedia.org/wiki/Object-Relational_Mapping

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top