Reponse加入 cookie的问题

0

在开发中,遇到response中需要加入 cookie的问题,但response是在 helpers.php response() 方法中创建的,在不改方法的前提下,我将 response通过容器创建


<?php

namespace support\bootstrap;

class Container implements Bootstrap
{
public static function response(...$arguments)
{
/** @var Response $response */
$response = static::$_instance->get('support\Response');
if (empty($arguments)) {
return $response;
} else {
$response->withStatus($arguments[0]);
if (isset($arguments[1]) && is_array($arguments[1]) && !empty($arguments[1])) {
$response->withHeaders($arguments[1]);
}
if (isset($arguments[2]) && strlen($arguments[2]) > 0 && $arguments[2] !== null) {
$response->withBody($arguments[2]);
}
return $response;
}
}
}

然后 helpers.php 修改


function response($body = '', $status = 200, $headers = array())
{
return \support\bootstrap\Container::response($status, $headers, $body);
}

然后将support/Response.php 改成这样


<?php

namespace support;

use support\bootstrap\Container;
use support\cookie\Cookie;
use support\cookie\CookieCollection;

/**
* Class Response
*
* @package support
*/
class Response extends \Webman\Http\Response
{
private $_cookies;

public function __construct($status = 200, $headers = array(), $body = '')
{
return parent::__construct($status, $headers, $body);
}

/**
* Sends the cookies to the client.
*/
protected function sendCookies()
{
if ($this->_cookies === null) {
return;
}

/** @var Cookie $cookie */
foreach ($this->getCookies() as $cookie) {
$this->cookie($cookie->name, $cookie->value, $cookie->expire, $cookie->path, $cookie->domain, $cookie->secure, $cookie->httpOnly);
}
}

public function getCookies()
{
if ($this->_cookies === null) {
$this->_cookies = new CookieCollection();
}
return $this->_cookies;
}

public function __toString()
{
$this->sendCookies();
$responseString = parent::__toString();
Container::remove('support\Response');
return $responseString;
}
}

这样在我自己测试过成功没有问题,大佬帮我看一下 这样会不会有问题

已邀请:

MarkGo

赞同来自:

原来不就提供了cookie的方法吗?为何还要改来改去的?


<?php
// 创建一个对象
$response = response();

// .... 业务逻辑省略

// 设置cookie
$response->cookie('foo', 'value');

// .... 业务逻辑省略

// 设置http头
$response->header('Content-Type', 'application/json');
$response->withHeaders([
'X-Header-One' => 'Header Value 1',
'X-Header-Tow' => 'Header Value 2',
]);

// .... 业务逻辑省略

// 设置要返回的数据
$response->withBody('返回的数据');
return $response;

?>

wo664881680

赞同来自:

怎么说呢,就是创建response的地方在 helpers.php, 而设置 cookie的地方在别的类中

要回复问题请先登录注册