tags:

views:

95

answers:

3

From the question itself:

class User
{
public function getByName($username)
{
//queries here
}

public function getById($id)
{
//queries here
}

}
A: 

Yes, it is correct. Models (in this case User) are an layer in MVC which connects controllers with the database so what they do is they actually creates SQL queries, execute it, interpret the results and then pass parsed data.

If you are using some PHP frameworks however this part in most of cases is taken cake by the framework. For example in CakePHP you have a "virtual" methods like findByName, findById etc. for every field in the database table the model references to. So if you are using a framework you may want to check first if it doesn't provide similar methods before you write your own.

RaYell
-1 the question is if a *library* can execute queries in the DB, not a model.
Alix Axel
+1  A: 

No. An entity should not be aware of any databases or other external information. For this you should use some sort of O/R-Mapper - like Doctrine.

Björn
I forgot to add that the User class is in the Libraries folder of the project, where my classes (which are real world entities) belong to. I am currently using ORM for this one but I may have messed it up by providing a controller that houses the entity's methods and another controller for registration. How should I be doing it instead?
I am currently looking at a couple of codes and here's what was done:in the class, there is a call to a model function that populates the properties...Hm...is that the proper way to do it? A call to an ORM function or a call to a query in a model?
You should populate your entities in the controller - correct. But I would have created a UserManager for CRUD-operations which will use Doctrine to populate the actual data source (your dbms). The Controller then instantiates the UserManager and perform registrations/updates/and so on.
Björn
A: 

Considering your "User" class is a Model class, I guess it would be OK...

But, still, you could go a bit farther, adding a new layer, and use :

  • a Model (User) class to store the User's data as seen by the application, and the corresponding business/logic-rules
  • a class that deals with the storage of that data (something like UserFinder, I suppose)
    • of course, that one would "know" the User class, and could populate it with data from the DB
    • and insert/update/delete "user" objects to/from the DB

This way, your User class wouldn't have to know how it is stored : it could be a DB, and XML file, a flat-file, whatever else, your User class would still be the same.

To make things easier, you could use some ORM Framework ; one really good in PHP is Doctrine.

Pascal MARTIN