Philipp Mochine
Philipp Mochine

Reputation: 4705

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'; 
   }
}

Upvotes: 9

Views: 4102

Answers (5)

Brian Lee
Brian Lee

Reputation: 18187

This is an outdated answer, the correct way is to use composer.json.

Original Answer

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;
}

Upvotes: 5

sajed zarrinpour
sajed zarrinpour

Reputation: 1224

I had the same issue, I was developing a local package located at packages/provider/package/src, I added

"autoload": {
        "psr-4": {
            ...
        },
        "files": [
                "packages/provider/package/src/Helpers/helpers.php"
            ]
    }

to my app composer.json file and it worked.

Upvotes: 0

Aridez
Aridez

Reputation: 502

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.

Upvotes: 5

Philipp Mochine
Philipp Mochine

Reputation: 4705

Just need to call in your main project

 composer update you/your-package

Source

Upvotes: 1

online Thomas
online Thomas

Reputation: 9381

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?

Upvotes: 4

Related Questions