Search code examples
phplaravellaravel-5laravel-5.3

Best option in laravel to create multiple modules under different namespace


I am new to Laravel and need to know how can i structure my project in Laravel.

1) We have almost 21 different modules in the project all the modules are connecting with same database but each module should be register under different namespace.

for example - if i have admin and inventory, the admin should access from /admin and inventory should access from /inventory. Also it will be fine if i can write the routing for each namespace from the corresponding app folder.

2) Another thing we have a different level of user and the different URL will be accessible to those who have permission. So i am planning to write a middle ware for checking the permission before the user request is reaching each controller. So i need a top level middle ware also to check the permission of the login user for all the module.

What structure will be good to implement this type of application. I only need to connect only one database throughout the application.


Solution

  • Here are a few suggestions :

    1) You must have a different controller for each module. Place the controllers further in subdirectories if needed.

    For example, I keep my Admin-related controllers in the Admin directory under the App\Controllers directory, API-related in App\Controllers\API directory and similarly, App\Controllers\Web for web-only controllers.

    2) Have a separate route-file (web.php) for each controller.

    Name the route-file to something that matches with the name of the module you are dealing with. for example, 'inventory.php' for dealing with inventory-controller routes only. You need to register the routes as well, just like web.php,api.php, etc routes have been pre-registered out of the box.

    3) Follow design patterns to keep your code clean. I would suggest taking a look at Service-Repository pattern.

    The code flow then becomes as follows :

    Routes pass on the request to a Controller. The controller does not handle the business logic and passes task specific requests to the Service Class where all the business logic will be handled. If any Database specific tasks (CRUD) are needed, the Service class then calls the methods defined in the Repository class.

    Have a separate Service and Repository class for all your modules. For example, InventoryController -> InventoryService -> InventoryRepository.

    This is just a practice that I follow and may not be the best solution.