封装设计一个MVC框架的request.php和response.php类,请给出完善安全的类文件代码
设计一个MVC框架的request.php
和response.php
类时,我们需要考虑安全性、可扩展性和易用性。以下是一个基本的实现示例:
<?php
class Request
{
private $get;
private $post;
private $server;
private $cookies;
private $files;
public function __construct()
{
$this->get = $this->sanitize($_GET);
$this->post = $this->sanitize($_POST);
$this->server = $this->sanitize($_SERVER);
$this->cookies = $this->sanitize($_COOKIE);
$this->files = $_FILES; // Files need special handling, so we don't sanitize them here
}
private function sanitize($data)
{
if (is_array($data)) {
return array_map([$this, 'sanitize'], $data);
}
return htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
}
public function get($key, $default = null)
{
return $this->get[$key] ?? $default;
}
public function post($key, $default = null)
{
return $this->post[$key] ?? $default;
}
public function server($key, $default = null)
{
return $this->server[$key] ?? $default;
}
public function cookie($key, $default = null)
{
return $this->cookies[$key] ?? $default;
}
public function file($key)
{
return $this->files[$key] ?? null;
}
public function getMethod()
{
return $this->server('REQUEST_METHOD', 'GET');
}
public function getUri()
{
return $this->server('REQUEST_URI', '/');
}
public function isPost()
{
return $this->getMethod() === 'POST';
}
public function isGet()
{
return $this->getMethod() === 'GET';
}
}
?>
<?php
class Response
{
private $headers = [];
private $body;
private $statusCode;
public function __construct($body = '', $statusCode = 200)
{
$this->body = $body;
$this->statusCode = $statusCode;
}
public function setHeader($name, $value)
{
$this->headers[$name] = $value;
}
public function setStatusCode($statusCode)
{
$this->statusCode = $statusCode;
}
public function setBody($body)
{
$this->body = $body;
}
public function send()
{
http_response_code($this->statusCode);
foreach ($this->headers as $name => $value) {
header("$name: $value");
}
echo $this->body;
}
public function json($data, $statusCode = 200)
{
$this->setHeader('Content-Type', 'application/json');
$this->setStatusCode($statusCode);
$this->setBody(json_encode($data));
}
public function redirect($url, $statusCode = 302)
{
$this->setHeader('Location', $url);
$this->setStatusCode($statusCode);
}
}
?>
Request 类:
Response 类:
这些类提供了一个基础的MVC框架的请求和响应处理机制,确保了输入数据的安全性和响应的灵活性。根据具体需求,可以进一步扩展和优化这些类。