最近在看书的时候,书中的作者有讲到用php来实现链式写法,顿时让我感到很惊奇。这让我想起来了TP框架的链式写法:
Db(xxx)->where(xxx)->select();
然后通过在网上查阅了一些资料大致了解了它的实现原理:其实和我们平常写的class类没用区别,唯一有区别的就是要在每个方法里面返回当前对象给下一个方法继续调用,如return $this。基于此封装了一个简单的curl模拟post、get、上传文件的类方法。因为平常会用php写一些接口,自己用很方便。
<?php
/*
* Curl 模拟表单提交
*/
class CurlUploadFile{
/**
* @var $filepath 上传文件本地路径
* @var $address 上传地址
*/
protected $filepath;
protected $address;
/**
* @param String $url 需要模拟提交的地址
*/
public function url(string $url)
{
if(!$url){
throw new Exception('上传地址不存在');
}
$this->address = $url;
return $this;
}
/**
* @param String $path 文件路径
*/
public function path(string $path)
{
if(file_exists($path)){
$this->filepath = $path;
return $this;
}
throw new Exception('文件路径不存在');
}
/**
* @param Array $param 自定义参数
*/
public function post(Array $param)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->address);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_POST,1);
$param = $param;
if($this->filepath){
$param += $this->up_handle($ch);
}
curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
//curl_setopt($ch, CURLOPT_HEADER,1);
$request = curl_exec($ch);
curl_close($ch);
return $request;
}
/**
* @param resource $ch curl初始句柄文件
*
*/
protected function up_handle($ch)
{
$data = [];
if(class_exists('\CURLFile')) //这里做一下兼容处理,php5.6以后不允许使用@上传文件,官方的说法是为了安全因为@这个符号在php里也可以抑制错误
{
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);
$data = ['file' => new \CURLFile(realpath($this->filepath))];
}
else
{
if(defined('CURLOPT_SAFE_UPLOAD'))
{
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
}
$data = ['file' => "@{$this->filepath}"];
}
return $data;
}
/**
* @param Array $param 自定义参数
*/
public function get(Array $param)
{
$ch = curl_init();
$param = http_build_query($param);
$address = rtrim($this->address,'?') . '?' . $param;
curl_setopt($ch,CURLOPT_URL,$address);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_HEADER,1);
$request = curl_exec($ch);
curl_close($ch);
return $request;
}
}

732

被折叠的 条评论
为什么被折叠?



