简体   繁体   中英

Call Model from custom component into Joomla 4 controller

I have been working in Joomla 4.2.5 and I need to convert my custom components from Joomla 3 to Joomla 4 compatible. I am trying to call model from my custom component into Joomla user controller file, but I am getting an error and code does not perform execution. I have tried few code but it is not working.

Joomla 3 code for call model from custom component into user controller:

UserController.php

JModelLegacy::addIncludePath(JPATH_SITE . '/components/com_mycomponent/models', 'MycomponentModel');            
$model = JModelLegacy::getInstance('Mycomponent', 'MycomponentModel');  

Here is my model file code in

components/Mycomponent/Models/mymodel.php

class MycomponentModelmycomponent extends JModelLegacy
{
    public function somefunction(){
      }
 }

Below is my attempt to convert above code into Joomla 4:

UserController.php

Use Joomla\CMS\MVC\Model\BaseDatabaseModel;

class UserController extends BaseController
{
  public function login()
  {
     login functions....
     
    BaseDatabaseModel::addIncludePath(JPATH_SITE .'/components/com_mycomponent/models');
    $model = BaseDatabaseModel::getInstance('Mycomponent', 'MycomponentModel');
    $model->myfunction($argument); 
  }
}

components/Mycomponent/Models/mymodel.php

namespace Joomla\Component\mycomponent\Site\Model;
use Joomla\Registry\Registry;
use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\Factory;
use Joomla\CMS\MVC\Model\ListModel;

class IbousersModelIbousers extends ListModel 
{
   public function myfunction($argument){
   } 
}

But it is not working, can anyone suggest me what is wrong or how can I call model from another component in Joomla 4?

In Joomla4, you get the model from the MVCFactory.

So the equivalent of:

BaseDatabaseModel::addIncludePath(JPATH_SITE .'/components/com_mycomponent/models');
$model = BaseDatabaseModel::getInstance('Mycomponent', 'MycomponentModel');

Would be:

$mvc = Factory::getApplication()->bootComponent('com_mycomponent')->getMVCFactory();
$model = $mvc->createModel('MycomponentModel', 'Site');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM