Which one is better about PHP class for query?
I have PHP class that contain function for query data from database. The first one is
class x{
public $var1;
public $var2;
function __construct(){ }
function getX($primkey){
$sql = mysql_qyery("SELECT * FROM x_table WHERE primkey='$primkey'");
$row = mysq;_fetch_assoc($sql);
$this->var1 = $row['var1'];
$this->var2 = $row['var2'];
}
}
and another on is
class x{
public $var1;
public $var2;
function __construct(){ }
function getX($primkey){
$sql = mysql_qyery("SELECT * FROM x_table WHERE primkey='$primkey'");
$row = mysq;_fetch_assoc($sql);
return $row;
}
}
two class has some difference on function getX(). The first class put data from database to class variables but the second one return whole data from database via array.
I would like to know about开发者_C百科 performance of two class, which one is better. and which one is good for programming or any idea?
Regards.
With the first form, you have the flexibility to do additional conversions and asymmetrical mappings. So in that sense, you're truly creating a Model class that does an abstract representation of your actual data source.
With the second form, if you follow the Convention Over Configuration (CoC) paradigm and clearly define your conventions, it may work. But, down the line, you may run into situations where you'll have to make exceptions. I would recommend the more flexible approach above, as an anticipation of future exceptions.
Tangential: In case you're not writing your own object mappings purely for educational purposes, or for some other plausible reason, have you looked at RedBeanPHP or other alternatives?
class x{
public $row;
function __construct(){ }
function getX($primkey){
$sql = mysql_qyery("SELECT * FROM x_table WHERE primkey='$primkey'");
this->$row = mysq;_fetch_assoc($sql);
}
}
My suggestion is this. You have encapsulation incorprated properly and its dynamic accomodating future requirements too.
Perhaps you can add getter function also.
I would create a Database Adapter, then create a Data Mapper and work with a model that uses the Data Mapper.
In which case a call to $model->find() calls the objects find method, which calls the Data Mapper find method which issues queries to the Database Adapter.
精彩评论