2
votes

I've created a module under folder api (which itself is same level as backend & frontend in yii2 advanced app).

Folder structure:

api
-- common
------ controllers
------ models
-- config
-- modules
------ v1
---------- controllers
---------- models
-- runtime
-- tests
-- web

In api/config/main.php:

return [
'id' => 'app-api',
'basePath' => dirname(__DIR__),    
'bootstrap' => ['log'],
'modules' => [
    'v1' => [
        'basePath' => '@app/modules/v1',
        'class' => 'api\modules\v1\Module'
    ]
],

I get error:

ReflectionException

Class api\modules\v1\Module does not exist

The class is definitely there.

I've run a composer dumpautoload (no errors).

urlManager in config/main.php:

'urlManager' => [
        'enablePrettyUrl' => true,
        'enableStrictParsing' => true,
        'showScriptName' => false,
        'rules' => [
              'v1/site/index' => 'v1/site/index', //module/controller/action
        ],        
    ]

Any help much appreciated,

thanks

2
Check if namespace in this Module.php file is correct. Also double check the path for case sensitivity differences. - Bizley
You dont need a basePath option, just 'v1' => [ 'class' => 'api\modules\v1\Module', ], - Yupik
Have you set correct alias for '@app' ? I mean for API it should point to api directory. - witzawitz
Bizley - Namespace of Module.php: namespace api\modules\v1; (seems OK?) Yupik - I've removed basePath entry, still get same error witzawitz - Hmmm don't think you need to explicitly set @app (isn't that determined automatically by the framework?) If not, where to set it? Still getting same error ... :( - gvanto
Btw this is the project I am basing it off: github.com/deerawan/yii2-advanced-api I basically copied the api folder and made minor changes to fit with my system. - gvanto

2 Answers

8
votes

OK got it: in common/config/bootstrap.php, add:

Yii::setAlias('@api', dirname(dirname(__DIR__)) . '/api');

Then in config/main.php use:

'modules' => [
        'v1' => [
            'basePath' => '@api/modules/v1',
            'class' => 'api\modules\v1\Module'
        ]
    ],

This seems to work, thanks guys

1
votes

Thanks, gvanto. Also check whether you include common/config/bootstrap.php in \api\web\index.php . Like here

<?php
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');

require(__DIR__ . '/../../vendor/autoload.php');
require(__DIR__ . '/../../vendor/yiisoft/yii2/Yii.php');
require (__DIR__ . '/../../common/config/bootstrap.php');

$config = yii\helpers\ArrayHelper::merge(
require(__DIR__ . '/../../common/config/main.php'),
require(__DIR__ . '/../../common/config/main-local.php'),
require(__DIR__ . '/../config/main.php'),
require(__DIR__ . '/../config/main-local.php')
);

$application = new yii\web\Application($config);
$application->run();

that was my mistake. Maybe it will help someone