Search code examples
phpsymfonyautoloader

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?


Solution

  • 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"
        ]
      },