PHP Slim Framework 请求使用 withAttribute 错误

PHP Slim Framework request using withAttribute error

我只是尝试从中间件身份验证函数传递用户名

$request->withAttribute('username','XXXXXX');
return $next($request, $response);

但是我无法使用

访问这个用户名
$request->getAttribute('username');

我找到了一个解决方案,只有当我这样添加时它才有效

 return $next($request->withAttribute('username','XXXXXX'), $response);

这是什么原因?请帮我。我需要传递多个参数传递。我该怎么办?

withAttributes 不会改变 this 对象的状态。

Excerpt from relevant source code

public function withAttribute($name, $value)
{
    $clone = clone $this; 
    $clone->attributes->set($name, $value);
    return $clone;
}

出于测试目的,在您的 slim fork 中,将上面的代码更改为这样。

/* 
* Slim/Http/Request.php 
*/
public function withAttribute($name, $value)
{

    $this->attributes->set($name, $value);
    return $this;
}

然后 return $next($request, $response); 将按您预期的方式工作。

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);
   
   ?>

结果:

 object(Book)#1 (2) {
  ["price"]=>
  int(25)
  ["title"]=>
  string(10) "Peter Pan"
}
object(CopyBook)#2 (2) {
  ["price"]=>
  NULL
  ["title"]=>
  NULL
}

请求和响应对象是 immutable。这意味着 withAttribute() 将 return $request 对象的新副本。您需要 return 新对象而不是原始对象。

$request = $request->withAttribute('username','XXXXXX');
return $next($request, $response);