Hi.
I have created a "Data Access Object" for my Raw_Materials table. However there is a lot of redundant code! This is an example:
/**
* The Raw_Materials Data Access Object
*
* Represents the RawMaterials Data Structure of a Record.
*
* It uses the mysql connection object and functions as a
* container for common and complicated queries.
*
* @access public
*/
class Raw_Materials_dao {
protected $_connection; // protected so the variable cannot be accessed outside of the class.
public function __construct($connection)
{
$this->_connection = $connection;
}
public function get($id)
{
$sql = '
SELECT
`raw_materials`.`raw_material_id`,
`raw_materials`.`raw_material_name`,
`raw_materials`.`raw_material_unit`,
`raw_materials`.`raw_material_price`
FROM
`raw_materials`
WHERE (`raw_materials`.`raw_material_id` = '.$id.')';
return $this->_connection->query($sql);
}
public function get_all()
{
$sql = '
SELECT
`raw_materials`.`raw_material_id`,
`raw_materials`.`raw_material_name`,
`raw_materials`.`raw_material_unit`,
`raw_materials`.`raw_material_price`
FROM
`raw_materials`
';
return $this->_connection->query($sql);
}
public function search($request)
{
$sql = '
SELECT
`raw_materials`.`raw_material_id`,
`raw_materials`.`raw_material_name`,
`raw_materials`.`raw_material_unit`,
`raw_materials`.`raw_material_price`
FROM
`raw_materials`
WHERE `raw_material_name` LIKE \'%' . $request->get('search_term') . '%\'';
$result = $this->connection->query($sql);
return $result;
}
}
Is there a simple way that I can remove all the redundant code in the sql select statement? What is best practice to avoid this kind of "problems"?
Best regards.
Asbjørn Morell.