使用withAttribute错误

时间:2017-02-10 07:35:58

标签: php slim

我只是尝试从middileware auth函数传递用户名

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

但我无法使用

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

我找到了一个解决方案,只有当我像这样添加

时才能正常工作
 return $next($request->withAttribute('username','XXXXXX'), $response);

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

2 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:-1)

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

Excerpt from relevant source code

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

出于测试目的,在您的瘦叉中,更改上面的代码。

/* 
* 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
}