Cookie面向对象分装
<?php
class Cookie
{
const OPTION_EXPIRE = 'expire';
const OPTION_PATH = 'path';
const OPTION_DOMAIN = 'domain';
const OPTION_SECURE = 'secure';
const OPTION_HTTPONLY = 'httponly';
/**
* Cookie 实例
* @var null
*/
private static $instance = null;
/**
* Cookie 选项
* @var array
*/
private $options = [
self::OPTION_EXPIRE => 3600,
self::OPTION_PATH => '/',
self::OPTION_DOMAIN => 'domain',
self::OPTION_SECURE => false,
self::OPTION_HTTPONLY => false
];
/**
* Cookie constructor.
* @param $options
*/
private function __construct($options){
$this->setOptions($options);
}
/**
* privated __clone
*/
private function __clone(){
}
/**
* 获取实例
* @param $options
* @return Cookie|null
*/
public static function getInstance($options){
if (is_null(self::$instance)) {
self::$instance = new self($options);
}
return self::$instance;
}
/**
* 设置选项
* @param $name
* @param $value
*/
public function setOption($name, $value){
if (isset($this->options[$name])) {
$this->options[$name] = $value;
}
throw new InvalidArgumentException('Cookie option not exists:{$name}');
}
/**
* 设置多个选项
* @param $options
*/
public function setOptions($options){
foreach ($options as $name => $value) {
$this->setOption($name, $value);
}
}
/**
* 设置 Cookie
* @param $name
* @param $value
* @param array $options
*/
public function set($name, $value, $options = []){
$this->setOptions($options);
if (is_array($value) || is_object($value)) {
$value = json_encode($value);
}
setcookie(
$name,
$value,
$this->options[self::OPTION_EXPIRE],
$this->options[self::OPTION_PATH],
$this->options[self::OPTION_DOMAIN],
$this->options[self::OPTION_SECURE],
$this->options[self::OPTION_HTTPONLY]
);
}
/**
* 获取 Cookie
* @param $name
* @return array|mixed
*/
public function get($name){
$value = $_COOKIE[$name];
if (is_array($value)) {
$arr=[];
foreach ($value as $k => $v) {
$arr[$k] = substr($v, 0,1) == '{' ? json_decode($value) : $v;
}
return $arr;
} else {
return substr($value, 0,1) == '{' ? json_decode($value) : $value;
}
}
/**
* 删除 Cookie
* @param $name
* @param array $options
*/
public function del($name, $options = []){
$this->setOptions($options);
$value = $_COOKIE[$name];
if ($value) {
if (is_array($value)) {
foreach ($value as $k => $v) {
setcookie(
$name . '[' . $k . ']',
'',
time() - 3600,
$this->options[self::OPTION_EXPIRE],
$this->options[self::OPTION_PATH],
$this->options[self::OPTION_DOMAIN],
$this->options[self::OPTION_SECURE],
$this->options[self::OPTION_HTTPONLY]
);
unset($v);
}
}else{
setcookie(
$name,
'',
time() - 3600,
$this->options[self::OPTION_EXPIRE],
$this->options[self::OPTION_PATH],
$this->options[self::OPTION_DOMAIN],
$this->options[self::OPTION_SECURE],
$this->options[self::OPTION_HTTPONLY]
);
unset($value);
}
}
}
}
上一篇: 解析Laravel5.5之事件监听、任务调度、队列
下一篇: TP5简单复习及快速上手2