J3.x

J3.x: Entwicklung einer MVC Komponente/Verwendung der Datenbank

From Joomla! Documentation

Revision as of 21:08, 11 October 2024 by Vomoa (talk | contribs) (Created page with "Inhalt des Verzeichnisses mit dem Code")
Joomla! 
3.x
Tutorial
Entwicklung einer MVC Komponente

Hinzufügen einer variablen Anfrage zum Menütyp

Benutzung der Datenbank

Backend-Grundlagen

Hinzufügen von Sprachen

Hinzufügen von Aktionen im Backend

Hinzufügen von Dekorationen zum Backend

Hinzufügen von Validierungen

Hinzufügen von Kategorien

Hinzufügen einer Konfiguration

  1. Hinzufügen von ACL

Hinzufügen eines Installations-/Deinstallations-/Aktualisierungs-Skriptes

Hinzufügen eines Formulars im Frontend

  1. Hinzufügen von Bildern
  2. Hinzufügen von Karten
  3. Hinzufügen von AJAX
  4. Hinzufügen eines Alias

Benutzung des Sprachenfilters

  1. Hinzufügen von Modalen
  2. Hinzufügen von Verknüpfungen
  3. Hinzufügen der Freigabe/Sperrung von Elementen
  4. Hinzufügen von Sortierungen
  5. Hinzufügen von Ebenen
  6. Hinzufügen von Versionen
  7. Hinzufügen von Schlagwörtern (Tags)
  8. Hinzufügen von Zugriffsebenen
  9. Hinzufügen von Stapelverarbeitungen
  10. Hinzufügen eines Cache-Speichers
  11. Hinzufügen eines Feeds

Hinzufügen eines Aktualisierungs-Servers

  1. Adding Custom Fields
  2. Upgrading to Joomla4



Dies ist eine Artikel-Serie mit Tutorials über die Entwicklung einer Modal-View-Controller Komponente für Joomla! VersionJoomla 3.x.

Beginne mit der Einführung und navigiere durch die Artikel dieser Serie mit Hilfe des Buttons am Ende der Seite oder der Box auf der rechten Seite ("Artikel in dieser Serie").



Einleitung

Dieses Tutorial ist ein Teil der Artikelserie mit Tutorials über Developing an MVC Component for Joomla! 3.3. Es wird empfohlen die vorherigen Teile des Tutorials zu lesen, bevor dieser Teil gelesen wird. Es wird auch empfohlen weitere Quellen über über Datenbankabfragen, die Auswahl von Daten aus einer Datenbanktabelle und das Abrufen von Daten in verschiedenen Formaten zu lesen.

Zu diesem Teil gibt es auch drei Videos: - Setup der Datenbank the Database Setup - Anzeigen der Nachricht (unter Verwendung von JTable) Displaying the message (using JTable) - Auswahl der Nachricht im Admin-Bereich (unter Verwendung von JDatabase) Admin message selection (and JDatabase).

Verwendung der Datenbank

Komponenten verwalten ihren Inhalt in der Regel über die Datenbank. Während der Installations-/Deinstallations-/Aktualisierungsphase einer Komponente können SQL-Abfragen mithilfe von SQL-Textdateien ausgeführt werden.

Mit dem bevorzugten Dateimanager und Editor sollen zwei Dateien erstellt werden: - admin/sql/install.mysql.utf8.sql - admin/sql/updates/mysql/0.0.6.sql Beide sollen den gleichen, folgenden Inhalt haben:

admin/sql/install.mysql.utf8.sql and admin/sql/updates/mysql/0.0.6.sql

DROP TABLE IF EXISTS `#__helloworld`;

CREATE TABLE `#__helloworld` (
	`id`       INT(11)     NOT NULL AUTO_INCREMENT,
	`greeting` VARCHAR(25) NOT NULL,
	`published` tinyint(4) NOT NULL DEFAULT '1',
	PRIMARY KEY (`id`)
)
	ENGINE =MyISAM
	AUTO_INCREMENT =0
	DEFAULT CHARSET =utf8;

INSERT INTO `#__helloworld` (`greeting`) VALUES
('Hello World!'),
('Good bye World!');

""Anmerkung."" Für die aktuell verwendete Datenbankstruktur wird folgende Angabe empfohlen:

ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 DEFAULT COLLATE=utf8mb4_unicode_ci;

