Mugo Web main content.

How to create image aliases in eZ Publish using PHP

By: Cosmin Atanasiu | September 4, 2012 | eZ Publish development tips

Image aliases are used in eZ Publish to define image sizes and other image variations. As an example, this allows for the editor to upload an image once and have it automatically formatted for a thumbnail display, a full size display, and more. By default, image alias files are automatically created whenever they are displayed in a template. However, you might have other use cases whereby you need to generate image alias files outside of the default scenario (for example, for an external site or feed).

Some quick code to generate an image alias in PHP is as follows:

$img = eZImageManager::instance();
$img->convert( $sourcePath, $destPath, $aliasName );

This might work on some installs, but is not the best practice use of the eZ Publish PHP API. You have to specify a non-intuitive direct source and destination path, but more importantly, you will run into a problem if you use a DFS cluster setup. In short, because the path information is more complex (images are served through a script that manages cache files and the NFS path), the alias won't be saved to disk with the previous code. In order to deal with this, we need to update our code to:

$myObject = eZContentObject::fetch( $objectID );
$dataMap = $myObject->attribute( 'data_map' );
$imageAttribute = $dataMap[ 'image' ];
$imageHandler = new eZImageAliasHandler( $imageAttribute );
$result = $imageHandler->imageAlias( $aliasName );
return $result['full_path'];

This piece of code goes through the eZ Publish content model to access an object's image attribute and triggers the image alias creation using an eZImageAliasHandler object. The aptly-named eZImageAliasHandler takes care of the proper paths. It should work on all eZ Publish setups, including the default setup and a cluster setup.

On the topic of image aliases, see also: