Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
923 views
in Technique[技术] by (71.8m points)

cakephp - Change route if it starts with a certain string/character

I have this in routes.php:

$builder
    ->connect( '/a/*', [ "controller" => "Api", "action" => "foo" ] )
    ->setHost("domain.world");

This works perfectly for URLs like this https://domain.world/a/5nxdy9lmcthc. I fail when I want to enable different routes depending on the first character(s) in the URL.

For example these different action targets:

  • a* --> aAction
  • b* --> bdAction
  • c* --> cbAction ...

It works now with the / but for some reasons I would like to omit the / so the URL would be https://domain.world/a5nxdy9lmcthc or https://domain.world/b5nxdy9lmcthc and this would trigger different actions because of the a and b as first characters after the /.

My question:

Is it possible or is the slash needed in order to use to *?

question from:https://stackoverflow.com/questions/65915623/change-route-if-it-starts-with-a-certain-string-character

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The greedy star (*) and the trailing star (**) are path segment operators, they will match the rest of the path segments, they do not match parts of a segment, so yes, a slash is required.

You can use regular expressions for custom route elements to achieve what you're looking for:

$builder
    ->connect('/{key}', ['controller' => 'Api', 'action' => 'aAction'])
    ->setPatterns(['key' => 'a[a-z0-9]+'])
    ->setPass(['key'])
    ->setHost('domain.world');

$builder
    ->connect('/{key}', ['controller' => 'Api', 'action' => 'bAction'])
    ->setPatterns(['key' => 'b[a-z0-9]+'])
    ->setPass(['key'])
    ->setHost('domain.world');

$builder
    ->connect('/{key}', ['controller' => 'Api', 'action' => 'cAction'])
    ->setPatterns(['key' => 'c[a-z0-9]+'])
    ->setPass(['key'])
    ->setHost('domain.world');

See also


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...