Using Multiple Controllers in Joomla Component Dev

2019-04-02 08:26发布

问题:

My structure has component.php in the root of my component. I am using the http://www.notwebdesign.com/joomla-component-creator/j15/index.php I feel the need to have multiple controllers to have cleaner code as I have around 12 tasks to be run. I am using multiple models and need to have multiple controllers.

Anyone who can point me in the right direction? Sample code highly appreciated.

回答1:

You need to make a folder in your component's main directory (e.g. components/com_mycom/controllers/...)

Then the main file of my component (it should be called "mycom.php" using the example from above) has code that looks like this:

// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

// load a constants file for use throughout the component
require_once(JPATH_COMPONENT.DS.'lib'.DS.'constants.php');

// fetch the view
$view = JRequest::getVar( 'view' , 'null' );

// use the view to fetch the right controller
require_once( JPATH_COMPONENT.DS.'controllers'.DS.$view.'.php' );

// initiate the contoller class and execute the controller
$controllerClass = 'MycomController'.ucfirst($view);
$controller = new $controllerClass;
// call the display function in the controller by default - add a task param to the url to call another function in the controller
$controller->execute( JRequest::getVar( 'task', 'display' ) ); 
$controller->redirect();

Then for your controllers in your controllers directory your code would be as normal e.g.

defined( '_JEXEC' ) or die( 'Restricted access' );
jimport('joomla.application.component.controller');

class MycomControllerAdd extends JController
{

  function display() { 
    $viewLayout  = JRequest::getVar( 'tmpl', 'add' );
    $view = &$this->getView( 'add', 'html' );
    $model = &$this->getModel( 'add' );
    $view->setModel( $model, true );
    $view->setLayout( $viewLayout );
    $view->addStuff();
  }

  ...

A url that would call this would look like so:

http://somedomain.com/index.php?option=com_mycom&view=add


标签: joomla