重构雄辩的回调

时间:2015-07-03 22:19:24

标签: php laravel callback eloquent

有没有办法重构这个功能?我想在回调中重用重复的代码。我不知道从哪里开始,我不仅有更多的方法,重复使用重复的代码会有所帮助。

public static function addedPaginatedUrls($crawl_id, $cmp_crawl_id) {
    return UrlStatus::paginated($crawl_id)
        ->whereNotIn('url.url', function ($sql) use($cmp_crawl_id) {
            // START REPEATED CODE
            $sql->select('url.url')->from('url_status')
            ->join('url', 'url.id', '=', 'url_status.url_id')
            ->join('crawl', 'crawl.id', '=', 'url_status.crawl_id')
            ->where('url_status.crawl_id', '=', $cmp_crawl_id)
            // END REPEATED CODE
            ->where('url_status.pagination', '<>', '')
            ->whereNotNull('url_status.pagination');
        });
}

public static function addedCanonicalUrls($crawl_id, $cmp_crawl_id) {
    return UrlStatus::canonical($crawl_id)
        ->whereNotIn('url.url', function ($sql) use($cmp_crawl_id) {
            // START REPEATED CODE
            $sql->select('url.url')->from('url_status')
            ->join('url', 'url.id', '=', 'url_status.url_id')
            ->join('crawl', 'crawl.id', '=', 'url_status.crawl_id')
            ->where('url_status.crawl_id', '=', $cmp_crawl_id)
            // END REPEATED CODE
            ->whereNotNull('url_status.canonical');
        });
}

1 个答案:

答案 0 :(得分:0)

你可以在你的模型上创建一个静态方法,虽然我不知道这是否有意义,因为我不知道你的所有app逻辑。

在您的UrlStatus模型中:

CREATE TEMPORARY TABLE IF NOT EXISTS query AS (SELECT t1.categoryid AS lev1, t2.categoryid as lev2, t3.categoryid as lev3, t4.categoryid as lev4
FROM category AS t1
  LEFT JOIN category AS t2 ON t2.parent = t1.categoryid
LEFT JOIN category AS t3 ON t3.parent = t2.categoryid
LEFT JOIN category AS t4 ON t4.parent = t3.categoryid
WHERE t1.categoryid = 4149418031))

SELECT lev1 AS category_value FROM query
  UNION
SELECT lev2 AS category_value FROM query
  UNION
SELECT lev3 AS category_value FROM query
  UNION
SELECT lev4 AS category_value FROM query;

然后在你的代码中静静地调用它:

public static function repeatedCodeRefractoringNameItWhateverYouWant($sql, $cmp_crawl_id){
    // START REPEATED CODE
    return $sql->select('url.url')->from('url_status')
    ->join('url', 'url.id', '=', 'url_status.url_id')
    ->join('crawl', 'crawl.id', '=', 'url_status.crawl_id')
    ->where('url_status.crawl_id', '=', $cmp_crawl_id);
    // END REPEATED CODE
}

如果应该通过某些或所有模型共享重复的代码,只需使用此方法创建一个新的Model类,并从中扩展所有模型