簡體   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