Data Access Layer Best Practice

I'm looking for information on the best way to refactor the Data Access Layer (DAL) in my PHP web application. I am following the MVC pattern: PHP / HTML / CSS / etc. front panel views, PHP controllers / services in the middle, and PHP DALs sitting on top of a relational database in a model. Pretty standard stuff. Everything works fine, but my DAL is getting big (codemell?) And getting a little unwieldy.

My DAL contains almost all the logic for interacting with my database and is full of functions that look like this:

function getUser($user_id) {
   $statement = "select id, name from users where user_id=:user_id";
   PDO builds statement and fetchs results as an array
   return $array_of_results_generated_by_PDO_fetch_method;
}

      

Notes:

  • The logic in my controller only interacts with the model using functions like the above in the DAL
  • I am not using a framework (I am from the opinion that PHP is a template language and there is no need for the complexity of injecting through a framework)
  • I usually use PHP as a procedural language and tend to shy away from its OOP approach (I like OOP but prefer the complexity from PHP)

What approaches did you take when your DAL reached this point? Do I have a fundamental design problem? Should I just slice the DAL into multiple smaller files (split it logically)? Thanks.

+2


a source to share


2 answers


In terms of your architecture, each table in your DB should (usually) have its own model (PHP class), if you don't, then I would say you have a code smell.

If you have each table as a model, I wouldn't bother with the amount of code in each class. It's good to have "fat models" and "skinny controllers".

If you want to line up some code, you can use a lightweight data object wrapper, something like PEAR DB_DataObject . Some examples of what the DB_DataObject model looks like:




$user = new User;
$user->get($user_id);

      


$user = new User;
$user->name = 'foo';
$user->find();
while($user->fetch()) {
...
}

      

The advantage of using something like DB_DataObject is that you abstract away a lot of low-level PDOs and your class implementation will be more focused on your business logic.

+3


a source


May be a little distracted from the actual question, but you might be interested in a series of presentations by Toon Koppelaars, a fairly competent Oracle DB chap, on software architecture known (or I would, unfortunately, not known) as "The Declaration of Helsinki".

See http://thehelsinkideclaration.blogspot.com/2009/03/helsinki-declaration-observation-1.html



This concerns, perhaps a little sideways, but in any case, to a large extent, on the question of what your question is really about him.

+1


a source







All Articles