What is the best practice for passing a database connection object to a PHP class for improved code reusability?
When passing a database connection object to a PHP class for improved code reusability, it is best practice to use dependency injection. This means injecting the database connection object into the class constructor or a setter method, rather than creating the connection inside the class itself. This allows for better separation of concerns and makes the class more flexible and easier to test.
<?php
class Database
{
private $connection;
public function __construct($connection)
{
$this->connection = $connection;
}
public function query($sql)
{
// Use $this->connection to execute the query
}
}
// Create a database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Pass the database connection object to the class
$database = new Database($pdo);
// Use the database object to execute queries
$database->query('SELECT * FROM table_name');
?>
Related Questions
- What are the best practices for handling form submission in PHP to ensure that error messages are displayed only when the form is submitted?
- How can the PHP function "pathinfo()" be utilized to determine the file extension of a given file, and how can this information be used to selectively delete files based on their extension?
- What are best practices for utilizing the Bitbucket API in PHP to automate ticket creation for error reporting?