From the question itself:
class User
{
public function getByName($username)
{
//queries here
}
public function getById($id)
{
//queries here
}
}
From the question itself:
class User
{
public function getByName($username)
{
//queries here
}
public function getById($id)
{
//queries here
}
}
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.
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.
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 :
User
) class to store the User's data as seen by the application, and the corresponding business/logic-rulesThis 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.