First Class problems

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: First Class problems

Post 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.
(#10850)
User avatar
psurrena
Forum Contributor
Posts: 355
Joined: Thu Nov 10, 2005 12:31 pm
Location: Broolyn, NY

Re: First Class problems

Post by psurrena »

That's really great! Thank you for all your help!
Post Reply