Quantcast
Channel: Joomla! Forum - community, help and support
Viewing all articles
Browse latest Browse all 917

Joomla! 5.x Coding • Re: Reading data from an external database in a model

$
0
0
Since I never explicitly create the model myself, I have successfully specified the required database in the construction of my model, and the actual working code is shown below.

My component shows Blog articles from a different (Joomla 3) database that was too complex to convert. Users can search and display the articles from the current (Joomla 5) site, thus preserving the historical records that go back several years. The details of the external database are specified in the menu definition of what is otherwise a list that follows the usual paradigm.

As in many cases, once one has overcome the lack of documentation it is quite straightforward, but I would not have been able to solve the problem without the help and support offered by this Forum. I am most grateful.

Code:

    use Joomla\CMS\Factory;    use Joomla\CMS\MVC\Model\ListModel;    use Joomla\Database\DatabaseFactory;    class ArticlesModel extends ListModel {    public function __construct($config = []) {        $params = Factory::getApplication()->getMenu()->getActive()->getParams();        parent::__construct($config);        if ($params->get('site') == 'remote') {            $options = array();            $options['driver'] = 'mysqli';                                      // Database driver name            $options['host'] = $params->get('server');               // Database host name            $options['database'] = $params->get('database');  // Database name            $options['user'] = $params->get('user');                 // User for database authentication            $options['password'] = $params->get('password'); // Password for database authentication            $options['prefix'] = $params->get('prefix');              // Database prefix            // external database connection            $dbFactory = new DatabaseFactory();            try {                $dbDriver = $dbFactory->getDriver('mysqli', $options);                $this->setDatabase($dbDriver);            } catch (\RuntimeException $exception) {                Factory::getApplication()->enqueueMessage(                        Text::sprintf('JLIB_DATABASE_ERROR_FUNCTION_FAILED', $e->getCode(), $e->getMessage()),                        'warning'                );            }            if (empty($dbDriver)) {                throw new \RuntimeException("Joomla did not return a database object.");            }          }        }

Statistics: Posted by CharlieBigley — Tue Sep 03, 2024 7:00 pm



Viewing all articles
Browse latest Browse all 917

Trending Articles





<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>