Page 3 of 3

Re: First Class problems

Posted: Wed Apr 09, 2008 12:52 am
by Christopher
Well my example above is generic, but you have to pass the whole SQL string. Maybe something like this where you just give it the specifics about what you want instead of full SQL:

Code: Select all

class TableGateway {
   protected $table;
   protected $columns;
   protected $orderby = '';
   protected $errorMsg = '';
 
   public function __construct($table, $columns='*') {
        $this->table = $table;
        $this->columns= $columns;
   }
 
   public function orderBy($orderby) {
        $this->orderby = " ORDER BY $orderby";
   }
 
   public function findAll() {
        $result=mysql_query("SELECT {$this->columns} FROM {$this->table}{$this->orderby}") or die (mysql_error());
 
        $thumbnails = array();
        if(mysql_num_rows($result) < 1){
            $this->errorMsg="There was no content found.";
        }else{
            while($row=mysql_fetch_array($result)){
                $thumbnails[] = $row;
        }
        return $thumbnails;
    }
}
 
$work= new TableGateway('work', 'id, title, image');
$work->orderBy('id ASC');
$rows = $work->findAll();
You could add find($id) or findWhere($sql) methods if you wanted ... and maybe a fluent interface. And your Work Model class could inherit this and set the $table, $columns and $orderby properties for you, like:

Code: Select all

class WorkModel extends TableGateway {
 
   public function __construct() {
        parent::__construct('work', 'id, title, image');
        $this->orderBy('id ASC');
   }
}
 
// and you are back to
$work= new WorkModel();
$rows = $work->findAll();
But now you can create nice Model classes with only a few lines of code.

Re: First Class problems

Posted: Thu Apr 10, 2008 2:32 pm
by psurrena
That's really great! Thank you for all your help!