Laravel:从视图中调用 base_controller 中定义的函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13481136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 07:25:29  来源:igfitidea点击:

Laravel : Calling functions defined in base_controller from view

phplaravelstatic-classes

提问by Jim

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

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

class Base_Controller extends Controller {

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

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

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

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

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

Probably a silly question, but thanks in advance!

可能是一个愚蠢的问题,但提前致谢!

Edit

编辑

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

好的!首先,执行此类操作的正确位置是在库文件夹中。其次,问题是你的班级不能有下划线。

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

所以在应用程序/库中,我用类创建了文件 AppHelper.php

class AppHelper {

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

And can call it like:

并且可以这样称呼它:

$formated = AppHelper::format_something;

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

感谢您的帮助和良好的论坛找到 Boofus McGoofus。

采纳答案by J.T. Grimes

This answer was written for Laravel 3. For Laravel 4 and after, Lajdák Marek's answer using Composer's autoloader is better.

这个答案是为 Laravel 3 编写的。对于 Laravel 4 及之后的版本,Lajdák Marek 使用 Composer 的自动加载器的答案更好。

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.

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

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.phpfile:

我在应用程序文件夹中为我所有的小帮助函数创建了一个名为“helpers”的文件夹。为了确保我的所有控制器、视图和模型都可以访问它们,我在我的start.php文件中包含了以下内容:

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.

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

回答by Lajdák Marek

For me is working:

对我来说正在工作:

Create directory "helpers" or whatever and file:

创建目录“helpers”或其他文件:

// app/helpers/AppHelper.php

class AppHelper {

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

Add path to composer.json

将路径添加到 composer.json

// composer.json

    "autoload": {
        "classmap": [
                    "app/helpers"   // <-------- add this line
        ]
    },

Run: (reload the autoload)

运行:(重新加载自动加载)

composer dump-autoload

Now you can call:

现在你可以调用:

$formated = AppHelper::format_something();

回答by Capripot

You can inspire yourself from Laravel framework itself.

您可以从Laravel 框架本身中激发自己的灵感

I will take your example of a formatter and refer to urlhelper in Laravel Framework.

我将以您的格式化程序为例,并参考urlLaravel 框架中的帮助程序。

Start by creating your own helpers.phpfile:

首先创建您自己的helpers.php文件:

<?php

if (! function_exists('format_that')) {
    /**
     * Generate something
     *
     * @param  string  $text
     * @return string
     */
    function format_that($text)
    {
        return app('formatter')->format_that($text);
    }
}

And add itto your composer.jsonfile:

把它添加到您的composer.json文件:

"autoload": {
      "files": [
          "app/helpers/helpers.php"
      ]
}

Run this command to recreate the autoload php file:

运行此命令以重新创建自动加载 php 文件:

$ composer dumpautoload

Create your service providerapp/Providers/FormatterServiceProvider.php:

创建您的服务提供者app/Providers/FormatterServiceProvider.php

<?php

namespace Illuminate\Routing;

use Illuminate\Support\ServiceProvider;
use App\Helpers\FormatGenerator;

class FormatterServiceProvider extends ServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app['formatter'] = $this->app->share(function ($app) {
            return new FormatGenerator($app['request']);
        });
    }
}

Registeryour service provider. Laravel framework invokes registermethod but you only need to add it to your app config file config/app.php:

注册您的服务提供商。Laravel 框架调用register方法,但您只需要将其添加到您的应用程序配置文件中config/app.php

 'providers' => [


      /*
       * Application Service Providers...
       */
      App\Providers\AppServiceProvider::class,
      // other providers...
      App\Providers\FormatterServiceProvider::class,

 ]

Finally, create your actual generator classapp/Helpers/FormatGenerator.php

最后,创建您的实际生成器类app/Helpers/FormatGenerator.php

<?php

namespace App\Helpers;

use Illuminate\Http\Request;

class FormatGenerator
{

    protected $request;

    /**
     * Create a new URL Generator instance.
     *
     * @param  \Illuminate\Routing\RouteCollection  $routes
     * @param  \Illuminate\Http\Request  $request
     * @return void
     */
    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    public function format_that($text){
        if ($request->path() == "home"){
            return mb_strtoupper($text);
        }
        else{
            return $text;
        }
    }

}

You can optionally create a Facadeapp/Facade/Formatter.php, to be able to do Formatter::format_that($text):

您可以选择创建一个 Facadeapp/Facade/Formatter.php,以便能够Formatter::format_that($text)

<?php

namespace App\Facades;

use Illuminate\Support\Facades\Facade;

/**
 * @see \App\Helpers\FormatGenerator
 */

class Formatter extends Facade
{
    protected static function getFacadeAccessor() { return 'formatter'; }
}

You could ask yourself:

你可以问问自己:

  • Why the facade?You can reuse the component somewhere else by simply calling Formatter::format_that($text)instead of app('formatter')->format_that($text). Sugar syntax really.
  • Why the Service provider?Dependence injections. If you need to use Requestor want to build a complex object, the Service provider will take care of that for you and make it available in your $appobject.
  • 为什么是门面?您可以通过简单地调用Formatter::format_that($text)代替app('formatter')->format_that($text). 糖语法真的。
  • 为什么是服务提供者?依赖注入。如果您需要使用Request或想要构建一个复杂的对象,服务提供者会为您处理好并使其在您的$app对象中可用。