anstelle der oben genannten. InnoDB ist die modernere (und jetzt standardmäßige) MySQL-Datenbank-Engine, die MyISAM ersetzt, und mit dem Format utf8mb4 eine breitere Palette von Zeichensätzen einschließlich Emojis unterstützt. Es wurden jedoch nicht alle Teile des Tutorials mit dieser Einstellung getestet. Wenn die weiteren Teile der Tutorial-Serie durchgearbeitet und InnoDB verwendet wird, dann wird empfohlen diese Datei auch in den anderen Teilen des Tutorials zu aktualisieren.

Also note that if you look at a Joomla database many of the key database tables have a field called 'title' for the sort of information which we're storing in our 'greeting' field. It's generally advisable to follow the Joomla pattern, and use 'title' as the field name, as when we try to use more complex functionality (such as ACL and associations) some of the core Joomla javascript routines we want to reuse expect a 'title' field to be present. (Something to consider changing when this tutorial series is next updated).

Oft gibt es in der Datenbanktabelle ein Feld, in dem der Veröffentlichungs- bzw. Nichtveröffentlichungsstatus eines Eintrags festgehalten wird. Die Verwendung des Namens 'state' innerhalb von Joomla wird nicht empfohlen, da dies zu Konflikten führen kann, stattdessen wird der Name 'published' verwendet.
Hinweis: Wie kann man Joomla anweisen, den Wert des veröffentlichten Formularfeldes in einem Datenbankfeld mit einem anderen Namen zu speichern? Wir tun dies durch die Verwendung der Methode setColumnAlias() (seit Joomla 3.4.0).

Die Datei install.mysql.utf8.sql wird ausgeführt, wenn diese Komponente installiert wird. Die Datei updates/mysql/0.0.6.sql wird ausgeführt, wenn ein Update durchgeführt wird.

Damit die Installation bzw. das Update durchgeührt werden kann, müssen die entsprechenden Dateien in der Datei helloworld.xml angegeben werden.

Wichtiger Hinweis: Wenn die SQL-Dateien in utf8 gespeichert wird, dann muss sichergestellt werden, dass sie als utf8 NOT BOM gespeichert wird, ansonsten wird die Abfrage mit dem MySQL-Fehler #1064 fehlschlagen.

helloworld.xml

<?xml version="1.0" encoding="utf-8"?>
<extension type="component" version="3.0" method="upgrade">

	<name>Hello World!</name>
	<!-- The following elements are optional and free of formatting constraints -->
	<creationDate>January 2018</creationDate>
	<author>John Doe</author>
	<authorEmail>john.doe@example.org</authorEmail>
	<authorUrl>http://www.example.org</authorUrl>
	<copyright>Copyright Info</copyright>
	<license>License Info</license>
	<!--  The version string is recorded in the components table -->
	<version>0.0.6</version>
	<!-- The description is optional and defaults to the name -->
	<description>Description of the Hello World component ...</description>

	<install> <!-- Runs on install -->
		<sql>
			<file driver="mysql" charset="utf8">sql/install.mysql.utf8.sql</file>
		</sql>
	</install>
	<uninstall> <!-- Runs on uninstall -->
		<sql>
			<file driver="mysql" charset="utf8">sql/uninstall.mysql.utf8.sql</file>
		</sql>
	</uninstall>
	<update> <!-- Runs on update; New since J2.5 -->
		<schemas>
			<schemapath type="mysql">sql/updates/mysql</schemapath>
		</schemas>
	</update>

	<!-- Site Main File Copy Section -->
	<!-- Note the folder attribute: This attribute describes the folder
		to copy FROM in the package to install therefore files copied
		in this section are copied from /site/ in the package -->
	<files folder="site">
		<filename>index.html</filename>
		<filename>helloworld.php</filename>
		<filename>controller.php</filename>
		<folder>views</folder>
		<folder>models</folder>
	</files>

	<administration>
		<!-- Administration Menu Section -->
		<menu link='index.php?option=com_helloworld'>Hello World!</menu>
		<!-- Administration Main File Copy Section -->
		<!-- Note the folder attribute: This attribute describes the folder
			to copy FROM in the package to install therefore files copied
			in this section are copied from /admin/ in the package -->
		<files folder="admin">
			<!-- Admin Main File Copy Section -->
			<filename>index.html</filename>
			<filename>helloworld.php</filename>
			<!-- SQL files section -->
			<folder>sql</folder>
			<!-- tables files section -->
			<folder>tables</folder>
			<!-- models files section -->
			<folder>models</folder>
		</files>
	</administration>

