29-11-2011 : Remettre dans le débat politique les principes du Conseil National de la Résistance
17-02-2012 : Pétition pour une protection de l’apiculture et des consommateurs face au lobby des OGM
Logo de mon site
Logo de mon site
Faire un don

Luxpopuli / eZ Publish / Dossiers techniques / eZ Publish : An Introduction to Developing eZ Publish Extensions / Accessing the database -- Accéder à la base de données





Right menu

Logo du site ez.no  Logo XHTML 1.O du W3C  Logo XHTML 1.O du W3C  Site francophone officiel de Firefox
zero papier grâce aux catalogues et promos en ligne de bonial

eZ Publish : An Introduction to Developing eZ Publish Extensions

Table des matières

  1. Introduction au développement d'extensions eZ Publish
  2. What are eZ Publish extensions ? -- Qu'est-ce que les extensions eZ Publish ?
  3. Creating a new extension -- Créer une nouvelle extension
  4. Configuring and enabling the extension -- Configurer et activer l'extension
  5. Activating the extension -- Activer l'extension
  6. Template system -- Le système de templates
  7. Creating a view -- Créer une vue
  8. Accessing the database -- Accéder à la base de données
  9. Template fetch function -- Fonction de recherche pour template
  10. Template operators -- Les opérateurs de templates
  11. INI file -- Le fichier INI
  12. Conclusion

Accessing the database -- Accéder à la base de données

Date de publication: le samedi 20 août 2011 à 09h24
Dernière modification: par Pascal BOYER le samedi 3 septembre 2011 à 20h53

Now we return to the database. We want to save the value of the form in our new table jacextension_data. To do this, we use the eZ Publish class eZPersistentObject. It contains functions for creating, changing, deleting or extracting data.
Revenons à présent à la base de données. Nous souhaitons sauvegarder les valeurs du formulaire dans notre nouvelle table jacextension_data. Pour cela, nous utiliserons la classe eZPersistentObject d'eZ Publish qui contient les fonctions de création, de suppression et d'extraction des données.

To use these functions we create a new class JACExtensionData. We save it in the folder <ezroot>/extension/jacextension/classes with the name jacextensiondata.php (see Listing 14).
Pour utiliser ces fonctions nous devons créer une nouvelle classe JACExtensionData que nous enregistrons dans le dossier <ezroot>/extension/jacextension/classes au nom de jacextensiondata.php (voir Script 14).

<?php
class JACExtensionData extends eZPersistentObject
{ 
    /** 
     * Constructor 
     *
     * @param array $row Hash of attributes for new JacExtensionData object
     */ 
    public function __construct( array $row )
    { 
        parent::eZPersistentObject( $row ); 
    }
 
    /*
     * Definition of the data object structure /of the structure of the database table 
     *
     * @return array Hash with table definition for this persistent object
     */ 
    public static function definition()
    { 
        return array( 'fields' => array( 'id' => array( 'name' => 'ID', 
                                                        'datatype' => 'integer', 
                                                        'default' => 0, 
                                                        'required' => true ),
 
                                        'user_id' => array( 'name' => 'UserID', 
                                                            'datatype' => 'integer', 
                                                            'default' => 0, 
                                                            'required' => true ),
 
                                        'created' => array( 'name' => 'Created', 
                                                            'datatype' => 'integer', 
                                                            'default' => 0, 
                                                            'required' => true ),
 
                                        'value' => array( 'name' => 'Value', 
                                                          'datatype' => 'string', 
                                                          'default' => '', 
                                                          'required' => true ) 
                                        ), 
                      'keys'=> array( 'id' ), 
                      'function_attributes' => array( 'user_object' => 'getUserObject' ), // accessing to attribute "user_object" will trigger getUserObject() method
                      'increment_key' => 'id', 
                      'class_name' => 'JACExtensionData', 
                      'name' => 'jacextension_data'
                      ); 
    }
 
    /** 
     * Help function will open in attribute function 
     * @param bool $asObject
     */ 
    public function getUserObject( $asObject = true )
    { 
        $userID = $this->attribute('user_id'); 
        $user = eZUser::fetch($userID, $asObject); 
        return $user; 
    }
 
