跳到内容

加载资源

编辑此页

加载器从不同的来源(如 YAML 文件)填充应用程序的配置。Config 组件定义了此类加载器的接口。Dependency Injection 和 Routing 组件为不同的文件格式提供了专门的加载器。

定位资源

加载配置通常从搜索资源开始,主要是文件。这可以使用 FileLocator 完成

1
2
3
4
5
6
use Symfony\Component\Config\FileLocator;

$configDirectories = [__DIR__.'/config'];

$fileLocator = new FileLocator($configDirectories);
$yamlUserFiles = $fileLocator->locate('users.yaml', null, false);

定位器接收它应该在其中查找文件的位置集合。locate() 的第一个参数是要查找的文件名。第二个参数可以是当前路径,如果提供,定位器将首先在此目录中查找。第三个参数指示定位器应返回找到的第一个文件还是包含所有匹配项的数组。

资源加载器

对于每种资源类型(YAML、XML、属性等),都必须定义一个加载器。每个加载器都应实现 LoaderInterface 或扩展抽象 FileLoader 类,该类允许递归导入其他资源

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
namespace Acme\Config\Loader;

use Symfony\Component\Config\Loader\FileLoader;
use Symfony\Component\Yaml\Yaml;

class YamlUserLoader extends FileLoader
{
    public function load($resource, $type = null): void
    {
        $configValues = Yaml::parse(file_get_contents($resource));

        // ... handle the config values

        // maybe import some other resource:

        // $this->import('extra_users.yaml');
    }

    public function supports($resource, $type = null): bool
    {
        return is_string($resource) && 'yaml' === pathinfo(
            $resource,
            PATHINFO_EXTENSION
        );
    }
}

找到合适的加载器

LoaderResolver 接收加载器集合作为其第一个构造函数参数。当应加载资源(例如 XML 文件)时,它会遍历此加载器集合并返回支持此特定资源类型的加载器。

DelegatingLoader 使用 LoaderResolver。当被要求加载资源时,它会将此问题委派给 LoaderResolver。如果解析器找到了合适的加载器,则将要求此加载器加载资源

1
2
3
4
5
6
7
8
9
10
use Acme\Config\Loader\YamlUserLoader;
use Symfony\Component\Config\Loader\DelegatingLoader;
use Symfony\Component\Config\Loader\LoaderResolver;

$loaderResolver = new LoaderResolver([new YamlUserLoader($fileLocator)]);
$delegatingLoader = new DelegatingLoader($loaderResolver);

// YamlUserLoader is used to load this resource because it supports
// files with the '.yaml' extension
$delegatingLoader->load(__DIR__.'/users.yaml');
这项工作,包括代码示例,根据 Creative Commons BY-SA 3.0 许可协议获得许可。
目录
    版本