[英]PHP Slim Framework request using withAttribute error
I am just try to pass username from middileware auth function 我只是尝试从Middileware auth函数传递用户名
$request->withAttribute('username','XXXXXX');
return $next($request, $response);
But i cannot access this username using 但是我无法使用
$request->getAttribute('username');
I found a solution that its working only when i add like this 我发现一个解决方案,仅当我这样添加时,它才有效
return $next($request->withAttribute('username','XXXXXX'), $response);
What is the reason? 是什么原因? Please help me. 请帮我。 I need to pass multiple arguments pass. 我需要传递多个参数传递。 What should i do? 我该怎么办?
Request and Response objects are immutable . 请求和响应对象是不可变的 。 This means withAttribute()
will return a new copy of the $request
object. 这意味着withAttribute()
将返回$request
对象的新副本。 You need to return the new object not the original one. 您需要返回新对象而不是原始对象。
$request = $request->withAttribute('username','XXXXXX');
return $next($request, $response);
withAttributes
does not change the state of this
object. withAttributes
不会更改this
对象的状态。
Excerpt from relevant source code 摘录自相关源代码
public function withAttribute($name, $value)
{
$clone = clone $this;
$clone->attributes->set($name, $value);
return $clone;
}
For testing purposes, in your slim fork, change above code as this. 为了进行测试,请在苗条的分支中更改上面的代码。
/*
* Slim/Http/Request.php
*/
public function withAttribute($name, $value)
{
$this->attributes->set($name, $value);
return $this;
}
Then return $next($request, $response);
然后return $next($request, $response);
will work as you expected. 将按预期工作。
Demo code for inspection 演示代码检查
<?php
/* code taken from - https://www.tutorialspoint.com/php/php_object_oriented.htm*/
class Book {
var $price;
var $title;
function setPrice($par){
$this->price = $par;
}
function getPrice(){
return $this->price;
}
function setTitle($par){
$this->title = $par;
}
function getTitle(){
return $this->title;
}
}
class CopyBook {
var $price;
var $title;
function setPrice($par){
$clone = clone $this;
$clone->price = $par;
}
function getPrice(){
return $this->price;
}
function setTitle($par){
$clone = clone $this;
$clone->title = $par;
}
function getTitle(){
return $this->title;
}
}
$pp = new Book;
$pp->setTitle('Perter Pan');
$pp->setPrice(25);
$cpp = new CopyBook;
$cpp->setTitle('Peter Pan');
$cpp->setPrice(25);
var_dump($pp);
var_dump($cpp);
?>
Result: 结果:
object(Book)#1 (2) {
["price"]=>
int(25)
["title"]=>
string(10) "Peter Pan"
}
object(CopyBook)#2 (2) {
["price"]=>
NULL
["title"]=>
NULL
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.