leafsphp / router

🏚 router module for leaf PHP
https://leafphp.dev/modules/router/
6 stars 6 forks source link

Enhanced Route Handler Definition Flexibility #18

Open ibnsultan opened 7 months ago

ibnsultan commented 7 months ago

Discussed in https://github.com/orgs/leafsphp/discussions/237

Originally posted by **ibnsultan** March 17, 2024 ### Limitations Currently, the route handler definition in the Leaf Router is limited to Closure or string-based definitions in the format `'MyClass@method'`. While this covers many use cases, it lacks flexibility in defining routes with additional options like view rendering and specifying response types. ### Proposed Solution Enhance the Router class to allow for more flexible route handler definitions while maintaining compatibility with existing syntax. Specifically, introduce methods to define routes with names, render views, and specify response types. ### Detailed Description 1. **Name Definition**: Implement a method `name()` to set a name for a route, allowing for easy reference and URL generation using named routes. ```php # instead of app()->method('/path', ['name'=>'routeName', Closure|HandlerClass@method]) # to be app()->method('/path', Closure|HandlerClass@method)->name('routeName') ``` 2. **View Rendering**: Introduce a method `view()` to specify the view to be rendered for a route. This would simplify the rendering of views directly within route definitions. ```php app()->method('/path', Closure|HandlerClass@method)->view('view.path') // output: markup rendered by blade ``` The Closure or HandlerClass' return would be passed as data to the render function i.e `render('view.path', Closure|HandlerClass@method)` 3. **Response Type Specification**: Add methods `json()`, `plain()`, `xml()` , etc to specify the response type for a route. This would allow developers to easily define routes that return JSON, plain text, responses types. ```php # without args app()->method('/path', Closure|HandlerClass@method)->type() // handling: response->type(return of Closure|HandlerClass@method) # with args app()->method('/path', Closure|HandlerClass@method)->type(args) // handling: response->type(return of Closure|HandlerClass@method, args) ``` ### Expected Benefits * Improved flexibility in defining routes with additional options like route names, view rendering, and response type specification. * Simplified syntax for defining routes with view rendering and specifying response types, leading to cleaner and more expressive route definitions. * Enhanced compatibility with existing codebase by maintaining support for the current syntax. ### Additional Considerations * Ensure backward compatibility with existing route definitions to avoid breaking changes.