wiifree
wiifree

Reputation: 55

CakePHP 4 custom plugin dont find classes

I try to create a Custom Plugin for CakePHP 4. But everytime i become a error that the plugin cant find the classes of the plugin.

I load the plugin in the Application.php

use Wirecore\CakePHP_JWT\Plugin as CakePHPJwt;

$plugin = new CakePHPJwt();
$this->addPlugin($plugin);

In the composer.json file of cake its also loaded:

"autoload": {
    "psr-4": {
        "App\\": "src/",
        "Wirecore\\CakePHP_JWT\\": "./plugins/CakePHP-JWT-Plugin/src/"
    }
},
"autoload-dev": {
    "psr-4": {
        "App\\Test\\": "tests/",
        "Cake\\Test\\": "vendor/cakephp/cakephp/tests/",
        "Wirecore\\CakePHP_JWT\\Test\\": "./plugins/CakePHP-JWT-Plugin/tests/"
    }
}

and i create a file in /plugins/CakePHP-JWT-Plugin/src/Middleware/JwtMiddleware.php with example code of the documentation Middleware. I changed the namespace of the example code to

namespace Wirecore\CakePHP_JWT\Middleware;

after this i try to load the middle in the middleware function of the plugin but everytime i become this error:

Class 'Wirecore\CakePHP_JWT\Middleware\TrackingCookieMiddleware' not found

here the code of the middleware function:

use Wirecore\CakePHP_JWT\Middleware\TrackingCookieMiddleware;

$middlewareQueue->add(new TrackingCookieMiddleware());
return $middlewareQueue;

i have tried to change the namespace but it does not work, and i try it with composer dumpautoload but again it changed nothing. Any ideas ?

Upvotes: 0

Views: 927

Answers (1)

Andy Hoffner
Andy Hoffner

Reputation: 3327

The autoload section in the composer file is what tells PHP how to find your namespaces on disk. Your namespace prefix for the class, Wirecore\CakePHP_JWT, is not the namespace you listed in the autoload section, you listed Wirecore\CakePHP-JWT-Plugin. Either fix the namespace declaration to match autoload, like so:

use Wirecore\CakePHP-JWT-Plugin\ .. etc

.. or change fix the autoload section to match the name listed in your namespace declaration:

"autoload": {
    "psr-4": {
        "Wirecore\\CakePHP_JWT\\": "src/"
    }
},
"autoload-dev": {
    "psr-4": {
        "Wirecore\\CakePHP_JWT\\Test\\": "tests/",
        "Cake\\Test\\": "vendor/cakephp/cakephp/tests/"
    }
}

Also, I'm not positive what standards your following here, but they potentially don't look right.

Is this a standalone plugin? If so, I'd mirror the structure from another standalone plugin like https://github.com/dereuromark/cakephp-geo/

If this isn't a standalone plugin (which is what seems more probable), but just a custom plugin being put directly into an existing CakePHP app, you're classes should be stuck in /plugins not /src, per the docs https://book.cakephp.org/4/en/plugins.html#creating-your-own-plugins

You might want to just use the Bake utility as a starting point (that'll solve your autoload issues too!) and copy your code into the classes it creates instead.

Upvotes: 1

Related Questions