Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

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

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 Helpers and within it create a file name AppHelper or any of your choice

<?php
namespace AppHelpers;

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
   AppHelpersAppHelper::instance()->startQueryLog();

   //some code that executes queries
   AppHelpersAppHelper::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
{{ AppHelpersAppHelper::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 AppHelpers by creating alias for the AppHelper class in configapp.php

'aliases' => [
       ....
       'AppHelper' => AppHelpersAppHelper::class
 ]

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...