【问题标题】:Laravel 5.2 custom helper not found未找到 Laravel 5.2 自定义助手
【发布时间】:2017-01-02 08:01:26
【问题描述】:

我已经创建了 app/Http/helpers.php

if (!function_exists('getLocation')) {
function getLocation($request)
{
    return 'test';
}

我在 composer.json 自动加载中添加了文件部分

    "autoload": {
    "classmap": [
        "database"
    ],
    "psr-4": {
        "App\\": "app/"
    },
    "files": [
        "app/Http/helpers.php"
    ]
},

这是我的控制器:

namespace App\Http\Controllers;

use App\Jobs\ChangeLocale;
use App\Http\Requests;
use Illuminate\Http\Request;
use DB;
use Log;

class HomeController extends Controller
{
     public function index(Request $request)
     {  
          $data['location'] = getLocation($request);

     }

}

当我将控制器中的函数调用为 getLocation($request);它说“调用未定义的函数 App\Http\Controllers\getLocation()”

这在我的本地运行良好,但在远程服务器上却不行。我在远程服务器中缺少什么。尝试作曲家安装和作曲家转储自动加载。

更新: 帮助文件未在 vendor/composer/autoload_files.php 中列出

【问题讨论】:

  • 您能否发布更多信息,例如来自服务器的控制器 sn-p?根据我从中收集到的信息,这可能是一些愚蠢的事情,例如您忘记更新某些文件或导入命名空间。
  • 添加了控制器,但它在我的本地工作并且在服务器上出错。
  • 根据我的经验,当这种情况发生时(服务器-本地主机的差异),这两种环境中的情况会有所不同。要么是辅助文件丢失,要么是不同的作曲家文件......

标签: laravel composer-php helper


【解决方案1】:

确保 Helper.php 的结构正确...

<?php

//no namespace, no classes
//classes are not helpers

if ( !function_exists('nextStage') ) {
    function nextStage($currentStage) {
        //if you need to access a class, use complete namespace
        return \App\Models\Stage::where('id',$currentStage)->first()->next_stage;
    }
}

More help on Laracast found here

【讨论】:

    【解决方案2】:

    这样试试,

    1. 在 app 目录中创建 Helpers 目录。
    2. 在 Helpers 目录中创建一个 Example.php 文件
    3. 在 config/app.php 文件中为这个文件创建一个别名

      例如:'Example' => App\Helpers\Example::class,

    Example.php 中的代码如下,

    <?php 
    
    namespace App\Helpers;
    
    class Example
    {   
        static function exampleMethod()
        {
           return "I am helper";
        }
    }
    

    在控制器文件中使用上面的示例帮助器,如下所示,

    <?php
    
    namespace App\Http\Controllers;
    use App\Helpers\Example;
    
    class HomeController extends Controller
    {
         public function index(Request $request)
         {  
              return Example::exampleMethod();
    
         }
    
    }
    

    在刀片视图文件中使用上述示例帮助程序,如下所示,

    <div>{{ Example::exampleMethod()}}</div>
    

    这将帮助您获得解决方案。

    【讨论】:

      【解决方案3】:

      在服务器上,你需要执行:

      composer dumpautoload
      

      因为在vendor/autoload.php上找不到它

      【讨论】:

      • 删除autoload.php, autoload_files.php 然后,再次发出命令。它看起来像缓存。
      猜你喜欢
      • 2013-07-31
      • 2016-06-28
      • 1970-01-01
      • 1970-01-01
      • 2016-09-23
      • 2013-09-02
      • 2017-01-11
      • 2018-11-21
      • 2019-02-02
      相关资源
      最近更新 更多