Laravel:从视图中调用base_controller中定义的函数 [英] Laravel : Calling functions defined in base_controller from view

查看:296
本文介绍了Laravel:从视图中调用base_controller中定义的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用laravel框架时,如何在视图中调用在base_controller中定义的函数.例如:

In using the laravel framework, how can I call a function defined in base_controller, in a view. For exacmple:

class Base_Controller extends Controller {

    public static function format_something()
    {
         return something;
    }
}

如何在视图文件中调用format_something()?

How can i call format_something() in a view file?

通常,我得到的错误看起来像这样: 未在View类上定义方法[link_to_action].

Usually the error I get looks something like this: Method [link_to_action] is not defined on the View class.

可能是一个愚蠢的问题,但在此先感谢!

Probably a silly question, but thanks in advance!

修改

好吧!首先,正确的位置是在librarys文件夹中. 其次,问题是您的班级不能有下划线.

Okay! First the correct place to do something like this is in the libraries folder. Second, problem is that your class cannot have underscores.

因此,在应用程序/库中,我使用类制作了文件AppHelper.php

So in application/libraries I made file AppHelper.php with class

class AppHelper {

    public static function format_something()
    {
        return something;
    }
}

并且可以这样称呼它:

$formated = AppHelper::format_something;

感谢您的帮助和良好的论坛,您可以找到Boofus McGoofus.

Thanks for the help and the good forum find Boofus McGoofus.

推荐答案

此答案是为Laravel 3编写的.对于Laravel 4及更高版本,LajdákMarek使用Composer的自动加载器的答案更好.

format_something()之类的功能不属于控制器.控制器应该只是从各种来源收集数据并将其传递给视图.它的工作主要是路由.

Functions like format_something() don't belong in the controller. The controller should just be about collecting data from various sources and passing it to the view. It's job is mostly just routing.

我已经在应用程序文件夹中为我的所有小辅助功能创建了一个名为"helpers"的文件夹.为了确保我所有的控制器,视图和模型都可以访问它们,我在start.php文件中添加了以下内容:

I've created a folder called "helpers" in the application folder for all my little helpery functions. To make sure all my controllers, views, and models have access to them, I've included the following in my start.php file:

foreach(glob(path('app').'helpers/*.php') as $filename) {
    include $filename;
}

我怀疑有更好的方法可以做到这一点,但到目前为止,它对我有用.

I suspect that there's a better way to do that, but so far it has worked for me.

这篇关于Laravel:从视图中调用base_controller中定义的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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