laravel 如何创建可以从任何控制器和刀片文件访问的全局函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44021662/
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-08 17:45:24  来源:igfitidea点击:

how to create global function that can be accessed from any controller and blade file

laravelcontrollerglobal

提问by Johnny

I have two controller file homecontroller and backendcontroller. What is the best way to create global function and access it from both files?

我有两个控制器文件 homecontroller 和 backendcontroller。创建全局函数并从两个文件访问它的最佳方法是什么?

I found hereArian Acosta's answer helpful but I wonder if there is an easiest way. I would appreciate any suggestions.

我在这里发现Arian Acosta 的回答很有帮助,但我想知道是否有最简单的方法。我将不胜感激任何建议。

采纳答案by Rahul Chauhan

Updated:

更新:

Step 1Add folder inside app folder app->Helper

步骤 1在 app 文件夹app->Helper 中添加文件夹

Step 2add php Class inside Helper folder Eg. Helper.php

第 2 步在 Helper 文件夹中添加 php Class 例如。帮手.php

Add namespace and class to the Helper.php

将命名空间和类添加到 Helper.php

namespace App\Helper;

class Helper
{

}

Register this Helper.php into config/app.php file

将此 Helper.php 注册到 config/app.php 文件中

'aliases' => [
       ....
       'Helper' => App\Helper\Helper::class
 ]

Now, write all the functions inside Helper.phpand it will be accessible everywhere.

现在,在Helper.php 中编写所有函数,它可以随处访问。

回答by Max Gaurav

Solution

解决方案

One way to do this is to create a class and use its instance, this way you can not only access the object of the class within a controller, blade, or any other class as well.

一种方法是创建一个类并使用它的实例,这样您不仅可以在控制器、刀片或任何其他类中访问该类的对象。

AppHelper file

应用助手文件

In you app folder create a folder named Helpersand within it create a file name AppHelperor any of your choice

在您的应用程序文件夹中创建一个名为Helpers的文件夹,并在其中创建一个文件名AppHelper或您选择的任何一个

<?php
namespace App\Helpers;

class AppHelper
{
      public function bladeHelper($someValue)
      {
             return "increment $someValue";
      }

     public function startQueryLog()
     {
           \DB::enableQueryLog();
     }

     public function showQueries()
     {
          dd(\DB::getQueryLog());
     }

     public static function instance()
     {
         return new AppHelper();
     }
}

Usage

用法

In a controller

在控制器中

When in a controller you can call the various functions

在控制器中时,您可以调用各种功能

public function index()
{
    //some code

   //need to debug query
   \App\Helpers\AppHelper::instance()->startQueryLog();

   //some code that executes queries
   \App\Helpers\AppHelper::instance()->showQueries();
}

In a blade file

在刀片文件中

Say you were in a blade file, here is how you can call the app blade helper function

假设您在刀片文件中,以下是调用应用程序刀片助手功能的方法

some html code
{{ \App\Helpers\AppHelper::instance()->bladeHelper($value) }}
and then some html code

Reduce the overhead of namespace (Optional)

减少命名空间的开销(可选)

You can also reduce the overhead of call the complete function namespace \App\Helpersby creating alias for the AppHelperclass in config\app.php

您还可以通过在config\app.php 中AppHelper类创建别名来减少调用完整函数命名空间\App\Helpers的开销

'aliases' => [
       ....
       'AppHelper' => App\Helpers\AppHelper::class
 ]

and in your controller or your blade file, you can directly call

并在您的控制器或刀片文件中,您可以直接调用

\AppHelper::instance()->functioName();

回答by Sapnesh Naik

Easy Solution:

简单的解决方案:

  1. Create a new Helpersfolder in your appdirectory.
  2. Create a phpfile named your_helper_function.phpin that Helpersfolder.
  3. Add your function inside your_helper_function.php

    function your_function($parameters){
    
        //function logic
    
    } 
    
    function your_another_function($parameters){
    
        //function logic
    
    } 
    
  4. Add this file to the Fileskey of your composer.jsonlike

    
    "autoload": {
        ...
        "files": [
            "app/Helpers/your_helper_function.php"
        ]
        ...
    }
    
  5. And then finally regenerate composer autoload files. (Run this in your project directory)

    composer dump-autoload
  1. Helpers在您的app目录中创建一个新文件夹。
  2. 创建一个在该文件夹中php命名your_helper_function.phpHelpers文件。
  3. 在里面添加你的功能 your_helper_function.php

    function your_function($parameters){
    
        //function logic
    
    } 
    
    function your_another_function($parameters){
    
        //function logic
    
    } 
    
  4. 将此文件添加到Filescomposer.json喜欢的密钥中

    
    "autoload": {
        ...
        "files": [
            "app/Helpers/your_helper_function.php"
        ]
        ...
    }
    
  5. 然后最后重新生成作曲家自动加载文件。(在您的项目目录中运行它)

    composer dump-autoload

That's it! and now you can access your_function()or your_another_function()in any part of your Laravel project.

就是这样!现在您可以访问your_function()your_another_function()在您的 Laravel 项目的任何部分。



If you still have any confusion check my blog post on how to do this:

如果您仍然有任何困惑,请查看我的博客文章,了解如何执行此操作:

How to Add a Global Function in Laravel Using Composer?

如何使用 Composer 在 Laravel 中添加全局函数?

回答by Murat Bagsiz

In your Controller.phpwhich extends BaseController, you can create a function like;

在您的Controller.phpwhich 中extends BaseController,您可以创建一个函数,例如;

public function data($arr = false)
{
 $data['foo'] = 'bar';
 return array_merge($data,$arr);
}

And from any controller when you send a data to a view;

当您将数据发送到视图时,来自任何控制器;

public function example()
{
 $data['smthg'] = 'smthgelse';
 return view('myView',$this->data($data));
}

The data in the the main controller can be accessed from all controllers and blades.

可以从所有控制器和刀片访问主控制器中的数据。

回答by Sandeesh

Laravel uses namespaces by default. So you need to follow the method described in that answer to setup a helper file.

Laravel 默认使用命名空间。因此,您需要按照该答案中描述的方法来设置帮助文件。

Though in your case you want to access a method in different controllers. For this there's a simpler way. Add a method to you base controller app/Http/Controllers/Controller.phpand you can access them in every other controller since they extend it.

尽管在您的情况下,您想访问不同控制器中的方法。为此,有一种更简单的方法。向您的基本控制器添加一个方法app/Http/Controllers/Controller.php,您可以在每个其他控制器中访问它们,因为它们扩展了它。

// in app/Http/Controllers/Controller.php
protected function dummy()
{
    return 'dummy';
}

// in homecontroller

$this->dummy();

回答by killstreet

There are a few ways, depending on the exact functionality you're trying to add.

有几种方法,具体取决于您尝试添加的确切功能。

1) Create a function inside Controller.php, and make all other controller extend that controller. You could somewhat compair this to the master.blade.php

1) 在Controller.php 中创建一个函数,并使所有其他控制器扩展该控制器。您可以将其与 master.blade.php 进行比较

2) Create a trait, a trait can do a lot for you, and keeping ur controllers clean. I personally love to use traits as it will look clean, keep my Controller.php from being a mess with tons of different lines of code.

2) 创建一个 trait,一个 trait 可以为你做很多事情,并保持你的控制器干净。我个人喜欢使用特性,因为它看起来很干净,让我的 Controller.php 不会被大量不同的代码行弄得一团糟。