    /**
     * Creates a new object of type JACExtensionData and shows it
     * @param int $user_id
     * @param string $value
     * @return JACExtensionData
     */
    public static function create( $user_id, $value )
    { 
        $row = array( 'id'      => null, 
                      'user_id' => $user_id, 
                      'value'   => $value, 
                      'created' => time() ); 
        return new self( $row ); 
    }
 
    /**
     * Shows the data as JACExtensionData with given id
     * @param int $id User ID
     * @param bool $asObject
     * @return JACExtensionData
     */ 
    public static function fetchByID( $id , $asObject = true)
    { 
        $result = eZPersistentObject::fetchObject( 
                                                    self::definition(), 
                                                    null, 
                                                    array( 'id' => $id ), 
                                                    $asObject, 
                                                    null, 
                                                    null ); 
 
        if ( $result instanceof JACExtensionData ) 
            return $result; 
        else 
            return false; 
    }
 
    /**
     * Shows all the objects JACExtensionData as object or array
     * @param int $asObject
     * @return array( JACExtensionData )
     */ 
    public static function fetchList( $asObject = true )
    { 
        $result = eZPersistentObject::fetchObjectList( 
                                                        self::definition(), 
                                                        null,null,null,null, 
                                                        $asObject, 
                                                        false,null ); 
        return $result; 
    }
 
    /**
     * Shows the amount of data
     * @return int 
     */ 
    public static function getListCount() 
    { 
        $db = eZDB::instance(); 
        $query = 'SELECT COUNT(id) AS count FROM jacextension_data'; 
        $rows = $db -> arrayQuery( $query ); 
        return $rows[0]['count'];
    } 
 
    // -- member variables-- 
    protected $ID;
    protected $UserID; 
    protected $Created; 
    protected $Value;
 
} 
?>
 

Listing 14. jacextension/classes/jacextensiondata.php example for access to the database with eZ PersistentObject
Script 14 : L'exemple jacextension/classes/jacextensiondata.php pour accéder à la base de données grâce à eZ PersistentObject

The most important function is JACExtensionData::definition(). This defines the object structure of JACExtensionData, specifying the table and columns where the data will be stored.
La fonction la plus importante est JACExtensionData::definition(). Elle définit la structure de l'objet de JACExtensionData tout en spécifiant la table et les colonnes où les données seront stockées.

Next we create the static functions create(), fetchByID(), fetchList(), getListCount(). There are three different types in which the data will be shown:
Nous créons à présent les fonctions statiques create(), fetchByID(), fetchList(), getListCount(). Il existe trois types différents dans lesquels les données seront affichées:

  1. eZPersistentObject::fetchObject()
  2. eZPersistentObject::fetchObjectList()
  3. direct SQL command / Commande SQL directe

