概述
简单引用单例模式
将单例类文件放入到TP核心库下
D:phpstudy_proWWWprojecttp51thinkphplibrarythink
声明命名空间
namespace think;
<?php
//加入命名空间
namespace think;
/**
* @var HttpClient
*/
class HttpClient
{
/**
* @var 请求的路径
*/
private $url;
/**
* @var 请求方式
*/
private $method;
/**
* @var 请求参数
*/
private $param;
/**
* @var 请求头
*/
private $header;
/**
* @var 响应结果
*/
private $response;
//1.创建一个静态私有变量存放实例化的对象
private static $instance;
//2.创建一个私有构造函数
private function __construct()
{
}
//3.防止外部克隆该类
private function __clone()
{
}
//4.防止序列化
private function __wakeup()
{
}
//5.提供唯一的静态入口
public static function getInstance()
{
//判断$instance变量是否是HttpClient类的实例,如果不是,则实例化本身,如果是则直接返回
//instanceof 用于确定一个 PHP 变量是否属于某一类 class 的实例
if(!(static::$instance instanceof static )){ //static 换成self也可以,只不过static比self更精准些
static::$instance = new static;
}
return static::$instance;
}
/**
* @var 设置请求路径
*
* @param string url
*
* @return HttpClient
*/
private function setUrl(String $url = '')
{
$this->url = $url;
return $this;
}
/**
* @var 设置请求参数
*
* @param array param
*
* @return HttpClient
*/
private function setParam(Array $param)
{
$this->param = http_build_query($param);
return $this;
}
/**
* @var 设置请求头部
*
* @param array header
*
* @return HttpClient
*/
private function setHeader(Array $header)
{
foreach ($header as $key => $value) {
if (is_string($key)) {
$key = constant(strtoupper($key));
}
$this->header[$key] = $value;
}
return $this;
}
/**
* @var 设置请求方式
*
* @param string method
*
* @return HttpClient
*/
private function setMethod(String $method = 'GET')
{
$this->method = $method;
return $this;
}
/**
* @var 开始请求
*
* @return HttpClient
*/
private function exec()
{
$ch = curl_init();
if ($this->header) {
foreach ($this->header as $key => $value) {
curl_setopt($ch, $key, $value);
}
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_URL, $this->url);
if ($this->method == 'POST') {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->param);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded; charset=utf-8',
'Content-Length: ' . strlen($this->param)
));
} elseif ($this->method == 'GET') {
curl_setopt($ch, CURLOPT_URL, $this->url.'?'.$this->param);
curl_setopt($ch, CURLOPT_HEADER, false);
}
$info = curl_getinfo($ch);
$data = curl_exec($ch);
$error = curl_errno($ch);
curl_close($ch);
$this->response = [
'code' => $error ? 1 : 0,
'message' => $error,
'info' => $info,
'data' => $data,
];
return $this;
}
/**
* @var 获取响应数据
*
* @throw Exception
*
* @return array|string
*/
public function getBody()
{
if (!$this->response) {
throw new Exception('no httpRequest');
}
return $this->response['data'];
}
/**
* @var 获取响应状态码
*
* @throw Exception
*
* @return int
*/
public function getCode()
{
if (!$this->response) {
throw new Exception('no httpRequest');
}
return $this->response['code'];
}
/**
* @var 获取错误信息
*
* @throw Exception
*
* @return int|array
*/
public function getMessage()
{
if (!$this->response) {
throw new Exception('no httpRequest');
}
return $this->response['message'];
}
/**
* @var 获取响应信息
*
* @return array
*/
public function getInfo()
{
if (!$this->response) {
throw new Exception('no httpRequest');
}
return $this->response['info'];
}
/**
* @var GET请求
*
* @param string url
* @param array param
* @param array header
*
* @return HttpClient
*/
public function get(String $url, Array $param = [], Array $header = [])
{
return $this->setMethod('GET')->setUrl($url)->setParam($param)->setHeader($header)->exec();
}
/**
* @var POST请求
*
* @param string url
* @param array param
* @param array header
*
* @return HttpClient
*/
public function post(String $url, Array $param = [], $header = [])
{
return $this->setMethod('POST')->setUrl($url)->setParam($param)->setHeader($header)->exec();
}
/**
* @var 清理垃圾
*/
public function __destruct()
{
$this->url = null;
$this->method = null;
$this->param = null;
$this->header = null;
$this->response = null;
}
}
TP下使用单例类
<?php
namespace appindexcontroller;
use thinkHttpClient;
class Index
{
public function test()
{
$res = HttpClient::getInstance()->get("https://fanyi.baidu.com/translate?aldtype=16047&query=&keyfrom=baidu&smartresult=dict&lang=auto2zh#en/zh/framework");
var_dump($res);
}
}
显示结果页面
通过助手函数使用单例
在D:phpstudy_proWWWprojecttp51thinkphphelper.php助手函数类中加入
1.先引入think下的单例类
2.判断httpclient函数是否创建,未创建则创建并返回该函数
use thinkHttpClient;
if(!function_exists('httpclient')){
function httpclient()
{
return HttpClient::getInstance();
}
}
使用
<?php
namespace appindexcontroller;
//use thinkHttpClient;
class Index
{
public function test()
{
$res = httpclient()->get("https://fanyi.baidu.com/translate?aldtype=16047&query=&keyfrom=baidu&smartresult=dict&lang=auto2zh#en/zh/framework");
var_dump($res);
}
}
返回结果页面
通过依赖注入方式使用单例
单例模式已经被考虑列入到反模式中!请使用依赖注入获得更好的代码可测试性和可控性!
1.D:phpstudy_proWWWprojecttp51thinkphplibrarythink下的HttpClient.php类不能是单例类
<?php
//加入命名空间
namespace think;
/**
* @var HttpClient
*/
class HttpClient
{
/**
* @var 请求的路径
*/
private $url;
/**
* @var 请求方式
*/
private $method;
/**
* @var 请求参数
*/
private $param;
/**
* @var 请求头
*/
private $header;
/**
* @var 响应结果
*/
private $response;
/**
* @var 设置请求路径
*
* @param string url
*
* @return HttpClient
*/
private function setUrl(String $url = '')
{
$this->url = $url;
return $this;
}
/**
* @var 设置请求参数
*
* @param array param
*
* @return HttpClient
*/
private function setParam(Array $param)
{
$this->param = http_build_query($param);
return $this;
}
/**
* @var 设置请求头部
*
* @param array header
*
* @return HttpClient
*/
private function setHeader(Array $header)
{
foreach ($header as $key => $value) {
if (is_string($key)) {
$key = constant(strtoupper($key));
}
$this->header[$key] = $value;
}
return $this;
}
/**
* @var 设置请求方式
*
* @param string method
*
* @return HttpClient
*/
private function setMethod(String $method = 'GET')
{
$this->method = $method;
return $this;
}
/**
* @var 开始请求
*
* @return HttpClient
*/
private function exec()
{
$ch = curl_init();
if ($this->header) {
foreach ($this->header as $key => $value) {
curl_setopt($ch, $key, $value);
}
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_URL, $this->url);
if ($this->method == 'POST') {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->param);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded; charset=utf-8',
'Content-Length: ' . strlen($this->param)
));
} elseif ($this->method == 'GET') {
curl_setopt($ch, CURLOPT_URL, $this->url.'?'.$this->param);
curl_setopt($ch, CURLOPT_HEADER, false);
}
$info = curl_getinfo($ch);
$data = curl_exec($ch);
$error = curl_errno($ch);
curl_close($ch);
$this->response = [
'code' => $error ? 1 : 0,
'message' => $error,
'info' => $info,
'data' => $data,
];
return $this;
}
/**
* @var 获取响应数据
*
* @throw Exception
*
* @return array|string
*/
public function getBody()
{
if (!$this->response) {
throw new Exception('no httpRequest');
}
return $this->response['data'];
}
/**
* @var 获取响应状态码
*
* @throw Exception
*
* @return int
*/
public function getCode()
{
if (!$this->response) {
throw new Exception('no httpRequest');
}
return $this->response['code'];
}
/**
* @var 获取错误信息
*
* @throw Exception
*
* @return int|array
*/
public function getMessage()
{
if (!$this->response) {
throw new Exception('no httpRequest');
}
return $this->response['message'];
}
/**
* @var 获取响应信息
*
* @return array
*/
public function getInfo()
{
if (!$this->response) {
throw new Exception('no httpRequest');
}
return $this->response['info'];
}
/**
* @var GET请求
*
* @param string url
* @param array param
* @param array header
*
* @return HttpClient
*/
public function get(String $url, Array $param = [], Array $header = [])
{
return $this->setMethod('GET')->setUrl($url)->setParam($param)->setHeader($header)->exec();
}
/**
* @var POST请求
*
* @param string url
* @param array param
* @param array header
*
* @return HttpClient
*/
public function post(String $url, Array $param = [], $header = [])
{
return $this->setMethod('POST')->setUrl($url)->setParam($param)->setHeader($header)->exec();
}
/**
* @var 清理垃圾
*/
public function __destruct()
{
$this->url = null;
$this->method = null;
$this->param = null;
$this->header = null;
$this->response = null;
}
}
2.D:phpstudy_proWWWprojecttp51thinkphplibrarythinkfacade创建一个HttpClient.php同名文件
<?php
namespace thinkfacade;
use thinkFacade;
class HttpClient extends Facade
{
protected static function getFacadeClass()
{
return '\think\HttpClient';
}
}
使用
<?php
namespace appindexcontroller;
use thinkfacadeHttpClient;
class Index
{
public function test()
{
$res = HttpClient::get("https://fanyi.baidu.com/translate?aldtype=16047&query=&keyfrom=baidu&smartresult=dict&lang=auto2zh#en/zh/framework");
var_dump($res);
}
}
显示结果页面
最后
以上就是害羞樱桃为你收集整理的PHP设计模式-单例模式在ThinkPHP中的应用的全部内容,希望文章能够帮你解决PHP设计模式-单例模式在ThinkPHP中的应用所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复