在開發(fā)中,遇到response中需要加入 cookie的問題,但response是在 helpers.php response() 方法中創(chuàng)建的,在不改方法的前提下,我將 response通過容器創(chuàng)建
<?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;
}
}
這樣在我自己測試過成功沒有問題,大佬幫我看一下 這樣會不會有問題
原來不就提供了cookie的方法嗎?為何還要改來改去的?
<?php
// 創(chuàng)建一個對象
$response = response();
// .... 業(yè)務(wù)邏輯省略
// 設(shè)置cookie
$response->cookie('foo', 'value');
// .... 業(yè)務(wù)邏輯省略
// 設(shè)置http頭
$response->header('Content-Type', 'application/json');
$response->withHeaders([
'X-Header-One' => 'Header Value 1',
'X-Header-Tow' => 'Header Value 2',
]);
// .... 業(yè)務(wù)邏輯省略
// 設(shè)置要返回的數(shù)據(jù)
$response->withBody('返回的數(shù)據(jù)');
return $response;
?>
@70:那有什么問題.....
controller\a.php
<?php
class a{
public function abc($request){
$response = response();
$response->cookie('abc',1);
$this->rc($response);
$response->withBody('asdfadsf');
return $response;
}
private function rc($r){
$r->cookie('def',1);
}
}
@70:其實我還沒弄清你的需求,
按我理解,helpers里的等同語法糖而已,
你也可以不使用helpers的方法,在業(yè)務(wù)處理的地方直接 new response,
所以無論是通過helpers的response還是直接new response,
最終得到的都是response對象。
而response對象本來就帶了cookie方法。
如果僅僅是不想傳參,
那可以把類中的response設(shè)為類的變量,那樣其他方法直接使用它就可以達到不傳參啦。
改框架源碼來實現(xiàn)需求的話,除非你以后不更新框架源碼,或者每次更新都diff手工改一遍,
否則沒太大必要去改......