Sometimes I have complicated find procedure开发者_如何转开发s and I'm feeling dirty to repeat this code in my Controller.
Now I am thinking, it is possible to do something like this:
class User extends BaseUser
{
private static function getTable()
{
return Doctrine_Core::getTable('User');
}
public static function findAll()
{
return getTable()->findAll();
}
public function currentEnrolments() {
$query = Doctrine_Query::create()
->from('Enrolment e')
->where('e.user_id = ?', $this->id)
->addWhere('e.finish_date IS NULL');
return $query->execute();
}
}
Is this a good practice? Or should I only put non static members like the query I have shown?
Generally, if it saves you time, there nothing to lose and every minute you can save to gain.
Functions like getTable
and findAll
are probably not saving you a lot, but custom queries for finding stuff more specific to your application will definitely be worth it.
I have got pretty much the same approach.
- I wouldn't bother with your static proxies of
getTable()
andfindAll()
.- That doesn't really add any value to your code
- I, personnaly, never call
findAll()
on any model object as you will generally need- to cross-check against a foreign key
- paginate / sort
- ...
- regarding your
currentEnrolments()
function, this is worth doing as you have a bit of logic on this->addWhere('e.finish_date IS NULL')
, thus explaining you can't use the "magic" Doctrine relation->Enrolment
. Maybe this is something Doctrine 2 is resolving, need to check this out ...
Regards
精彩评论