PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, February 13, 2022

[FIXED] CakePHP 3.x - Extension router in prefix only

 February 13, 2022     cakephp-3.0, prefix, routing     No comments   

Issue

I am developing an application which has a side available to users (the dashboard) and a back-end side (an API). I want the API side to have pages which output JSON. Thanks to Cake this is made easy with a $this->set('_serialize', [...]); from a controller in combination with a router setting: Router::extensions(['json', 'xml']);. I use prefix routing to group the API pages.

Question: how can I make only the API pages support the *.json pages from the extensions router?

Things I tried

  • Putting the Router::extensions(['json', 'xml']); line in the routes.php main scope makes it work everywhere, obviously.
  • Putting the Router::extensions(['json', 'xml']); line inside the prefix scope...

    Router::prefix('api', function ($routes) {
         //...
         Router::extensions(['json', 'xml']);
         //...
    });
    

    ...Makes it work everywhere but inside the API prefix.

  • Putting it in a new scope...

    Router::scope('/api', function ($routes) {
       $routes->extensions(['json', 'xml']);
    });
    

    ...Also makes it work everywhere.


Solution

Prefixes are scopes too, just with additional functionality (it's basically a shorthand method for scope() and passing the prefix option). In fact, every route is scoped, even if not explicitly connected via the scope() method.

Use the routes builder that is passed to the callback for the prefix() method, just as shown in the scope() example in the docs and your question:

Router::prefix('api', function ($routes) {
    $routes->extensions(['json']);
    // ...
});

And make sure that you do not use Router::extensions(['json', 'xml']); anywhere.

See also

  • Cookbook > Routes > Routing File Extensions


Answered By - ndm
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing