php - quick refactoring
I have 2 methods, that are pretty much exactly the same and I'd likie someone to help me refactor them:
public static function searchFromVideoRequest($word, $returnPropelObjects = false)
{
$c = new Criteria();
$c->addJoin(YoutubeVideoPeer::ID,ItemPeer::YOUTUBE_VIDEO_ID开发者_高级运维);
$c->addSelectColumn(self::TITLE);
$c->addSelectColumn(self::ID);
$c->add(ItemPeer::TITLE, '%'.$word.'%', Criteria::LIKE);
$c->addAnd(self::YOUTUBE_VIDEO_ID, null, Criteria::ISNOTNULL);
$c->addAscendingOrderByColumn(self::TITLE);
if ($returnPropelObjects)
return self::doSelect($c);
$stmt = self::doSelectStmt($c);
$results = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$results[] = $row;
}
return $results;
}
public static function searchFromFlickrRequest($word, $returnPropelObjects = false)
{
$c = new Criteria();
$c->addJoin(FlickrPhotoPeer::ID,ItemPeer::FLICKR_PHOTO_ID);
$c->addSelectColumn(self::TITLE);
$c->addSelectColumn(self::ID);
$c->add(ItemPeer::TITLE, '%'.$word.'%', Criteria::LIKE);
$c->addAnd(self::FLICKR_PHOTO_ID, null, Criteria::ISNOTNULL);
$c->addAscendingOrderByColumn(self::TITLE);
if ($returnPropelObjects)
return self::doSelect($c);
$stmt = self::doSelectStmt($c);
$results = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$results[] = $row;
}
return $results;
}
Thanks
To refactor such methods you can split up them into a few methods that will contain common code and make them private, so no one can use them outside the class:
public static function searchFromVideoRequest($word, $returnPropelObjects = false)
{
$c = self::buildSearchCriteria($word);
$c->addJoin(YoutubeVideoPeer::ID,ItemPeer::YOUTUBE_VIDEO_ID);
$c->addAnd(self::YOUTUBE_VIDEO_ID, null, Criteria::ISNOTNULL);
return self::getSearchResult($c, $returnPropelObjects);
}
public static function searchFromFlickrRequest($word, $returnPropelObjects = false)
{
$c = self::buildSearchCriteria($word);
$c->addJoin(FlickrPhotoPeer::ID,ItemPeer::FLICKR_PHOTO_ID);
$c->addAnd(self::FLICKR_PHOTO_ID, null, Criteria::ISNOTNULL);
return self::getSearchResult($c, $returnPropelObjects);
}
private static function buildSearchCriteria($word)
{
$c = new Criteria();
$c->addSelectColumn(self::TITLE);
$c->addSelectColumn(self::ID);
$c->add(ItemPeer::TITLE, '%'.$word.'%', Criteria::LIKE);
$c->addAscendingOrderByColumn(self::TITLE);
return $c;
}
private static function getSearchResult($c, $returnPropelObjects)
{
if ($returnPropelObjects)
return self::doSelect($c);
$stmt = self::doSelectStmt($c);
$results = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$results[] = $row;
}
return $results;
}
PS: And I think the question is OK.
精彩评论