具有相似参数的路线上的路线参数模式 [英] Route parameter patterns on routes with similar parameters
问题描述
我有一些采用几个UUID作为参数的路由:
I have a few routes that takes a couple of UUIDs as parameters:
Route::get('/foo/{uuid1}/{uuid2}', 'Controller@action');
我希望能够在将控制权转交给操作之前验证这些参数的格式是否正确:
I want to be able to verify that those parameters are the correct format before passing control off to the action:
Route::pattern('uuid1', '^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$');
这很好.但是,我真的不想重复这种模式很多次(实际上,我对8个不同的UUID路由参数重复了8次).
This works fine. However, I really don't want to repeat that pattern so many times (in the real case I have it repeated 8 times for 8 different UUID route parameters).
我不能这样做:
Route::get('/foo/{uuid}/{uuid}', 'Controller@action');
由于产生错误:
路由模式"/foo/{uuid}/{uuid}"不能多次引用变量名"uuid".
Route pattern "/foo/{uuid}/{uuid}" cannot reference variable name "uuid" more than once.
自从发现Route::patterns
以来,我可以将它们全部合并为一个函数调用:
I can lump them all into a single function call since I discovered Route::patterns
:
Route::patterns([
'uuid1' => '^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$',
'uuid2' => '^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$',
]);
但这仍然是重复的.有什么方法可以将多个模式键绑定到单个正则表达式?
But that is still repetitious. Is there a way I can bind multiple pattern keys to a single regular expression?
理想情况下,我想找到一种避免这种情况的方法:
Ideally I'd like to find a way that avoids something like this:
$pattern = 'uuid regex';
Route::patterns([
'uuid1' => $pattern,
'uuid2' => $pattern,
]);
推荐答案
没有内置的方法可以处理此问题,我实际上认为您找到的解决方案非常不错.也许会更优雅一些:
There's no built in way to handle this, and I actually think the solution you found is pretty nice. Maybe a bit more elegant would be this:
Route::patterns(array_fill_keys(['uuid1', 'uuid2'], '/uuid regex/'));
这篇关于具有相似参数的路线上的路线参数模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!