我在Zend Framework 2中工作,有可变的操作和主键。下面是我的模块路由器。我想根据操作将不同的ID传递给它(如果我删除语言,它将引用语言ID。如果我删除相册,它将参考相册ID)。我需要为语言和相册创建子路由,然后确定每个子路由使用的特定ID吗?或者,有没有一种方法可以说,第二个参数将始终是一个数字,并且操作将对该数字执行所需的操作?
操作:deleteLanguage ID:languageId
选项:deleteAlbumID:albumId
'router' => array(
'routes' => array(
'pro' => array(
'type' => 'segment',
'options' => array(
'route' => '/pro[/][:action][/:id]',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'language_id' => '[0-9]+',
),
'defaults' => array(
'controller' => 'Pro'Controller'Pro',
'action' => 'index',
),
非常感谢,M
只有完整地写下配置,才能在操作和标识符之间创建依赖关系。ZF2没有基于其他参数值重命名参数名称的方法(如果你仔细想想,有很多充分的理由不具备此功能)。
剩下两个选项:
'pro' => [
'type' => 'literal',
'options' => [
'route' => '/pro',
'defaults' => [
'controller' => 'Pro'Controller'Pro',
'action' => 'index',
],
'may_terminate' => true,
'child_routes' => [
'delete-language' => [
'type' => 'segment',
'options' => [
'route' => '/delete-language/:language_id',
'defaults' => [
'action' => 'deleteLanguage'
],
'constraints' => [
'language_id' => '[0-9]+'
],
],
],
'delete-album' => [
'type' => 'segment',
'options' => [
'route' => '/delete-album/:album_id',
'defaults' => [
'action' => 'deleteAlbum'
],
'constraints' => [
'album_id' => '[0-9]+'
],
],
],
],
],
]
或者接受你只处理一个"id"(这是imho更喜欢的):
'pro' => [
'type' => 'segment',
'options' => [
'route' => '/pro[/:action[/:id]]',
'defaults' => [
'controller' => 'Pro'Controller'Pro',
'action' => 'index',
],
'constraints' => [
'id' => '[0-9]+'
],
],
]
此外,如果按实体/域模型拆分控制器,也会有很大帮助。不要将"语言"的删除和"相册"的删除放在同一个控制器中。把他们分开!更多地考虑RESTful原则,它将使您的代码更加干净。