sseraluck sseraluck - 6 months ago 14
PHP Question

Package: calling method from multiple controllers

I'm calling a method from multiple controllers in my application. I don't want to have duplicate code in my project, so I'm looking for a way to put the method somewhere, so I can call it from every controller.

I did some research and I stumbled upon "Helpers". (I dont' know if this is the right way to solve this. Other approaches are welcome too) I've read this post and did exactly what Jeffrey Way said in his post, but I still get following error:


Call to undefined function initFb()


I've tried
composer dump-autoload
.

So this is my
helpers.php
:

<?php

if (! function_exists('initFb'))
{
function initFb()
{
$fb = new \Facebook\Facebook([
'app_id' => getenv('FACEBOOK_APP_ID'),
'app_secret' => getenv('FACEBOOK_APP_SECRET'),
'default_graph_version' => 'v2.5',
]);

return $fb;
}
}


My composer.json of my package:

"files": [
"src/helpers.php"
]


Important

This is for a package I'm developing.

Answer

To register your own helpers.php file, add these lines into Laravel's composer.json:

"autoload": {
        ...
        "files": [
            "app/some_path/helpers.php"
        ]

For classes use psr-4 section:

"psr-4": {
            "App\\": "app/",
            "YourName\\PackageNamespace\\": "packages/yourname/package-name/src"
        },

Then run composer dumpauto (if doesn't help, try composer dumpauto -o).

Also, try with some simple helper to test if it works , do something like this:

if (! function_exists('helpersTest'))
{
    function helpersTest()
    {
        return 'It works!';
    }
}

If you're trying to use these helpers after installing your package with composer (from Packagist), you should add these lines to package's composer.json file.

Comments