2

I have been going through lots of examples on this, but the more I read the more I get confused (sorry!). My priority is keep it simple and efficient. Generate a single MySql connection and share it with multiple PHP objects.

// open a db connection 
$dbc = new PDO(.......);

// allow multiple objects to use the same connection

$object_1 = new class_1($dbc);
$object_2 = new class_2($dbc);
$object_3 = new class_3($dbc);

// or should it be passed this way?

$object_1->connection($dbc);
$object_2->connection($dbc);
$object_3->connection($dbc);

// or should each of the classes be getting the connection
// from a singleton type db object? 

// should each object be an extesion of a db class?

// or is there something else I need to consider?

2 Answers 2

1
// allow multiple objects to use the same connection

$object_1 = new class_1($dbc);
$object_2 = new class_2($dbc);
$object_3 = new class_3($dbc);

// or should it be passed this way?

$object_1->connection($dbc);
$object_2->connection($dbc);
$object_3->connection($dbc);

Both of these are correct, although if database connection is necessary for an object to work, then passing it to constructor is the preferred way.

For more information on this topic look up articles on Dependency Injection.

For example: http://martinfowler.com/articles/injection.html

Sign up to request clarification or add additional context in comments.

2 Comments

thanks! I have been led to believe that passing an object into another one this way results in it being copied not really passed. The implication being that somehow that reduces efficiency or causes other issues. Any thoughts?
In PHP4 it was copied, in PHP5 objects are always passed by reference. Variables, however, are still copied unless you specifically pass them by reference.
1

I preffer to make Connection Class as Singlton :

class DBConnection {
    // Store the single instance of DBConnection 
    private static $m_pInstance;

    private function __construct() { ... }

    public static function getInstance()
    {
        if (!self::$m_pInstance)
        {
            self::$m_pInstance = new DBConnection();
        }

        return self::$m_pInstance;
    }
} 

2 Comments

Thanks! I am starting to think this is the way I want to go too. I know this sounds dumb, but can I ask how you call the connection from with the classes that use it and do you use any kind of destruct to close the connection?
frankly , I used it in ASP.NET Not in PHP . and I copy this code from some site ..I thought it should be helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.