【问题标题】:How to use simple function in Symfony 4?如何在 Symfony 4 中使用简单功能?
【发布时间】:2019-07-11 15:40:30
【问题描述】:

我想在 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...
}

但我收到以下错误:

自动加载器期望类“App\Service\Utils”在文件“/var/www/interop/vendor/composer/../../src/Service/Utils.php”中定义。这 找到文件但类不在其中,类名或命名空间可能有错字。

有没有办法做到这一点而不必创建Utils 类?

【问题讨论】:

  • 基本没有。 PHP 不支持函数的自动加载。静态类函数确实是您最好的选择。或者找出使用 require 语句的最佳位置。

标签: php symfony autoloader


【解决方案1】:

您可以使用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"
    ]
  },

【讨论】:

    【解决方案2】:

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

    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. 当您将来需要在这些函数/方法中添加一些依赖项时,您可以轻松地注入它们,因为它是一项服务。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-17
      • 2021-08-16
      • 2018-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多