I have module named dashboard and PlanningController inside. The controller has become too big and I want to split it into several separate controllers.
Now I have the following actions in PlanningController:
/dashboard/planning/purchase
/dashboard/planning/purchase-create
/dashboard/planning/purchase-update
/dashboard/planning/supplier
/dashboard/planning/supplier-create
/dashboard/planning/supplier-update
But I want to have 2 separate controllers PurchaseController and SupplierController which will be logically combined into a folder planning:
/dashboard/planning/purchase
/dashboard/planning/purchase/create
/dashboard/planning/purchase/update
/dashboard/planning/supplier
/dashboard/planning/supplier/create
/dashboard/planning/supplier/update
I read that Yii2 does not support subfolders in controllers. How do I merge two controllers into one folder?
Depending on what exactly you want to achieve there are multiple ways to handle this.
Nested Modules
You can use nested modules to structure your code. Create a
planningsub-module inside ofmodules/dashboard/modules. Then in the dashboard'sModuleclass add the nested module for example like this:That way you can separate all code related to your planning controllers into its own sub-module. Also, it will help you avoid any potential conflicts in routes.
Controller Map
The property
yii\base\Module::$controllerMapallows you to use controllers that doesn't match the default yii's naming and folder structure conventions. With that you can place yourPurchaseControllerandSupplierControllerinto foldermodules/dashboard/controllers/planningthen set the map in your module class like this:If you use this approach and you want routes to contain the "/planning/" part you will have to set up specific url rules.
Standalone Actions
If you only want to split the code of
PlanningControllerbecause it is getting too big, but you are ok with keeping it as single controller. You can extract the action code into standalone action classes. For example you can createPurchaseCreateActionclass inmodules/dashboard/controllers/actions/planningfolder like this:You can include the standalone action in your planning controller like this: