It is returning something. I’m using ez_sql, and by default it returns objects instead of arrays. I do get a result and can print the id, etc. If I change findbyid() to a static method, then do
I don’t know whats going on but the code siniplet you provided says, findbyid is not returning an object of Model. But what ever “$db->get_row” is returning is not a class of Model.
Returning an object of stdClass not an object of Model. (The name of the class in your snipplet is named Model) Thus when you try and call a method that only exists within the Model object it fails.
From the documentation I am not seeing any direct method to change the mapping to a custom class, looks like its either an array or stdClass. If you want to create a new instance of model you would need to do that manually. Something like this is how I would recommend doing it using a proper mapper pattern.
(untested)
class ModelMapper {
protected
$_db;
public function __construct($db) {
$this->_db = $db;
}
public function findById($id) {
$row = $db->get_row('SELECT id,name,profile_photo FROM models WHERE id='.$id);
return $row?$this->_map($row):null;
}
protected function _map($row) {
$model = new Model();
$model->id = $row->id;
$model->name = $row->name;
$model->profile_photo = $row->profile_photo;
return $model;
}
}
class Model {
public
$id
,$name
,profile_photo;
public function getProfilePhotoPath() {
return MEDIA.'/'.$this->name.'/photos/'.$this->profile_photo;
}
}
$mapper = new ModelMapper($db);
$model = $mapper->findById(45);
echo $model->getProfilePhotoPath();
Probably be good to add some exception checking in some places but that would be the gist of it.
Lastly, model is probably a bad name. It looks like your dealing with users if so use user instead. Name the classes and table based the context from the domain, not something generic like “model”. Naming something so generically is likely to cause confusion and/or conflict down the line. Try to be as specific and consistent with naming as possible without getting to convoluted. That will make the code easier to read later down the line for everyone involved.
Oddz, your example worked. I Googled object class mapper and couldn’t really find any examples or tutorials on the method you used - I found results on ORM (which I’m using) and actual maps, which isn’t so helpful.
I’d like to know more about this. Is there a site/article you could recommend to me?