Question

I have a project am willing to create its files structured like this:

js
css
images
core
--- dblayer.class.php
--- user.class.php
--- comments.class.php
--- etc.class.php
index.php
users.php 

The DBLayer class inherits from PDO like this:

class DBLayer extends PDO
{
    public function __construct()
    {
        $options = array(
            PDO::ATTR_PERSISTENT => true,
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
        );

        $dsn = DB_DRIVER . ":host=" . DB_HOST . ";dbname=" . DB_NAME;
        parent::__construct($dsn, DB_USER, DB_PASSWORD, $options);
    }

    public function getLastId()
    {
    }

    public function getLastError()
    {
    }

    // Other general methods used frequently by other classes
}

The other classes will inherit from DBLayer class:

class User extends DBLayer
{
}

So, my question here: is this good practice in the term of performance, code reuse/ readability(the project may invite other developers in the future)?

No correct solution

OTHER TIPS

In general, no.

Inheritance is for IS-A relationships. You should inherit when you want all the methods of a class to be usable by its extended class.

Do you want calling code to be able to do this:

$user = new User('mysql:host=localhost;dbname=test', $user, $password);
$stmt = $user->query("SELECT * FROM Comments");

In other words, by giving access to general-purpose methods like query(), you allow someone to use the User object to query any unrelated data. That would be very confusing!

As @zerkms says in a comment, "User is not a database [connection]". That is what would be implied by User IS-A PDO.

This is a case where you should favor composition over inheritance. Each of your domain model classes, should HAS-A PDO object, which would give you an opportunity to avoid repeating code in every class.

Your usage would therefore be:

$pdo = new PDO(...);
$user = new User($pdo);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top