...">

How to separate sql from php code

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

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

All of these methods contain SQL queries inside. Some actions require only one sql query, some more than one. If the database structure changes, it will be difficult to change all the queries (the class is long). Therefore, I decided to leave SQL queries from this class. But how to do that?

After reading this question, I knew about stored procedures. Does this mean that only one SQL query is required for a single action (call to a stored procedure)? But how to organize sql separation from php? Should I store sql queries in an array? Or maybe it should be a class of sql queries. If so, how to organize this class (maybe which template should I learn)

+5
source share
4 answers

This is an amazingly big topic, but I have a few tips to help you along the way:

You should study the object-relational mapping in which the object automatically generates SQL queries. See Object Relational Mapping and Active Article Entry for an overview. This will cause the database code to be minimal and simplified if your table structure changes.

. , . , . , , , , , . , - , , .

, , "". , - . , . - Ruby on Rails. , "". , - - , !

" ", - Model-View-Controller (MVC). PHP MVC, CodeIgniter, Kohaha, CakePHP .. , - , , .

+5

, , - , .

+1
+1

" 2K ", -, - .

, - " " -.

MVC - -, , , , .

, , , - - - .

In any case, you need to read about refactoring - getting from where you want it will be difficult. I recommend Fowler's book as a starter.

Could you explain why your database schema may change? This is usually a sign of trouble ahead .....

+1
source

All Articles