2

This is not really a problem but more of a question. My question is how it's 'supposed to be' programmed. It might not be too clear to explain, though.

So my question is; do I have to make multiple methods to retrieve data from a database? For example, I have a table called FRUITS. It contains the ID, name and date the fruit was added. Now I want to get the name of the fruit based on a given ID, and later on in the script I want to get the date of the fruit as well.

Should I make one method such as get_fruit($id) which returns both the name and date, or two separate methods get_name($id) and get_date($id)?

Thanks in advance.

3 Answers 3

3

You should use one object which would contain all the required data. For example:

class Fruit {

    protected ... variables;

    public function getId() {...}
    public function getDate() {...}
    ...

}

Also implementing __set and __get would be nice example of using full php potential.

You also may implement save() method (or extend database row class, such as Zend_Db_Table_Row.

So whole code would look like:

$fruit = $model->getFruid( 7); // $id = 7 :)
echo $fruit->id; // would call internally $fruit->__get( 'id')
echo $fruit->date;

// And modification:
$fruit->data = '2011-08-07';
$fruit->save();

EDIT: using separate methods to load certain data is useful (only?) when you need to load large amount of data (such as long texts) which is required only on one place in your code and would affect performance.

EDIT 2: (answer to comment): __get and __set are called when you try to access undefined property of an object, for example:

class Foo {
     public $bar;
     public function __get( $name){
         echo $name "\n";
         return 'This value was loaded';   
     }
}

// Try to use
Foo $foo;
echo $foo->bar . "\n";
echo $foo->foo . "\n";

There are two "large" approaches to this that I know about:

// First use __get and __set to access internal array containing data
class DbObject {
protected $data = array();

public function __get( $propertyName){
    // Cannot use isset because of null values
    if( !array_key_exits( $propertyName,$this->data)){
         throw new Exception( 'Undefined key....');
    }

    return $this->data[ $propertyName];
}

// Don't forget to implement __set, __isset
}

// Second try to call getters and setter, such as:
class DbObject {
public function getId() {
   return $this->id;
}

public function __get( $propertyName){
    $methodName = 'get' . ucfirst( $propertyName);
    if( !method_exits( array( $this, $methodName)){
        throw new Exception( 'Undefined key....');
    }
    return $this->$methodName();
}
}

To sum up... First approach is easy to implement, is fully automatized... You don't need large amount of code and sources would be pretty much the same for every class. The second approach required more coding, but gives you a better control. For example:

public function setDate( $date){
    $this->date = date( 'Y-m-d h:i:s', strtotime( $date));
}

But on the other hand, you can do this with first approach:

class Fruit extends DbObject {
public function __set( $key, $val){
  switch( $key){
     case 'date':
       return $this->setDate( $val);

     default:
       return parent::__set( $key, $val);
  }
}
}

Or you can use total combination and check for getter/setter first and than try to access property directly...

Sign up to request clarification or add additional context in comments.

1 Comment

Clear explanation. Thanks. __set and __get should be used for what exactly? I read inaccessible objects (so..Private objects?)
0

here is the code how you can use the one function to get different field's value.

function get_fruit($id,$field = ''){

   $sql = "select * from table_name where id = $id";
   $result = mysql_fetch_object(mysql_query($sql));

   if($field != ''){
     return $result->$field;
   }else{
     return $result;
   }
}

echo get_fruit(1,'field_name');

Comments

0
class  data_retrieve
{
    public $tablename;
    public $dbname;
    public $fieldset;
    public $data_array;
    public $num_rows
    function __construct()
    {
        $this->tablename='junk';
        $this->dbname='test';
        $this->fieldset=array('junk_id');   

    }
function getData($where_str)
    {
        $this->data_array= array();

                   global $dbconnect, $query;
        if($dbconnect ==0 )
        {
            echo" Already Connected \n ";
            $dbconnect=db_connect("objectdb") or die("cannot connect");
        }

        $where_str;

        if(empty($where_str))
        {
            $where_str=NULL;
        }
        else
        {
             $where_str= "where". $where_str ;
        }

$query= "select * from $this->tablename $where_str";
$record= mysql_query($query) or die($query);
        $recNo=mysql_num_rows($record); 

        $this->num_rows=$recNo;
                    while($row= mysql_fetch_assoc($record))
        {
            $this->data_array[]=$row;
        }

        mysql_free_result($record);

        return $this->data_array;
}

class fruit extends data_retrieve
{

function __construct()
    {
        parent::__construct();
        $this->tablename='fruit';
        $this->fieldset=array('fruit_id','fruit_name','date');

    }
}

then in your file create a fruit object like

$str="fruit_id=5";
$fruit_data = new  fruit();

$records=$fruit_data->getData($str);

to display

foreach($records as $row )
{
print <<< HERE
<label class='table_content' > $row[fruit_id]</label>
<label class='table_content' > $row[fruit_name]</label>
<label class='table_content' > $row[date]</label>
HERE;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.