How to autoload a class inside the composer file and run a script?

Viewed 16

I'm on Drupal 9.3.x trying to add a script to run with composer, following this guide

I've tried either to add the autoload and script part to the drupal project composer.json file

{
    "name": "drupal/d9-starter-kit",
    "description": "Project template for D9 starter kit",
    "type": "project",
    "license": "GPL-2.0-or-later",
    "homepage": "https://www.drupal.org/project/drupal",
    "support": {
        "docs": "https://www.drupal.org/docs/user_guide/en/index.html",
        "chat": "https://www.drupal.org/node/314178"
    },
    "autoload": {
        "classmap": [
            "Drupal\\d9_starter_kit\\Starter.php"
        ]
    },
    "scripts": {
        "doStart": [
            "Drupal\\d9_starter_kit\\Starter::doStart"
        ]
    }, 
    // require, extra, etc...
}

or to create a composer.json inside the custom module I've made

{
    "name": "drupal/d9_starter_kit",
    "type": "drupal-custom-module",
    "description": "a module to script the start",
    "license": "proprietary",
    "authors": [
        {
            "name": "My name",
            "email": "mymail@mail.com"
        }
    ],
    "require": {},
   "autoload": {
        "classmap": [
            "src\\Starter.php"
        ]
    },
    "scripts": {
        "doStart": [
            "Drupal\\d9_starter_kit\\Starter::doStart"
        ]
    }
}


and include that to the project composer file, according the the guide on Drupal site

The path of the Start class is web/modules/custom/d9_starter_kit/src/Starter.php

<?php

namespace Drupal\d9_starter_kit;

class Starter {
  public static function doStart() {
    print('test');
    // TODO
  }
}

I've tried various other syntax for the autoload part - e.g. d9_starter_kit\\Starter.php - but none works.

I get the following error

Could not scan for classes inside "Drupal\d9_starter_kit\Starter.php" which does not appear to be a file nor a folder

Class Drupal\d9_starter_kit\Starter is not autoloadable, can not call doStart script

What is the correct way to autoload the class and run a script? The objective of the latter is the same of the guide, copy, rename and edit some files in order of automate the "start up" of a custom project template.

0 Answers
Related