Composer require doesn't work in sage theme

For a specific use case I need an array flatten function in a sage 8.x-based theme.
In command line in sage theme folder I ran composer to install a package with array flatten function ( for the theme:

  $ composer require sarhan/php-flatten

However, using the class doesn’t work, e.g. in setup.php:

use Sarhan\Flatten;

$multiArray = [
    'say' => 'what',
    'hi' => [ 'de' => 'Hallo', 'es' => 'Hola' ]

$array = Flatten::flatten($multiArray);

This results in an error, PHP can’t find the class:

Fatal error: Uncaught Error: Class 'Sarhan\Flatten' not found in [...]/setup.php`
Error: Class 'Sarhan\Flatten' not found in [...]/setup.php

Where are you running that?

I run this command in the theme folder ([…]/the-app/site/web/app/themes/the-theme/).
The composer files of the theme are also modified by the command, composer succeeds, but PHP still cannot find the class.

You’ll notice that the composer file in Sage 8 is for loading the theme as a WP theme, but the vendor autoload file isn’t included by default because there’s no packages to install. It’s not like Sage 9 where Composer is required. So if you install something with Sage 8, you need to include the theme/vendor/autoload.php file. However if you’re also using Bedrock and it’s all one project I would be inclined to install any PHP packages from Bedrock.


Thanks! I want to install in theme because it is completely theme-specific.
Where is a good place in the theme files for including theme/vendor/autoload.php ?

functions.php. Autoloader should usually be required as early in the process possible.