w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Is extending classes good practice?

Simple rule of thumb: if a class extends another, then that class is that parent class (only slightly altered or extended). You can pass this child class instead of the parent class. Example:

class Foo { }

class Bar extends Foo { }

function baz(Foo $foo) { }

baz(new Bar);

This works, baz() expects a Foo but also accepts a Bar, because Bar is a Foo.

Now, is your Users a Database? No. Your users are not a database. Your users use a database. If at all, you should use composition:

class User {

    protected $database;

    public function __construct(Database $database) {
        $this->database = $database;
    }

}

A class should be what its responsibilities are. The responsibility of a user management class is to manage user data. Part of that may involve talking to a database, but that doesn't mean the user management class is a database. If User extends Database, that means it can do everything the Database class can do (and more). That means you could use the User class everywhere instead of the Database class, and that doesn't make any sense. Keep responsibilities separate.

Now, it's still debatable whether that is the right structure or not, but it goes into the right direction. But you may really want to have a User class, which represents one user. You then have a UserManager or UserORM or UserStorage or whatever, which is concerned with retrieving and storing User objects in a database. This class in turn uses a Database to do just that. That keeps responsibilities clear and separated. The User class represents user data, the Database class interacts with the database, the UserORM/Manager/whatever in the middle negotiates between the two.





© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.