</extension>

Mit der Datei zur Deinstallation wird genau so verfahren:

Mit dem bevorzugten Dateimanager und Editor soll die Datei admin/sql/uninstall.mysql.utf8.sql erstellt werden, die folgenden Inhalt enthält:

admin/sql/uninstall.mysql.utf8.sql

DROP TABLE IF EXISTS `#__helloworld`;

Schematische Nummerierung

Die Komponente besitzt eine Versionsnummer (diese ist innerhalb des Tags <version> in der Manifestdatei helloword.xml angegeben). Das Schema der Datenbank der Komponente besitzt eine eigene Versionsnummer (diese basiert auf den Dateinamen der Sql-Update-Dateien).

Joomla speichert die Version des Datenbankschemas der jeweiligen Komponente durch einen Datensatz in der Tabelle #__schemas wenn eine Komponente erstmalig installiert wird. Liegt z.B. eine Datei namens admin/sql/updates/mysql/0.0.6.sql vor, dann wird Joomla den Wert 0.0.6 in der Datenbank als Version speichern.

When you next install a newer version of this component - it doesn't have to be the next version, you can skip versions - Joomla will do the following:

  • it will retrieve the component's latest database schema version from its #__schemas table - so it might find in our example the value 0.0.6.
  • it will get the filenames of all the files in the admin/sql/updates/mysql/ directory, and organise them in numerically increasing order.
  • it will process in order the update files which have filenames numerically after the current schema version - so it might find files called 0.0.7.sql, 0.0.9.sql and 0.0.10.sql, and process these in order.
  • it will update the schemas record to have the number of the last update file which it processed - eg 0.0.10.

Wenn Sie bereits eine Versionen der Komponente ohne Datenbanknutzung veröffentlicht wurde, dann sollten sie folgenden Hinweis beachten. Mit der erstmaligen Nutzung der Datenbank durch die Komponente muss die Aktualisierungsdatei dann den gleichen Inhalt haben, wie die Installationsdatei.

Although it may be a good idea to keep the two version numbers in step, you don't have to. Joomla takes the schema version from the name of the numerically last update file. That's why it is recommended that there should be an initial update file, even if it's empty. If you want to keep your schema numbers in step with the component version numbers when you update your code but not the database schema, you simply include an update file to go with the new release number, and that update file, too, will be empty.

As you make subsequent releases of your component the database install file must always contain the full schema and the update files only need to contain any changes you have made to the schema since the last update.

Adding a new field type

For the moment, we have used a hard coded field type for messages. We need to use our database for choosing the message, and for this we need to define a custom field type (which we call helloworld below) as described here.

Bearbeite die Datei site/views/helloworld/tmpl/default.xml und ergänze folgende Zeilen:

site/views/helloworld/tmpl/default.xml

<?xml version="1.0" encoding="utf-8"?>
<metadata>
	<layout title="COM_HELLOWORLD_HELLOWORLD_VIEW_DEFAULT_TITLE">
		<message>COM_HELLOWORLD_HELLOWORLD_VIEW_DEFAULT_DESC</message>
	</layout>
	<fields
			name="request"
			addfieldpath="/administrator/components/com_helloworld/models/fields"
			>
		<fieldset name="request">
			<field
					name="id"
					type="helloworld"
					label="COM_HELLOWORLD_HELLOWORLD_FIELD_GREETING_LABEL"
					description="COM_HELLOWORLD_HELLOWORLD_FIELD_GREETING_DESC"
					/>
		</fieldset>
	</fields>
</metadata>

It introduces a new field type and tells Joomla to look for the field definition in the /administrator/components/com_helloworld/models/fields folder.

In order to learn more on database queries, selecting data from a database table and retrieving it in several formats click here. Mit dem bevorzugten Dateimanager und Editor soll die Datei admin/models/fields/helloworld.php erstellt werden, die folgenden Inhalt enthält:

admin/models/fields/helloworld.php

