2016-07-07 112 views
0

所以我有這個函數可以獲取我的Laravel項目所在的剩餘內存。事情是有兩個控制器需要檢查剩餘的內存。使用laravel調用控制器外部的php函數4.2

這裏是什麼樣子,這只是我的控制器內

private function convGB($bytes, $unit = "", $decimals = 2) 
{ 
    $units = array('B' => 0, 'KB' => 1, 'MB' => 2, 'GB' => 3, 'TB' => 4, 
    'PB' => 5, 'EB' => 6, 'ZB' => 7, 'YB' => 8); 

    $value = 0; 
    if ($bytes > 0) 
    { 
     if (!array_key_exists($unit, $units)) 
     { 
      $pow = floor(log($bytes)/log(1024)); 
      $unit = array_search($pow, $units); 
     } 

     $value = ($bytes/pow(1024,floor($units[$unit]))); 
    } 

    if (!is_numeric($decimals) || $decimals < 0) { 
    $decimals = 2; 
    } 

    return sprintf('%.' . $decimals . 'f '.$unit, $value); 
} 

private function getMem() 
{ 
    $ds = disk_total_space(substr(base_path(), 0, 2)); 
    $fs = disk_free_space(substr(base_path(), 0, 2)); 
    $ffs = disk_free_space(substr(base_path(), 0, 2)); 

    if ($ds >= 1073741824) 
    { 
     $ds = number_format($ds/1073741824, 2) . ' GB'; 
    } 
    elseif ($ds >= 1048576) 
    { 
     $ds = number_format($ds/1048576, 2) . ' MB'; 
    } 
    elseif ($ds >= 1024) 
    { 
     $ds = number_format($ds/1024, 2) . ' KB'; 
    } 
    elseif ($ds > 1) 
    { 
     $ds = $ds . ' B'; 
    } 
    elseif ($ds == 1) 
    { 
     $ds = $ds . ' B'; 
    } 
    else 
    { 
     $ds = '0 size'; 
    } 

    if ($fs >= 1073741824) 
    { 
     $fs = number_format($fs/1073741824, 2) . ' GB'; 
    } 
    elseif ($fs >= 1048576) 
    { 
     $fs = number_format($fs/1048576, 2) . ' MB'; 
    } 
    elseif ($fs >= 1024) 
    { 
     $fs = number_format($fs/1024, 2) . ' KB'; 
    } 
    elseif ($fs > 1) 
    { 
     $fs = $fs . ' B'; 
    } 
    elseif ($fs == 1) 
    { 
     $fs = $fs . ' B'; 
    } 
    else 
    { 
     $fs = '0 size'; 
    } 

    $converted = $this->convGB($ffs); 

    return array($ds , $fs , $converted); 
} 

所以我希望把該功能在外部PHP,這樣我就只是把它當我需要它。任何想法如何做到這一點?非常感謝!

+0

所以,你要移動它的功能?我在你的代碼示例中看到兩個。 – JRSofty

+0

嗨,我只使用'getMem'函數 – BourneShady

回答

1

創建您的應用程序/傭工目錄名的新文件,它AnythingHelper.php幫助我的一個例子是:

<?php 
function getDomesticCities() 
{ 
$result = \App\Package::where('type', '=', 'domestic') 
    ->groupBy('from_city') 
    ->get(['from_city']); 

return $result; 
} 

通過以下命令

php artisan make:provider HelperServiceProvider 

爲您的幫助服務提供商在您新近生成的HelperServiceProvider.php的註冊功能中添加以下代碼

require base_path().'/app/Helpers/AnythingHelper.php'; 
現在210

在你的config/app.php加載該服務提供商和你做

'App\Providers\HelperServiceProvider', 

的代碼從這裏取:How do I make global helper functions in laravel 5?

相關問題