4

So the entrypoint file in the Symfony 6 framework (public/index.php) has a construct which I don't understand.

Below is the whole content of the file:

<?php

use App\Kernel;

require_once dirname(__DIR__).'/vendor/autoload_runtime.php';

return function (array $context) {
    return new Kernel($context['APP_ENV'], (bool) $context['APP_DEBUG']);
};

What I don't understand is the usage of the anonymous function. As we are at the very top level I don't know how it is executed and where does it return it's result.

r34
  • 320
  • 2
  • 12

1 Answers1

2

What happens is simple.

As you can see you are not asking for a standard autoload of composer

require_once dirname(__DIR__).'/vendor/autoload.php';

But you are requiring

require_once dirname(__DIR__).'/vendor/autoload_runtime.php';

This file is generated by symfony/runtime

The operation is simple, I'll give you an example

File index.php (entry point):

<?php
require_once __DIR__.'/runtime.php';

return function (array $context){
    print_r($context);
    return 1;
};

File runtime.php (runtime):

<?php
$app = require $_SERVER['SCRIPT_FILENAME'];

$app = $app(['context_variable'=>1]);

What Happnes:

  1. When the index is called it requires the runtime
  2. The runtime takes the variable 'SCRIPT_FILENAME' which is populated with the path of the index
  3. The autoload file then makes a require_once of the executed file and passes it some parameters
  4. Since in the index the runtime is called via require_once this will prevent files from calling each other recursively

I hope I have been exhaustive, otherwise please ask me.