If possible, you should use the functions eZPersistentObject fetch. You should not use special SQL entries for the database, which ensures that the SQL commands will work with all the databases supported by eZ Publish. (See the related API documentation at http://pubsvn.ez.no/doxygen/4.4/html/classeZPersistentObject.html)
Vous devez utiliser, dans la mesure du possible, les fonctions fetch eZPersistentObject. Vous devez éviter l'usage d'entrées SQL particulières pour la base de données afin de vous assurer que les commandes SQL fonctionneront avec toutes les bases de données supportées par eZ Publish. Reportez-vous à la documentation de l'API http://pubsvn.ez.no/doxygen/4.4/html/classeZPersistentObject.html .

Before using this new class, we need to regenerate the autoloads array. This operation makes eZ Publish know where to find each PHP class present in the system :
Avant d'utiliser cette nouvelle classe, nous devons régénérer le tableau des autochargements. Cette opération permet à eZ Publish de savoir où trouver chaque classe PHP présente sur le système:

cd /path/to/ezpublish/root

php bin/php/ezpgenerateautoloads.php -e -p

Now we use the new functions in the script create.php. To save new data we create a new object of the type JACExtensionData with the function JACExtensionData::create( $value ) . The function create() creates the transmitted value (value of the form), the current user ID and the current timestamp.
Nous pouvons à présent utiliser les nouvelles fonctions dans le script create.php. Afin de sauvegarder les nouvelles données, nous créons un nouvel objet du type JACExtensionData grâce à la fonction JACExtensionData::create( $value ). La fonction create() crée les valeurs transmises (celles du formulaire), l'ID de l'utilisateur courant ainsi que la valeur timestamp.

With the function store() we save the data in our database table jacextension_data. To see this happening we write these to the Debug view. create.php is shown below.
Avec la fonction store(), nous sauvegardons les données dans la table jacextension_data de notre base de données et pour visualiser ce qui se passe, nous les écrivons dans la vue Debug. Le fichier create.php ressemble donc à ceci:

<?php
// modul1/create.php – Function file of View create 
// ... 
$value = '';
 
// If the variable 'name' is sent by GET or POST, show variable 
if( $http->hasVariable('name') ) 
    $value = $http->variable('name');
 
if( $value != '' ) 
{
    // ask for the ID of current user 
    $userId = eZUser::currentUserID();
 
    // generate new data object 
    $JacDataObject = JACExtensionData::create( $userId, $value );
    eZDebug::writeDebug( '1.'.print_r( $JacDataObject, true ), 
                         'JacDataObject before saving: ID not set' ) ;
 
    // save object in database 
    $JacDataObject->store();
    eZDebug::writeDebug( '2.'.print_r( $JacDataObject, true ), 
                         'JacDataObject after saving: ID set' ) ;
 
    // ask for the ID of the new created object 
    $id = $JacDataObject->attribute( 'id' );
 
    // ask for the login of the user who has created the data  
    $userObject = $JacDataObject->attribute( 'user_object' ); 
    $userName = $userObject->attribute( 'login' );
 
    // show again the data 
    $dataObject = JACExtensionData::fetchByID( $id ); 
    eZDebug::writeDebug( '3.'.print_r( $dataObject, true ),
                         'JacDataObject shown with function fetchByID()');
 
    // investigate the amount of data existing 
    $count = JACExtensionData::getListCount(); 
    $statusMessage = 'Name: >>'. $value .
                     '<< of the user >>'. $userName.
                     '<< In database with ID >>'. $id.
                     '<< saved!New ammount = '. $count ; 
} 
else 
{ 
    $statusMessage = 'Please enter data'; 
}
 
// take data as object and as array and show in Output Debug 
$ObjectArray = JACExtensionData::fetchList( true );
eZDebug::writeDebug( '4. JacDataObjects: '.print_r( $ObjectArray, true ), 
                     'fetchList( $asObject = true )' );
 
$array = JACExtensionData::fetchList( false );
eZDebug::writeDebug( '5. JacDataArrays: '.print_r( $array, true ), 
                     'fetchList( $asObject = false )' );
 
// initialize Templateobject 
$tpl = eZTemplate::factory(); 
$tpl->setVariable( 'status_message', $statusMessage ); 
 
//... 
 
?>
 

Listing 15. jacextension/modules/modul1/create.php. Creating a new entry in the database and different ways of showing it.
Script 15 : le fichier jacextension/modules/modul1/create.php. Créer une nouvelle entrée dans la base de données et proposer différentes façon de l'afficher.

To access objects of the type eZPersistentObject, we use $JacDataObject- >attribute('id'). The function parameter “id” maps to the column id in the table, so we don't have to think much to access the different values. This can be applied to all data that is saved in eZ (for example eZContentObject and eZUser objects).
Pour accéder aux objets du type eZPersistentObject, nous utilisons la syntaxe $JacDataObject- >attribute('id'). Le paramètre id de la fonction correspondant à la colonne id de la table, nous n'avons rien à faire de plus pour accéder aux différentes valeurs. Et ceci peut s'appliquer à l'ensemble des données sauvegardées dans eZ (comme par exemple les objets eZContentObject et eZUser).

Commentaires