Path

7x / documentation / tutorials / developing ez publish exten... / accessing the database


Caution: This documentation is for eZ Publish legacy, from version 3.x to 6.x.
For 5.x documentation covering Platform see eZ Documentation Center, for difference between legacy and Platform see 5.x Architecture overview.

Accessing the database

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.

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).

<?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

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.

Next we create the static functions create(), fetchByID(), fetchList(), getListCount(). There are three different types in which the data will be shown:
 eZPersistentObject::fetchObject()
 eZPersistentObject::fetchObjectList()
 direct SQL command

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)
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:

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.

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.

<?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.

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).