首页 > 解决方案 > 如何在自己的 laravel 包中添加助手?(调用未定义的函数)

问题描述

在我的 composer.json 我写过:

"autoload": {
    "psr-4": {
      "Pmochine\\MyOwnPackage\\": "src/"
    },
    "files": [
      "src/helpers.php"
    ]
  },

但不知何故,即使在 composer dump-autoload 之后,函数也没有加载。我得到“调用未定义的函数”。为了创建包,我使用了包生成器。也许它与在供应商文件夹中创建一个符号链接有关?

我写过的内部助手

<?php

if (! function_exists('myowntest')) {

   function myowntest()
   { 
      return 'test'; 
   }
}

标签: laravelpackage

解决方案


在包服务提供者中,尝试添加:

// if 'src/helpers.php' does not work, try with 'helpers.php'
if (file_exists($file = app_path('src/helpers.php'))) { 
    require $file;
}

推荐阅读