'Creating composer package for Codeigniter 4

I am trying to create my first composer package for Codeigniter 4. However, I always get an error Class 'Myapp\Settings\Greet' not found. I'm totally lost.

I created a folder inside the ThirdParty folder named myapp-settings. Inside of that folder is another folder called src and composer.json.

Here's the content of that composer.json

{
    "name": "myapp/settings",
    "description": ".",
    "license": "MIT",
    "minimum-stability": "dev",
    "autoload": {
        "psr-4": {
            "Myapp\\Settings\\": "src"
        }
    },
    "require": {}
}

I created a test file inside the src folder named Greet.php

<?php namespace Myapp\Settings;

class Greet
{
    public function hello()
    {
        return 'Hey, there!';
    }
}

On codeigniter's App\Config\Autoload.php

public $psr4 = [
    'Myapp\Settings' => APPPATH . 'ThirdParty/myapp-settings/src'
];

Then on codeigniter's default controller I called it.

<?php namespace App\Controllers;

use Myapp\Settings\Greet;

class Home extends BaseController
{
    public function index()
    {
        $h = new Greet();
        echo $h->hello();
    }

    //--------------------------------------------------------------------

}

Once I run it I got an error Class 'Myapp\Settings\Greet' not found. APPPATH\Controllers\Home.php at line 9. How can I fix this?



Solution 1:[1]

Instead of editing the codeigniter's app/Config/Autoload.php, revert it and add these lines to the project composer.json:

"repositories": [
    {
        "type": "path",
        "url": "app/ThirdParty/myapp-settings"
    }
],
// "require": {

Then run composer require myapp/settings

Since I have also stuck at this problem, a GitHub repository is created just for it. You might check and clone, watch the commits to understand the steps.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mondayrris