Completely abstracting the database layer in php

I’ve searched but I couldn’t find anything decent, so sorry if this is a repeated question.

Basically, I’m going to be making a large site soon, and I want to make it as good as possible.

One of my bad (is it?) habits is including database logic within objects. For instance:

$user = new User();
$user->login('username', 'password');
// Check if $user is false etc

So i need to start abstracting it out, using data mappers. e.g.

$user = UserDataMapper::LoadUser('username', 'password');
// Check if $user is false etc

Is this a better method?

I was then curious as to how I can extend this. What if an object needs access to the database, loading in admin sections for example. Would I have an AdminSectionDataMapper?

A data mapper for each class that needs access to the database seems extreme, but then merging them all into one mapper also seems silly.

Am I going about this the right way? Or is there a simpler/different method?

Thanks in advance!

Even if can answer the question, some basic pointers on php5 oop best practices would be awesome!

I don’t think there is anything wrong with having database code in php objects, provided it is appropriate for your application.

Typically, I have a class that manages the product categories in a database. I usually create a database connection in the script ($conn), outside of the class, and then pass the connection to the class via the class constructor when instantiating the class. The class then uses that $conn in its methods to add/edit/delete categories in the database.

I had thought about passing in a db object, seemed like a good way to separate the two classes, but it’d still create some coupling.

I might just keep it how I’ve got it, but I’m still not comfortable with it.

Thanks for the reply :slight_smile: