In my company, we use a framework built on top of Lumen. We don't write routes. we write actions.
So for example:
app/api/Food/AddFoodAction.php
app/api/food/EditFoodAction.php
In Postman you hit, if you want to add food
{{host}}/api/food/AddFood
{{host}}/api/food/EditFood
A typical action looks like this
class AddFoodAction
{
protected $verbs = ['POST'];
public $inputRules = [
'name' => 'required',
'description' => ''
];
public function execute()
{
$name = $this->request->get('name');
try {
...
return $this->response->statusOk();
}
catch(\Exception $ex) {
return $this->response->statusFail("");
}
}
}
I'm just interested in the routing part of it, the idea of never writing routes, only actions. I would like to use the same concept in other projects without having to use the framework that my company uses.
Do you know how that's done? I searched for dynamic routing, but that's not dynamic routing, do you know what's the name of the concept used?
I suppose this is done with dynamic class names, where you would have one 'real' endpoint which catches all parameters, then with this information you could generate the full clas path.
For example if you navigate to {{host}}/api/food/AddFood
your code would extract the /food/AddFood
part. This part is then parsed so it produces app/api/Food/AddFoodAction
(i.e. by camelcasing and prexing with /app/api
) which matches the namespace + classname.
If this is stored in a variable you can then call this class dynamically, where it would produce something like this:
// this would be dynamically build, but is hardcoded to illustrate the example
$className = "\app\api\Food\AddFoodAction";
$action = $className();
$action->execute();
I hope this helps you, if you have any questions feel free to ask!
P.S. please note that the name needs to use the namespace and not the folder path