简单工厂模式 (Simple Factory Pattern)
使用curl
发送请求时,通常需要设置请求头信息User-Agent
。
使用简单工厂模式来创建属于不同平台(手机端、微信端、PC端)的UserAgent
类。
代码实现
1.抽象UserAgent
abstract class UserAgent
{
abstract public static function getAgents();
public static function getAgent()
{
$agents = self::getAgents();
$index = array_rand($agents);
return $agents[$index];
}
}
2.具体UserAgent
/**
* MobileUserAgent 手机平台
*/
class MobileUserAgent extends UserAgent
{
public static function getAgents()
{
return [
'Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1', // iPhone 6plus
'Mozilla/5.0 (iPad; CPU OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1', // iPad
'Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.23 Mobile Safari/537.36', // Galaxy S5
'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.23 Mobile Safari/537.36', // Nexus 5X
'Mozilla/5.0 (iPod; U; CPU like Mac OS X; en) AppleWebKit/420.1 (KHTML, like Gecko) Version/3.0 Mobile/3A101a Safari/419.3', // iPod
];
}
}
/**
* WechatUserAgent 微信平台
*/
class WechatUserAgent extends UserAgent
{
public static function getAgents()
{
return [
'mozilla/5.0 (linux; u; android 4.1.2; zh-cn; mi-one plus build/jzo54k) applewebkit/534.30 (khtml, like gecko) version/4.0 mobile safari/534.30 micromessenger/5.0.1.352',
'mozilla/5.0 (iphone; cpu iphone os 5_1_1 like mac os x) applewebkit/534.46 (khtml, like gecko) mobile/9b206 micromessenger/5.0',
];
}
}
/**
* PcUserAgent PC平台
*/
class PcUserAgent extends UserAgent
{
public static function getAgents()
{
return [
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36',
// Windows
'Opera/9.80 (Windows NT 6.1; WOW64; U; en) Presto/2.10.229 Version/11.62',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2859.0 Safari/537.36',
];
}
}
/**
* AllUserAgent 任意平台
*/
class AllUserAgent extends UserAgent
{
public static function getAgents()
{
return array_merge(PcUserAgent::getAgents(), MobileUserAgent::getAgents(), WechatUserAgents());
}
}
3.工厂类
class UserAgentFactoty
{
const AGENT_TYPE_ALL = 0;
const AGENT_TYPE_MOBILE = 1;
const AGENT_TYPE_WECHAT = 2;
const AGENT_TYPE_PC = 3;
protected static $agentTypes = [
self::AGENT_TYPE_ALL => 'All',
self::AGENT_TYPE_MOBILE => 'Mobile',
self::AGENT_TYPE_WECHAT => 'Wechat',
self::AGENT_TYPE_PC => 'Pc',
];
public static function createUserAgent($agentType = self::AGENT_TYPE_ALL)
{
if (!array_key_exists($agentType, self::$agentTypes)) {
$agentType = self::AGENT_TYPE_ALL;
}
$className = self::$agentTypes[$agentType];
return new $className();
}
}