【问题标题】:I need help avoiding duplicate code (copy pasting code twice)我需要帮助避免重复代码(复制粘贴代码两次)
【发布时间】:2018-04-01 19:52:37
【问题描述】:

我一直在努力提高我的编程技能,到目前为止我都是在线学习的。但我找不到避免重复代码的方法。这是我的代码:

public function Curl($page, $check_top = 0, $pages = 1, $pagesources = array()){
//$page is the URL
//$check_top 0 = false 1 = true. When true it needs to check both false & true
//$pages is the amount of pages it needs to check.

        $agent = "Mozilla/5.0 (Windows NT x.y; Win64; x64; rv:10.0) Gecko/20100101 Firefox/10.0";

try{
        for($i = 0; $i < $pages; $i++){
            $count = $i * 25; //Page 1 starts at 0, page 2 at 25 etc.. 
            $ch = curl_init($page . "/?count=" . $count);
            curl_setopt($ch, CURLOPT_USERAGENT, $agent);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_TIMEOUT, 60);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            $pagesource = curl_exec($ch);
            $pagesources[] = $pagesource;
        }

        if($check_top == 1){
            for($i = 0; $i < $pages; $i++){
                $count = $i * 25;
                $ch = curl_init($page . "/top/?sort=top&t=all&count=" . $count);
                curl_setopt($ch, CURLOPT_USERAGENT, $agent);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_TIMEOUT, 60);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                $pagesource = curl_exec($ch);
                $pagesources[] = $pagesource;
            }
        }

}  catch (Exception $e){
echo $e->getMessage();
}
return $pagesources;

}

我正在尝试做的事情: 我想从特定页面范围(例如 1 到 5 页)中获取 HTML 页面源。有首页和标准页面,我想从页面范围内获取来源。所以我的代码工作正常,但很明显;一定有更好的办法。

【问题讨论】:

  • 可以通过将重复代码包装在函数或类中来避免重复代码。只需为 curl 操作编写一个函数。
  • 例如,我将如何处理这个问题?我需要传递的数据是动态的。 2 个独立的功能,一个用于首页,一个用于标准页面? @Marcel

标签: php code-duplication


【解决方案1】:

这是一个简短的示例,您可以如何通过编写函数并一起使用它们来避免重复代码。

class A
{
    public function methodA($paramA, $paramB, $paramC)
    {
        if ($paramA == 'A') {
            $result = $this->methodB($paramB);
        } else {
            $result = $this->methodB($paramC);
        }

        return $result;
    }

    public function methodB($paramA)
    {
        // do something with the given param and return the result
    }
}

$classA = new Class();
$result = $classA->methodA('foo', 'bar', 'baz');

上面给出的代码显示了一个带有两个方法的简单类。当您在示例中将函数 Curl 声明为公开时,我猜您正在使用一个类。上面例子中的类是非常基础的。它在类的nethodA 方法中以不同的参数调用方法methodB

这对你意味着什么?您必须找出您的辅助函数需要哪些参数。如果你知道它需要哪些参数,只需编写另一个类方法,它使用给定的参数执行 curl 函数。像馅饼一样简单。

如果您不熟悉在 php 中使用类和方法,我建议您阅读文档,其中描述了类、方法和成员的基本功能:http://php.net/manual/en/classobj.examples.php

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-03
    • 2014-03-07
    相关资源
    最近更新 更多