Developing an MVC Component/Using the database/fr: Difference between revisions
From Joomla! Documentation
Updating to match new version of source page |
No edit summary |
||
| Line 438: | Line 438: | ||
S:MyLanguage/J3.x:Developing_an_MVC_Component/Basic backend|Suiv. : Backend de base | S:MyLanguage/J3.x:Developing_an_MVC_Component/Basic backend|Suiv. : Backend de base | ||
</div>|class=expand success}}</div> | </div>|class=expand success}}</div> | ||
<div class="large-6 columns">{{Basic button| | <div class="large-6 columns">{{Basic button|S:MyLanguage/J3.x:Developing_an_MVC_Component/Basic backend|Suiv. : Backend de base|class=expand}}</div> | ||
</div> | </div> | ||
Revision as of 13:23, 29 March 2018
Les articles de cette série
Ajout d'un type de menu à la partie site
Ajout d'un modèle à la partie site
Ajout d'une requête de variable dans le type de menu
Utilisation de la base de données
Backend de base
Ajout de la gestion des langues
Ajout d'actions en backend
Ajout de décorations pour le backend
Ajout de vérifications
Ajout de catégories
Ajout de configuration
Ajout d'un fichier script installation/désinstallation/mise à jour
Ajout d'un formulaire de frontend
Utilisation du filtre de langues
- Ajouter une fenêtre modale
- Ajout d'associations
- Ajout de Checkout
- Ajout d'un filtre
- Ajout de niveaux
- Ajout de versions
- Ajout de tags
- Ajout d'accès
- Ajout d'un processus de traitement
- Ajout d'un cache
- Ajout d'un fil d'actualité
Ajout d'un serveur de mise à jour
Ceci est une série qui regroupe plusieurs articles pour devenir un didacticiel sur la façon de développer un Composant pour Joomla!
suivant le principe Modèle-Vue-Contrôleur.
Commencez avec l'introduction, et naviguez dans les articles de cette série soit à l'aide des boutons de navigation en bas des articles, soit grâce au menu de droite : Les articles de cette série.
Introduction
Ce didacticiel fait partie de la série de didacticiels sur le Développement d'un Composant MVC pour Joomla! 3.x. Vous êtes invité à lire les articles précédents de cette série avant de lire celui-ci.
There are also 3 videos associated with this step in the tutorial, covering the Database Setup, Displaying the message (using JTable) and Admin message selection (and JDatabase).
Utiliser la base de données
Les composants gèrent généralement leur contenu à l'aide de la base de données. Lors de la procédure d'installation/désinstallation/mise à jour d'un composant, vous pouvez exécuter des requêtes SQL par l'utilisation de fichiers texte SQL.
A l'aide de votre gestionnaire de fichiers et éditeur préférés, créez deux fichiers nommés admin/sql/install.mysql.utf8.sql et admin/sql/updates/mysql/0.0.6.sql. Ils devraient tous les deux avoir le même contenu :
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!');
Le fichier install.mysql.utf8.sql sera exécuté lorsque vous installez le composant. Le fichier 0.0.6.sql est exécuté lorsque vous effectuez une mise à jour.
Voici le fichier d'installation. Il sera exécuté si vous respectez un ordre approprié dans votre fichier helloworld.xml.
Remarque importante : Lors de l'enregistrement des fichiers SQL en utf8, assurez-vous de bien les enregistrer en utf8 SANS BOM, sinon la requête échouera avec l'erreur MySQL #1064.
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>
Faites de même avec le fichier de désinstallation :
A l'aide de votre gestionnaire de fichiers et éditeur préférés, ajoutez un fichier admin/sql/uninstall.mysql.utf8.sql contenant :
admin/sql/uninstall.mysql.utf8.sql
DROP TABLE IF EXISTS `#__helloworld`;
Schema Numbering
Your component has a version number (which is specified inside the <version> tag in your helloword.xml manifest file), and your component's database schema has its own version number (which is based on the filenames of the sql update files).
Joomla keeps track of the database schema version of your component through a record in its #__schemas table. So when you first install a component, if there's a file called, say, admin/sql/updates/mysql/0.0.6.sql, then Joomla will store the value 0.0.6 it its schemas record.
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.
If you have already released versions of your component when you introduce database use, as we have simulated in this tutorial series, then your first update file must have exactly the same content as the install file. If you have not, then it should be empty.
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.
Ajouter un nouveau type de champ
Pour le moment, nous avons utilisé un type de champ encodé en dur pour les messages. Nous devons utiliser notre base de données pour choisir le message.
Modifiez le fichier site/views/helloworld/tmpl/default.xml et ajoutez ces lignes :
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>
Cela introduit un nouveau type de champ et indique à Joomla! de rechercher la définition du champ dans le dossier /administrator/components/com_helloworld/models/fields.
A l'aide de votre gestionnaire de fichiers et éditeur préférés, ajoutez un fichier site/models/helloworld.php contenant :
Le nouveau type de champ affiche une liste déroulante des messages à choisir. Vous pouvez voir le résultat pour l'élément helloworld dans le gestionnaire des menus.
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;
}
}
Afficher le message sélectionné
Lors de la création/mise à jour d'un lien de menu de ce composant, Joomla! stocke l'identifiant du message. Le modèle HelloWorldModelHelloWorld doit maintenant calculer le message en fonction de cet identifiant et des données stockées dans la base de données.
Modifiez le fichier site/models/helloworld.php :
Le modèle demande le message à la TableHelloWorld. Cette classe de table doit être définie dans le fichier admin/tables/helloworld.php.
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];
}
}
Vous ne devriez voir aucune différence, mais si vous accédez à la base de données, vous devriez voir une table nommée jos_helloworld contenant deux colonnes : id et greeting. Ainsi que deux entrées: Hello World! et Good bye World.
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);
}
}
Empaqueter le composant
Contenu de votre répertoire de code
Créez un fichier compressé de ce répertoire ou téléchargez directement l'archive et installez-le en utilisant le gestionnaire des extensions Joomla. Vous pouvez ajouter un élément de menu pour ce composant à l'aide du gestionnaire de menus dans le backend.
- helloworld.xml
- site/helloworld.php
- site/index.html
- site/controller.php
- site/views/index.html
- site/views/helloworld/index.html
- site/views/helloworld/view.html.php
- site/views/helloworld/tmpl/index.html
- site/views/helloworld/tmpl/default.xml
- site/views/helloworld/tmpl/default.php
- site/models/index.html
- site/models/helloworld.php
- admin/index.html
- admin/helloworld.php
- admin/sql/index.html
- admin/sql/install.mysql.utf8.sql
- admin/sql/uninstall.mysql.utf8.sql
- admin/sql/updates/index.html
- admin/sql/updates/mysql/index.html
- admin/sql/updates/mysql/0.0.1.sql
- admin/sql/updates/mysql/0.0.6.sql
- admin/models/index.html
- admin/models/helloworld.php
- admin/models/fields/index.html
- #admin/models/fields/helloworld.php
- admin/tables/index.html
- admin/tables/helloworld.php
Merci de créer un pull request ou un rapport d'anomalie sur https://github.com/joomla/Joomla-3.2-Hello-World-Component pour toute incohérence dans le code ou pour modifier le code source de cette page.