Salines
Salines

Reputation: 5767

CakePHP 3: Admin Plugin & Routing

for the purpose of migration to cakephp 3 and mastering the skills of making applications on this version of the framework, I just baked app and plugin.

I want to separate the web application in plugins, Admin, Customers, etc.

I'm fine to access locations within the plugin, for example myapp/admin/users, myapp/admin/, but if I try to visit the url myapp/admin (without the slash at the end) I have to redirect the location myapp/webroot/admin/.

in myapp/webroot/ I have a theme folder called admin, I tried to change the name in admintheme, but still have a redirect.

How to solve this?

Thank You.

Upvotes: 0

Views: 3321

Answers (1)

Kim Stacks
Kim Stacks

Reputation: 10812

This works with cakephp 3.1.2

Step 1: Set the routes for admin prefix above your normal /

// code ... 

// for prefix admin
Router::prefix('admin', function ($routes) {
    // All routes here will be prefixed with `/admin`
    // And have the prefix => admin route element added.
    $routes->fallbacks('InflectedRoute');
});

// for the non-prefix routes
Router::scope('/', function ($routes) {
// more code ...

Step 2: Create a folder called Admin inside your Controllers folder

Dump the appropriate Controller there.

 Controller
    |
    |------Admin
    |        |
    |        |----- AppController.php
    |        |---- ProductsController.php // this handles all the admin actions  
    |        
    |----- ProductsController.php // this handles the  non-prefix actions        

Step 3: Ensure all the Controllers inside the Admin folder use the namespace namespace App\Controller\Admin;

Step 4: Make all the Controllers inside the Admin folder extend the AppController inside the Admin folder

Step 5: Add this in your beforeFilter for App/Controller/Admin/AppController

public function beforeFilter(Event $event) 
    {
        $this->viewBuilder()->theme('AppUI'); // AppUI is my plugin name
        $this->viewBuilder()->layout('AppUI.backend'); 
    }

Why this works?

Because theme now should be a plugin. See http://book.cakephp.org/3.0/en/views/themes.html#themes

And I quote

Themes in CakePHP are simply plugins that focus on providing template files.

Like this:

 plugins
    |
    |------AppUI
    |        |
    |        |----- src
             |        |
             |        |---- Template
                      |        |---- Layout
                               |        |---- backend.ctp

Upvotes: 7

Related Questions