Silex, connect multiple controllers with closure

I am trying to use Silex and I have a little problem, or I can say more inconvenience ...

I am trying to load 2 routes from 2 separate yaml files, but for some reason setting ( $app->mount(...)) does not work with closing.

Here is the code:

// load configuration
$loader->load('core.yml');
$loader->load('api.yml');


function bla($app, $container, $key) {
    $myApp = $app['controllers_factory'];

    foreach ($container->getExtensionConfig('routes')[$key] as $name => $route) {
        $controller = $myApp->match($route['pattern'], $route['controller']);
        $controller->method($route['requirements']['_method']);
        $controller->bind($name);
    }
    return $myApp;
}

$app->mount('/core', bla($app, $container, 0));
$app->mount('/api', bla($app, $container, 1));

It works.

What does not work if I do the same with closing, for example:

$app->mount('/core', function ($app, $container, $key) {
    return $app['controllers_factory'];
});

Gives the following error:

LogicException: The "mount" method takes either a ControllerCollection or a ControllerProviderInterface instance.

But

var_dump($app['controllers_factory']);

splashes out an object of type Silex\ControllerCollection.

I am clearly missing something.

Thank you for your help.

+3
source share
1 answer

Problem

In the first example, you set the result of a function. In the second example, you install this function yourself.

bla() .

$app->mount('/core', bla($app, $container, 0));

, ControllerCollection.

$app->mount('/core', function ($app, $container, $key) {...});

. . itstelf ControllerCollection ControllerProviderInterface, .

PHP-

. , " Silex", .

:

$app->mount('/core', include 'controllers/core.php');
$app->mount('/api', include 'controllers/api.php');

controllers. api.php :

$controllers = $app['controllers_factory'];

$controllers->get('/version', function() use ($app) {
  // do whatever you want
  return 'version 1.2';
});

return $controllers;

, YML yml , yml php . , .

. , , . , , . , .

+2

All Articles