Laravel 5 - 在哪里定义功能并在视图中调用它们&控制器

时间:2015-02-28 11:18:23

标签: php helper laravel-5

我有以下功能,想从视图中调用它。基本上我想把所有常用功能放在一个文件中。我不知道在哪里创建该文件以及如何在控制器和视图中调用它。

<?php namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use DB;

class CommonController extends Controller {

public function BytesToMB($bytes=0)
{
    if(empty($bytes))
    return 0;

    $kb = ceil($bytes/1024);

    $mb = ceil($kb/1024);

    return $mb;
}

}

到目前为止,我已经在app / Http / Controllers中创建了CommonController.php并将上面的函数放入其中。

然后在其他控制器中,我试图按照以下方式调用它:

use App\Http\Controllers\Common;

class SongsController extends Controller {
    public function index($id)
    {
       echo Common::BytesToMB('7012187');
    }
}

但是我收到了错误:

 Class 'App\Http\Controllers\Common' not found

1 个答案:

答案 0 :(得分:2)

好的,新尝试。您错过了使用完整的类名并添加静态关键字:

<?php 

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use DB;

class CommonController extends Controller {

    public static function BytesToMB($bytes=0)
    {
        if(empty($bytes))
        return 0;

        $kb = ceil($bytes/1024);

        $mb = ceil($kb/1024);

        return $mb;
    }

}

然后:

<?php
namespace App\Http\Controllers;

// You do not need to define this, if you are in the same namespace
use App\Http\Controllers\CommonController;

class SongsController extends Controller {
    public function index($id)
    {
       echo CommonController::BytesToMB('7012187');
    }
}

另一个更多的OOP解决方案是使用父类中的函数:

<?php 

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use DB;

class CommonController extends Controller {

    protected function BytesToMB($bytes=0)
    {
        if(empty($bytes))
        return 0;

        $kb = ceil($bytes/1024);

        $mb = ceil($kb/1024);

        return $mb;
    }

}

然后:

<?php
namespace App\Http\Controllers;

// You do not need to define this, if you are in the same namespace
use App\Http\Controllers\CommonController;

class SongsController extends CommonController {

    public function index($id)
    {
       echo $this->bytesToMB('7012187');
    }
}