如何在Symfony 4中使用简单功能?

时间:2019-07-11 15:40:30

标签: php symfony autoloader

我想在Symfony 4中使用一个简单的函数,如下所示:

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

但是出现以下错误:

  

自动装带器应在文件“ /var/www/interop/vendor/composer/../../src/Service/Utils.php”中定义“ App \ Service \ Utils”类。的   找到文件,但没有找到类,文件名或名称空间可能有错字。

有没有一种方法而不必创建Utils类?

2 个答案:

答案 0 :(得分:2)

您可以使用autoloader files key in composer

在您的composer.json文件中包含以下内容:

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

(其中src/utility_functions.php是包含您的函数定义的文件)。

转储您的自动加载器(composer dump-autoload),以便将其合并到您的自动加载器文件中,并且您在此文件中定义的任何功能都可在每次请求时使用。

您的典型Sf4将在其中包含PSR4条目,因此您必须添加自己的条目。最终结果或多或少是这样的:

"autoload": {
    "psr-4": {
      "App\\": "src/"
    },
    "files": [
      "src/utility_functions.php"
    ]
  },

答案 1 :(得分:0)

我建议将此类函数包装在类中-例如:     

namespace App\Service;

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

如果您为该目录配置了自动加载功能,则应自动加载该目录-否则添加服务定义,如下所示:

App\Service\Utils:

然后您可以像使用它一样

use App\Service\Utils;

...

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

这种方式:

  1. 您的课程是根据PSR4(https://www.php-fig.org/psr/psr-4/)正确定义的:

    2.3.3:
    The terminating class name corresponds to a file name ending in .php. The file name MUST match the case of the terminating class name.
    
  2. 您不需要弄混作曲家。

  3. 将来在这些函数/方法中需要一些依赖项时,您可以轻松注入它们,因为它是一项服务。