PHP - 继承一个抽象类和一个带有覆盖方法的具体类



简介

我正在从事一个扫描网站漏洞威胁的项目。因此,我需要编写一个蜘蛛来索引所有页面。

我正在使用两个库的组合来编写蜘蛛程序。

1) SymfonyComponentBrowserKitClient //is a abstract class
2) mmerianphpcrawlPHPCrawler //is a concrete class with override function

为了使用它们,需要扩展它们,因为一个是抽象的,另一个具有覆盖功能,我需要使其实用。

PHP 不允许多重继承,有没有办法解决这个问题?

蜘蛛.php

<?php
namespace AppCore;
use PHPCrawler; //I need to inherit this object
use PHPCrawlerDocumentInfo;
use SymfonyComponentBrowserKitClient as BaseClient;

class Spider extends BaseClient
{
private $url;
private $phpCrawler;
public function __construct($url){
parent::__construct();
//I have instantiated the object instead of inheriting it.
$this->phpCrawler = new PHPCrawler;
$this->url = $url;
}
public function setup(){
$this->phpCrawler->setURL($this->url);
$this->phpCrawler->addContentTypeReceiveRule("#text/html#"); 
$this->phpCrawler->addURLFilterRule("#.(jpg|jpeg|gif|png|css)$# i"); 
}
public function start(){
$this->setup();
echo 'Starting spider' . PHP_EOL;
$this->phpCrawler->go();
$report = $this->phpCrawler->getProcessReport();
echo "Summary:". PHP_EOL; 
echo "Links followed: ".$report->links_followed . PHP_EOL; 
echo "Documents received: ".$report->files_received . PHP_EOL; 
echo "Bytes received: ".$report->bytes_received." bytes". PHP_EOL; 
echo "Process runtime: ".$report->process_runtime." sec" . PHP_EOL;
if(!empty($this->phpCrawler->links_found)){
echo 'not empty';
}
}
//Override - This doesn't work because it is not inherit
public function handleDocumentInfo(PHPCrawlerDocumentInfo $pageInfo){
$this->parseHTMLDocument($pageInfo->url, $pageInfo->content);
}
public function parseHTMLDocument($url, $content){
$crawler = $this->request('GET', $url);
$crawler->filter('a')->each(function (Crawler $node, $i){
echo $node->attr('href');
});
}
//This is a abstract function
public function doRequest($request){}
}

我已经找到了解决问题的方法。

我用自己的具体类扩展了抽象类(浏览器工具包\客户端(,就像BaseClient extends Client一样。这样就可以在Spider类中实例化BaseClient,而不是扩展它。此外,Spider类现在可以使用PHPCrawler进行扩展,以便可以调用覆盖函数handleDocumentInfo

解决方案的类结构

Core/
- BaseClient //extends BrowserKitClient
- Spider //extends PHPCrawl

最新更新