【问题标题】:calling a php function that is outside the controller using laravel 4.2使用 laravel 4.2 调用控制器外部的 php 函数
【发布时间】:2016-11-09 09:04:17
【问题描述】:

所以我有这个函数来获取我的 Laravel 项目所在的剩余内存。问题是有两个控制器需要检查剩余内存。

这是它在我的控制器内部的样子

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 中,这样我就可以在需要时调用它。关于如何做到这一点的任何想法?非常感谢!

【问题讨论】:

  • 那么你要移动哪个函数呢?我在您的代码示例中看到了两个。
  • 嗨,我只使用getMem函数

标签: php laravel laravel-4


【解决方案1】:

在您的 app/Helpers 目录中创建一个新文件,将其命名为 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';

现在在你的 config/app.php 中加载这个服务提供者,你就完成了

'App\Providers\HelperServiceProvider',

代码取自这里:How do I make global helper functions in laravel 5?

【讨论】:

    猜你喜欢
    • 2014-05-06
    • 2012-12-24
    • 2016-10-16
    • 2021-08-02
    • 2013-11-28
    • 1970-01-01
    • 1970-01-01
    • 2015-01-06
    • 2019-12-11
    相关资源
    最近更新 更多