Laravel 5-在何处定义函数并在View&中调用它们控制器 [英] Laravel 5 - Where to define functions and call them in views & controllers

查看:168
本文介绍了Laravel 5-在何处定义函数并在View&中调用它们控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have following function and want to call it from view. Basically i want to put all common functions in one file. I am not sure where to create that file and how to call it inside controller and view.

<?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并将其放在上面的函数中.

So far i have created CommonController.php in app/Http/Controllers and put above function in it.

然后在其他控制器中,我尝试通过以下方式调用它:

Then in other controller i have tried to call it following way:

use App\Http\Controllers\Common;

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

但是我遇到了错误:

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

推荐答案

好的,新尝试.您错过了使用完整的类名并添加static关键字的方法:

Ok, new try. You missed to use the complete class name and add the static keyword:

<?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解决方案是使用父类中的函数:

Another and more OOP solution is to use the function from the parent class:

<?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');
    }
}

这篇关于Laravel 5-在何处定义函数并在View&amp;中调用它们控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