Manual Pembangunan Pengumpul QueryList
/ 插件開發(fā)指導
插件開發(fā)指導
QueryList插件開發(fā)指導
講解前先列出最后的整體目錄結構,假定www
目錄為當前的項目目錄:
www ├── querylist │ ├── Ext │ │ └── Hello.php │ ├── QueryList.php │ └── vendor │ └── testHello.php
演示的所有源碼打包下載:完整下載
一.下載QueryList項目到本地
安裝querylist
composer create-project jaeger/querylist
然后到querylist
目錄去執(zhí)行下面命令安裝AQuery
,AQuery
為所有插件的基類,插件必須繼承AQuery
并實現(xiàn)run()
方法.
composer require jaeger/querylist-ext-aquery
二.在querylist
目錄下新建Ext目錄
querylist/Ext
目錄可用于存放QueryList
擴展
三.在querylist/Ext
目錄下新建擴展文件Hello.php
<?php /** * QueryList的Hello擴展演示 */ namespace QL\Ext; class Hello extends AQuery { /** * 必須要實現(xiàn)run()方法 */ public function run(array $args) { //getInstance()方法用于獲取任意類的實例,默認獲取QueryList實例 $ql = $this->getInstance(); //設置QueryList對象的html屬性 $ql->html = $this->getHtml($args['url']); //返回QueryList對象 return $ql; } /** * 自定義一個抓取網頁源碼的方法 */ public function getHtml($url) { return file_get_contents($url); } }
<?php require 'querylist/vendor/autoload.php'; use QL\QueryList; $ql = QueryList::run('Hello',[ 'url' => 'http://www.baidu.com' ]); $data = $ql->setQuery([ 'title'=>['title','text'] ])->data; print_r($data); 輸出結果; Array ( [0] => Array ( [title] => 百度一下,你就知道 ) )
下面附加一些現(xiàn)有的插件源碼來加強理解
下面是Request
擴展的源碼:
<?php namespace QL\Ext; /** * @Author: Jaeger <hj.q@qq.com> * @version 1.0 * 網絡操作擴展 */ class Request extends AQuery { protected function hq(array $args) { $args = array( 'http' => isset($args['http'])?$args['http']:$args, 'callback' => isset($args['callback'])?$args['callback']:'', 'args' => isset($args['args'])?$args['args']:'' ); $http = $this->getInstance('QL\Ext\Lib\Http'); $http->initialize($args['http']); $http->execute(); if(!empty($args['callback'])){ $http->result = call_user_func($args['callback'],$http->result,$args['args']); } return $http; } public function run(array $args) { $http = $this->hq($args); $ql = $this->getInstance(); $ql->html = $http->result; return $ql; } }
擴展之間還可以繼承,下面的Login擴展繼承了Request擴展并重寫了run()方法:
<?php namespace QL\Ext; /** * @Author: Jaeger <hj.q@qq.com> * @version 1.0 * 模擬登陸擴展 */ class Login extends Request { private $http; public $html; public function run(array $args) { $this->http = $this->hq($args); $this->html = $this->http->result; return $this; } public function get($url,$callback = null,$args = null) { $result = $this->http->get($url); return $this->getQL($result,$callback,$args); } public function post($url,$data=array(),$callback = null,$args = null) { $result = $this->http->post($url,$data); return $this->getQL($result,$callback,$args); } private function getQL($html,$callback = null,$args = null) { if(is_callable($callback)){ $result = call_user_func($callback,$result,$args); } $ql = $this->getInstance(); $ql->html = $html; return $ql; } }