5

I have a class that helps me to handle users. For example:

$user = new User("login","passw");
$name = $user->getName();
$surname = $user->getSurname();
$table = $user->showStats();

All these methods have SQL queries inside. Some actions require only one sql queries, some - more than one. If database structure changes - it will be difficult to change all queries (class is long). So I thought to keep SQL queries away from this class. But how to do this?

After reading this question I've known about Stored Procedures. Does it mean, that now one action requires only one SQL query (call of Stored Procedure)? But how to organize separation sql from php? Should i keep sql-queries in an array? Or may be it should be an sql-queries class. If yes, how to organise this class (maybe what pattern I should learn)

Community
  • 1
  • 1
Larry Foobar
  • 11,092
  • 15
  • 56
  • 89
  • If your database schema changes, you will be forced to change the code that maps this schema to PHP. There is no magic dust that will do this automatically. Stored procedures don't change anything in this case, because you then move the problem to having to edit the stored procedures. – Jon May 08 '11 at 12:03
  • @Jon: How would the separation occur. I mean, the change wont happen in one snap, but if you had to go through every single PHP file, that may be exhaustive. – Shamim Hafiz - MSFT May 08 '11 at 12:07
  • @Jon, I understand this. But if I have sql queries inside PHP-code, and it's about 2k lines of code (but sql-queries are about hundred lines) - you'll be scrolling your code and may miss some sql queries. But if you have file (class, or array) with only sql-squeries - it is easier to change them – Larry Foobar May 08 '11 at 12:07
  • If the code is well structured you won't really have such a problem. If each method just executes different hardcoded SQL, then you will have a problem sure. – Jon May 08 '11 at 12:11

4 Answers4

5

This is a surprisingly large topic, but I have a few suggestions to help you on your way:

You should to look into object-relational mapping, in which an object automatically generates SQL queries. Have a look at the Object-Relational Mapping and Active Record articles for an overview. This will keep your database code minimal and make it easier if your table structure changes.

But there is no silver bullet here. If your schema changes you will have to change your queries to match. Some people prefer to deal with this by encapsulating their query logic within database views and stored procedures. This is also a good approach if you are consistent, but keep in mind that once you start writing stored procedures, they are going to be tied heavily to the particular database you are using. There is nothing wrong with using them, but they are going to make it much more difficult for you to switch databases down the road - usually not an issue, but an important aspect to keep in mind.

Anyway, whatever method you choose, I recommend that you store your database logic within several "Model" classes. It looks like you are doing something similar to this already. The basic idea is that each model encapsulates logic for a particular area of the database. Traditionally, each model would map to a single table in the DB - this is how the Ruby on Rails active record class works. It is a good strategy as it breaks down your database logic into simple little "chunks". If you keep all of the database query logic within a single file it can quickly grow out of control and become a maintenance nightmare - trust me, I've been there!

To get a better understanding of the "big picture", I recommend you spend some time reading up on web Model-View-Controller (MVC) architecture. You will also want to look at the established PHP MVC frameworks, such as CodeIgniter, Kohaha, CakePHP, etc. Even if you do not use one - although I recommend you do - it would be helpful to see how these frameworks organize your code.

Justin Ethier
  • 131,333
  • 52
  • 229
  • 284
2

I would say you should look into implementing the "repository" design pattern in your code.

A good answer to how to implement this would be too long for this space, so I'll post a couple of PHP-oriented references:

travis swicegood -- Repository Pattern in PHP

Jon Lebensold -- A Repository Pattern in PHP

Faust
  • 15,130
  • 9
  • 54
  • 111
1

You are on the right lines if you use separation of concerns to separate your business logic from your data access logic you will be in a better place.

amelvin
  • 8,919
  • 4
  • 38
  • 59
  • Any references on studying how this should be done with PHP&MySQL? – Shamim Hafiz - MSFT May 08 '11 at 12:09
  • I have separation php&html, but what about php&sql? – Larry Foobar May 08 '11 at 12:14
  • @Innuendo If you separate all your data access code into a bunch of data access classes (so that they are separated from your business logic code) your business classes can then call them to create, read, update or delete data. Like all good patterns this works for just about any high level language. I like using stored procedures, but whether you use stored procedures or parameterized sql embedded in the data access classes the more important start point is to keep the sql access separate. – amelvin May 08 '11 at 13:31
  • @Gunner separation of concerns is not a language specific concept - it works for all high level languages. But this is IBMs take on separation of concerns in php - http://www.ibm.com/developerworks/opensource/library/os-php-objectorient/ – amelvin May 08 '11 at 13:34
1

Judging by your "there are already 2K lines of code" statement, you're either maintaining something, or midway through developing something.

Both Faust and Justin Ethier make good recommendations - "how should I separate my database access from my application code" is one of the oldest, and most-answered, questions in web development.

Personally, I like MVC - it's pretty much the default paradigm for web development, it balances maintainability with productivity, and there are a load of frameworks to support you while you're doing it.

You may, of course, decide that re-writing your app from scratch is too much effort - in which case the repository pattern is a good halfway house.

Either way, you need to read up on refactoring - getting from where you are to where you want to be is going to be tricky. I recommend the book by Fowler, as a starter.

Could you explain more about why your database schema may change? That's usually a sign of trouble ahead.....

Justin Ethier
  • 131,333
  • 52
  • 229
  • 284
Neville Kuyt
  • 29,247
  • 1
  • 37
  • 52
  • It's my first big project. There was written php code (from ex-programmer) - it wass terrible code (html+php+sql in a few files). I threw this code away, and wrote new html markup and php code (without html inside - with templating engine). But database is very huge and messy (mysql db + pgsql db with relations between them) and I heard that new database-programmer is wanted to rewrite whole database. So in soonest time I'll have to change all queries =( – Larry Foobar May 08 '11 at 13:08
  • then I'd definitely see if you can migrate to an MVC framework - the good news about things like CakePHP etc. is that they take a lot of the physical database access code away from you. The bad news is that they don't make changes to the database schema any nicer than any other framework... – Neville Kuyt May 08 '11 at 18:05
  • Yeah, I understand - migration to MVC - is my way (I've already read about MVC and glanced in the direction of Zend Framework). But I have no time for studying this (for exactly this project, for next - I'll have time =) ). Russian business - they give you bad code, ask to rewrite or write a new one, and give very little time =) – Larry Foobar May 08 '11 at 20:36