How to extend a controller?

Hello,

I'm trying to extent a controller in order to separate my actions in separate files (I hate files with 10k lines) .

Here is what I'm trying to do:

Instead of

File: app/controllers/DataController.php

class DataController extends Controller
{
  public function indexAction(){
    /* Some stuff */
  }
  /*......*/
  public function magicAction(){
    /* Some other stuff */
  }
}

I want to be able to do this

File: app/controllers/DataController.php

class DataController extends Controller
{
  public function indexAction(){
    /* Some stuff */
  }
}

File: app/controllers/DataController/MagicAction.php

class MagicAction extends DataController
{
  public function magicAction(){
    /* Some other stuff */
  }
}

How can I make that happen? Am I doing it the right way? If not what's the best way to do it?

Thanks in advance :)



30.7k

Hi,

you can use subcontrollers: see example here: https://github.com/phalcon/mvc/tree/master/simple-subcontrollers

and

// in app/controllers/magic

// instead of
class MagicAction extends DataController
{
  public function magicAction(){
    /* Some other stuff */
  }
}

// use
class IndexController extends DataController
{
  public function indexAction(){  // so that you've got a route /magic
    /* Some other stuff */
  }
}

More likely you should refactor your code and move deuplicated things to some services, move some business related model logic to model etc.

Well basically you must do a Router to access the subcontrollers

Check the router configuration for subcontrollers

Good luck

Also wasn't easier just to create some trait or something?