Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add helpers in own laravel packages? (Call to undefined function)

In my composer.json I have written:

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

But somehow even after composer dump-autoload the functions are not loaded. I get "Call to undefined function". To create the package I used a package generator. Maybe it has something to do that it creates a symlink in the vendor folder?

Inside helpers I have written

<?php

if (! function_exists('myowntest')) {

   function myowntest()
   { 
      return 'test'; 
   }
}
like image 589
Philipp Mochine Avatar asked Jul 13 '18 10:07

Philipp Mochine


4 Answers

In the package service provider, try adding this:

// if 'src/helpers.php' does not work, try with 'helpers.php'
if (file_exists($file = app_path('src/helpers.php'))) { 
    require $file;
}
like image 137
Brian Lee Avatar answered Nov 15 '22 08:11

Brian Lee


What you are doing is best practise and should work. I took the composer.json from barryvdh/laravel-debugbar as an example. https://github.com/barryvdh/laravel-debugbar/blob/master/composer.json

{

    "name": "barryvdh/laravel-debugbar",
    "description": "PHP Debugbar integration for Laravel",
    "keywords": ["laravel", "debugbar", "profiler", "debug", "webprofiler"],
    "license": "MIT",
    "authors": [
        {
            "name": "Barry vd. Heuvel",
            "email": "[email protected]"
        }
    ],
    "require": {
        "php": ">=5.5.9",
        "illuminate/support": "5.1.*|5.2.*|5.3.*|5.4.*|5.5.*",
        "symfony/finder": "~2.7|~3.0",
        "maximebf/debugbar": "~1.13.0"
    },
    "autoload": {
        "psr-4": {
            "Barryvdh\\Debugbar\\": "src/"
        },
        "files": [
            "src/helpers.php"
        ]
    }
}

My guess is that you are not requiring your own package the correct way in the main composer.json?

like image 31
online Thomas Avatar answered Nov 15 '22 09:11

online Thomas


Just need to call in your main project

 composer update you/your-package

Source

like image 27
Philipp Mochine Avatar answered Nov 15 '22 08:11

Philipp Mochine


The only thing that has worked for me is to run composer remove <vendor>/<package> and require it back again. The files section was ignored otherwise.

This seems to happen while developing locally the package and making changes on the composer.json file.

like image 25
Aridez Avatar answered Nov 15 '22 10:11

Aridez