Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use simple function in Symfony 4?

I'd like to use a simple function in Symfony 4, something like this :

src/Service/Utils.php

<?php

namespace App\Service;

/**
 * @param string $attr
 *
 * @return bool
 */
function attributNilTrue($attr): bool
{
    return json_encode($attr) === '{"@attributes":{"nil":"true"}}';
}

some/other/file.php

use function App\Service\attributNilTrue;

if (attributNilTrue($foo['bar'])) {
    // Do something...
}

But I get the following error:

The autoloader expected class "App\Service\Utils" to be defined in file "/var/www/interop/vendor/composer/../../src/Service/Utils.php". The file was found but the class was not in it, the class name or namespace probably has a typo.

Is there a way to do that without having to create a Utils class?

like image 370
Baptiste Costa Avatar asked Dec 15 '25 18:12

Baptiste Costa


1 Answers

You could use the autoloader files key in composer.

In your composer.json file include something like this:

{
    "autoload": {
        "files": ["src/utility_functions.php"]
    }
}

(where src/utility_functions.php is a file containing your function definitions).

Dump your autoloader (composer dump-autoload) so this is incorporated into your autoloader files, and whatever functions you define in this file will be available on each request.

Your typical Sf4 will already include a PSR4 entry there, so you will have to add your own. The end result would look more or less like this:

"autoload": {
    "psr-4": {
      "App\\": "src/"
    },
    "files": [
      "src/utility_functions.php"
    ]
  },
like image 55
yivi Avatar answered Dec 17 '25 07:12

yivi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!