繁体   English   中英

PHP Slim Framework请求使用withAttribute错误

[英]PHP Slim Framework request using withAttribute error

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

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

但是我无法使用

$request->getAttribute('username');

我发现一个解决方案,仅当我这样添加时,它才有效

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

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

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

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

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

摘录自相关源代码

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); 将按预期工作。

演示代码检查

<?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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM