平常总是说面向对象面向对象,但常常是在写一些过程化代码,2333;
这是我们的老师改进后,分享给我们的curl类,赞
<?php
namespace App\Services;
class CurlService
{
const GET = 0;
const POST = 1;
public $url;
public $ch = null;
private $type = 1;
public function __construct() {
}
public function init( $url , $type = self::POST)
{
$this->url = $url;
$this->ch = curl_init();
$this->type = $type;
return $this;
}
//post 方式传递数据
public function send($param)
{
if( self::POST == $this->type) {
return $this->posts($param);
} else {
return $this->gets($param);
}
}
public function posts($post_data)
{
curl_setopt( $this->ch, CURLOPT_URL, $this->url );
curl_setopt( $this->ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $this->ch, CURLOPT_HEADER, 0 );
curl_setopt($this->ch, CURLOPT_POST, 1);
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $post_data);
$output = curl_exec( $this->ch );
return $output;
}
public function gets($get_data)
{
$url = $this->url.'?'.http_build_query($get_data);
curl_setopt( $this->ch, CURLOPT_URL, $url );
curl_setopt( $this->ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $this->ch, CURLOPT_HEADER, 0 );
$output = curl_exec( $this->ch );
return $output;
}
}
//例子
$url = new CurlService();
//get
$curl->init('www.baidu.com',0)->send();
//post
$curl->init('www.baicu.com')->send('wd=1234');