插件開發指導
QueryList外掛程式開發指導
講解前先列出最後的整體目錄結構,假定www
目錄為目前的專案目錄:
www ├── querylist │ ├── Ext │ │ └── Hello.php │ ├── QueryList.php │ └── vendor │ └── testHello.php
示範的所有原始碼打包下載:完整下載
一.下載QueryList項目到本地
安裝querylist
composer create-project jaeger/querylist
然後到querylist
目錄去執行下面指令安裝AQuery
,AQuery
為所有外掛程式的基類,外掛必須繼承AQuery
並實作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 { /** * 必须要实现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] => 百度一下,你就知道 ) )
#下面附加一些現有的插件原始碼來加強理解
下面是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; } }