2017-06-15 36 views
1

這很可能是因爲我對PHP不太瞭解,但是這裏是:我使用無脂框架來創建一個項目,而現在我遇到了一個問題,我有一段時間需要解決/理解。

這是一個文件上傳,我要和無脂肪的網絡擴展處理回調方法裏面發生的事情,用receive($func=NULL,$overwrite=FALSE,$slug=TRUE)方法(包括$func$slug可以是函數,我使用的這下面的例子)。有了這個擴展,我可以使用一個函數作爲參數以某種方式驗證文件,另一個文件可以更改文件名。

問題是我不能在這些方法中使用任何全局$ f3變量。例如。在下面的代碼中,您可以看到我想要得到一個maxFileSizeMb變量來檢查哪個是允許的最大文件大小,但是當我直接調用$this->f3->get('maxFileSizeMb')或通過將它分配給函數中的一個變量時,它會破壞代碼。

$this->f3->set('UPLOADS','uploads/'.$this->f3->get('tmpMediaPath').'/'); 
$this->f3->set('maxFileSizeMb', 2); 
$this->f3->set('fileNameLenght', 30); 

// Using f3 \Web extension 
$overwrite = false; // set to true, to overwrite an existing file; Default: false 
// $slug = true; // we'll generate a new filename 
$web = \Web::instance(); 
$files = $web->receive(function($file,$formFieldName) { 

     // Check against the maximum allowed file size 
     if($file['size'] > (2 * 1024 * 1024)) // if bigger than 2 MB 
     //    >>>^<<< using $this->f3->get('maxFileSizeMb'); breaks the code 

      return false; // this file is not valid, return false will skip moving it 

     return true; // allows the file to be moved from php tmp dir to your defined upload dir 
    }, 
    $overwrite, 
    function($fileBaseName, $formFieldName){ 

     $fileExtension = ".tmp"; // Determine the true image type and rename it later on 
     // ##TODO## check if value is truly unique against the database. Here or elsewhere? 
     $randomName = bin2hex(openssl_random_pseudo_bytes(30)); 
     //           >>> ^^ <<< using $this->f3->get('fileNameLenght'); breaks the code 
     return $randomName.$fileExtension; 
    } 
); 

在此先感謝您的任何意見。

回答

1

是的,我知道這是缺乏PHP的知識。有必要調用Base實例,以便可以訪問這些變量。這意味着我們可以在這些函數中調用這個,它將檢索值:

$f3=Base::instance(); $maxFileSizeMb = $f3->get('maxFileSizeMb');

(從一個類似的問題的解決方案,認爲該解決方案是完全不適用的 - 至少我不能讓所有替代方案工作: Fat-Free-Framework global variables and functions

相關問題