Search code examples
phpjoomlaundefined

How do I initialize my custom joomla 2.5 model?


Okay so I've been following the joomla 2.5 tutorial here and I've managed to make a non faulty initial component.

But I'm wondering how do I import extra classes into the framework?

I have a model class called auth.php

// No direct access to this file
defined('_JEXEC') or die('Restricted access');

// import Joomla modelitem library
jimport('joomla.application.component.modelitem');

/**
 * Auth Model
 */
class AutoBaseModelAuth extends JModelItem
{
    function detail()
    {   
        echo "this is test";
    }
}

Located in C:/xampp/htdocs/com_autobase/model/auth.php

xampp
(source: iforce.co.nz)

And my view...

// No direct access to this file
defined('_JEXEC') or die('Restricted access');

// import Joomla view library
jimport('joomla.application.component.view');

/**
 * HTML View class for the AutoBase Component
*/
class AutoBaseViewAutoBase extends JView
{
    // Overwriting JView display method
    function display($tpl = null) 
    {       
        $db     =& JFactory::getDBO();
        //request the auth model
        $model  =& $this->getModel('auth');
        $items =& $model->detail();
    }
}

But I keep getting this error obliviously because it hasn't been imported yet... and I've been on about 5 different websites trying to find out how Joomla imports new models.

Notice: Undefined index: auth in C:\xampp\htdocs\libraries\joomla\application\component\view.php on line 413

So can someone please explain how models are initialized in joomla? and what I'm doing wrong.. thanks!


Solution

  • We usually have this static function in a helper that we include in all our components

    public static function getModel($name, $component_name = null, $config = array()) {
    
        //Use default configured component unless other component name supplied
        if(!$component_name) {
            $component_name = self::$com_name;
        }
    
        jimport('joomla.application.component.model');
        $modelFile = JPATH_SITE . DS . 'components' . DS . $component_name . DS . 'models' . DS . $name.'.php';
        $adminModelFile = JPATH_ADMINISTRATOR . DS . 'components' . DS . $component_name . DS . 'models' . DS . $name.'.php';
        if (file_exists($modelFile)) {
            require_once($modelFile);
        } elseif (file_exists($adminModelFile)) {
            require_once($adminModelFile);
        } else {
            JModel::addIncludePath(JPATH_SITE . DS . 'components' . DS . $component_name . DS . 'models');
        }
    
        //Get the right model prefix, e.g. UserModel for com_user
        $model_name = str_replace('com_', '', $component_name);
        $model_name = ucfirst($model_name).'Model';
    
        $model = JModel::getInstance($name, $model_name, $config);
    
        return $model;
    }
    

    You can then get a model anywhere by going

    $model = helper::getModel('Name', 'ComponentName');