<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_helloworld
 *
 * @copyright   Copyright (C) 2005 - 2018 Open Source Matters, Inc. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

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

JFormHelper::loadFieldClass('list');

/**
 * HelloWorld Form Field class for the HelloWorld component
 *
 * @since  0.0.1
 */
class JFormFieldHelloWorld extends JFormFieldList
{
	/**
	 * The field type.
	 *
	 * @var         string
	 */
	protected $type = 'HelloWorld';

	/**
	 * Method to get a list of options for a list input.
	 *
	 * @return  array  An array of JHtml options.
	 */
	protected function getOptions()
	{
		$db    = JFactory::getDBO();
		$query = $db->getQuery(true);
		$query->select('id,greeting');
		$query->from('#__helloworld');
		$db->setQuery((string) $query);
		$messages = $db->loadObjectList();
		$options  = array();

		if ($messages)
		{
			foreach ($messages as $message)
			{
				$options[] = JHtml::_('select.option', $message->id, $message->greeting);
			}
		}

		$options = array_merge(parent::getOptions(), $options);

		return $options;
	}
}

The new field type displays a drop-down list of messages to choose from. You can see the result of this change in the menu manager section for the helloworld item.

Display the chosen message

When a menu item of this component is created/updated, Joomla stores the identifier of the message. The HelloWorldModelHelloWorld model has now to compute the message according to this identifier and the data stored in the database. To do this is uses the JTable functionality, which is an alternative to JDatabase if only CRUD operations on single records are required.

Modify the site/models/helloworld.php file:

site/models/helloworld.php

<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_helloworld
 *
 * @copyright   Copyright (C) 2005 - 2018 Open Source Matters, Inc. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

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

/**
 * HelloWorld Model
 *
 * @since  0.0.1
 */
class HelloWorldModelHelloWorld extends JModelItem
{
	/**
	 * @var array messages
	 */
	protected $messages;

	/**
	 * Method to get a table object, load it if necessary.
	 *
	 * @param   string  $type    The table name. Optional.
	 * @param   string  $prefix  The class prefix. Optional.
	 * @param   array   $config  Configuration array for model. Optional.
	 *
	 * @return  JTable  A JTable object
	 *
	 * @since   1.6
	 */
	public function getTable($type = 'HelloWorld', $prefix = 'HelloWorldTable', $config = array())
	{
		return JTable::getInstance($type, $prefix, $config);
	}

	/**
	 * Get the message
	 *
	 * @param   integer  $id  Greeting Id
	 *
	 * @return  string        Fetched String from Table for relevant Id
	 */
	public function getMsg($id = 1)
	{
		if (!is_array($this->messages))
		{
			$this->messages = array();
		}

		if (!isset($this->messages[$id]))
		{
			// Request the selected id
			$jinput = JFactory::getApplication()->input;
			$id     = $jinput->get('id', 1, 'INT');

			// Get a TableHelloWorld instance
			$table = $this->getTable();

			// Load the message
			$table->load($id);

			// Assign the message
			$this->messages[$id] = $table->greeting;
		}

		return $this->messages[$id];
	}
}

The model now asks the TableHelloWorld to get the message. This table class has to be defined in admin/tables/helloworld.php file

admin/tables/helloworld.php

<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_helloworld
 *
 * @copyright   Copyright (C) 2005 - 2018 Open Source Matters, Inc. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */
// No direct access
defined('_JEXEC') or die('Restricted access');

/**
 * Hello Table class
 *
 * @since  0.0.1
 */
class HelloWorldTableHelloWorld extends JTable
{
	/**
	 * Constructor
	 *
	 * @param   JDatabaseDriver  &$db  A database connector object
	 */
	function __construct(&$db)
	{
		parent::__construct('#__helloworld', 'id', $db);
	}
}

You shouldn't see any differences, but if you access the database you should see a table named jos_helloworld with two columns: id and greeting. And two entries: Hello World! and Good bye World.

Die Komponente zur Bereitstellung vorbereiten

Inhalt des Verzeichnisses mit dem Code

Create a compressed file of this directory or directly download the archive and install it using the extension manager of Joomla. You can add a menu item of this component using the menu manager in the backend.

General Information

Please create a pull request or issue at https://github.com/joomla/Joomla-3.2-Hello-World-Component for any code discrepancies or if editing any of the source code on this page.

Contributors