D
D
Dmitry Andreenko2020-02-10 17:11:09
symfony
Dmitry Andreenko, 2020-02-10 17:11:09

How to load routings from several files at once?

There was a task to load routings at once from files in different directories.
The documentation has an example that shows how to search for a file in several directories for one file, and then get routings from there:

$fileLocator = new FileLocator(array(__DIR__));
$loader = new YamlFileLoader($fileLocator);
$routes = $loader->load('routes.yaml');


And how to do it to get files from different directories, and then work with them?
It works like this:
data/
├── dir1
│ └── routes.yaml
├── dir2
│ └── routes.yaml
...

you need to take all the routes.yaml files from the specified folders, and already look for routing there.

Is it possible to do this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
BoShurik, 2020-02-10
@amperkotfwb

If you know the location of the configs, then you can do this:

use Symfony\Component\Config\FileLocator;
use Symfony\Component\Routing\Loader\YamlFileLoader;
use Symfony\Component\Routing\RouteCollectionBuilder;

require_once __DIR__.'/../vendor/autoload.php';

$locator = new FileLocator([__DIR__.'/../data']);
$loader = new YamlFileLoader($locator);

$builder = new RouteCollectionBuilder($loader);
$builder->import('dir1/routes.yaml');
$builder->import('dir2/routes.yaml');

$routes = $builder->build();
var_dump($routes);

If the location of the configs is unknown or you just don't want to bother adding new ones:
use Symfony\Component\Config\FileLocator;
use Symfony\Component\Config\Loader\DelegatingLoader;
use Symfony\Component\Config\Loader\LoaderResolver;
use Symfony\Component\Routing\Loader\GlobFileLoader;
use Symfony\Component\Routing\Loader\YamlFileLoader;
use Symfony\Component\Routing\RouteCollectionBuilder;

require_once __DIR__.'/../vendor/autoload.php';

$locator = new FileLocator([__DIR__.'/../data']);
$resolver = new LoaderResolver([
    new GlobFileLoader($locator), // needs symfony/finder
    new YamlFileLoader($locator),
]);
$loader = new DelegatingLoader($resolver);

$builder = new RouteCollectionBuilder($loader);
$builder->import('**/*/routes.yaml', '/', 'glob');

$routes = $builder->build();
var_dump($routes);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question