Child pages
  • Creación de un módulo de PrestaShop

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Tabla de contenidos

Table of Contents
maxLevel2

...

Creación de un módulo de PrestaShop

...

El archivo mymodule.php debe comenzar con la siguiente prueba:

Code Block

if ( !defined( '_PS_VERSION_' ) )
  exit;

...

Code Block
titlemymodule.php
borderStylesolid

<?php
if ( !defined( '_PS_VERSION_' ) )
  exit;

class MyModule extends Module
  {
  public function __construct()
    {
    $this->name = 'mymodule';
    $this->tab = 'Test';
    $this->version = 1.0;
    $this->author = 'Firstname Lastname';
    $this->need_instance = 0;

    parent::__construct();

    $this->displayName = $this->l( 'My module' );
    $this->description = $this->l( 'Description of my module.' );
    }

  public function install()
    {
    if ( parent::install() == false )
      return false;
    return true;
    }
  }
?>

Vamos a examinar cada línea de nuestro objeto MyModule...

Code Block

public function __construct()

Define el constructor de clase.

Code Block

$this->name = 'mymodule';
$this->tab = 'Test';
$this->version = 1.0;
$this->author = 'PrestaShop';

...

  • Un atributo 'name'. Este es un identificador interno, así que hágalo único, sin caracteres especiales o espacios, y en minúsculas.
  • Un atributo 'tab'. Este es el título del cuadro que deberá contener este módulo en la lista de módulos del back office de PrestaShop. Usted puede utilizar un nombre ya existente, como Products, Blocks or Stats, o uno personalizado, como lo hicimos aquí. En este último caso, un nuevo cuadro se ha creado con su título.
  • Un número de versión para el módulo, aparece en la lista de módulos.
  • Un atributo 'author'. Este se muestra en la lista de módulos de PrestaShop.
Code Block

$this->need_instance = 0;

La bandera need_instance indica si se debe cargar la clase del módulo cuando se muestran los "Módulos", en el back-office. Si se establece en 0, el módulo no cargará, por lo tanto gastará menos recursos para generar el módulo de página. Si sus módulos necesitan mostrar un mensaje de advertencia en la página "Módulos", entonces debe establecer este atributo en 1.

Code Block

parent::__construct();

Llamar al constructor padre. Esto se debe realizar antes de cualquier uso del método $this->l() y después de la creación de $this->name.

Code Block

$this->displayName = $this->l( 'My module' );

Asignar un nombre público para el módulo, el cual será mostrado en la lista de módulos de back-office.
El método l() es parte de las herramientas de traducción de PrestaShop, y se explica más adelante.

Code Block

$this->description = $this->l( 'Description of my module.' );

Asignación de una descripción pública para el módulo, la cual se mostrará en la lista de módulos del back-office.

Code Block

public function install()
  {
  return ( parent::install() );
  }

...

Asimismo, el módulo debe contener un método uninstall() para contar con un proceso de desinstalación personalizado. Este método podría realizarse algo así como:

Code Block

public function uninstall()
  {
  if ( !parent::uninstall() )
    Db::getInstance()->Execute( 'DELETE FROM `' . _DB_PREFIX_ . 'mymodule`' );
  parent::uninstall();
  }

...

Code Block
titlemymodule.php (partial)
borderStylesolid

public function install()
  {
  if ( parent::install() == false OR !$this->registerHook( 'leftColumn' ) )
    return false;
  return true;
  }

...

public function hookLeftColumn( $params )
  {
  global $smarty;
  return $this->display( __FILE__, 'mymodule.tpl' );
  }

public function hookRightColumn( $params )
  {
  return $this->hookLeftColumn( $params );
  }

Vamos a explorar estas nuevas líneas.

Code Block

if ( parent::install() == false OR !$this->registerHook( 'leftColumn' ) )
  return false;
return true;

...

Por lo tanto, esta línea ahora se lee de esta manera: si la instalación o el "enganche" fracasa, nosotros informaremos a PrestaShop.

Code Block

public function hookLeftColumn( $params )
  {
  global $smarty;
  return $this->display(__FILE__, 'mymodule.tpl');
  }

El método hookLeftColumn() hace posible que el módulo se "enganche" en la columna izquierda del tema.
$smarty es la variable global para el sistema de plantillas Smarty, el cual utiliza PrestaShop y que tenemos que acceder.
El método display() devuelve el contenido del archivo de plantilla mymodule.tpl, si es que existe.

Code Block

public function hookRightColumn( $params )
  {
  return $this->hookLeftColumn( $params );
  }

...

Code Block
titlemymodule.tpl
borderStylesolid

<!-- Block mymodule -->
<div id="mymodule_block_left" class="block">
  <h4>Welcome!</h4>
  <div class="block_content">
    <ul>
      <li><a href="{$base_dir}modules/mymodule/mymodule_page.php" title="Click this link">Click me!</a></li>
    </ul>
  </div>
</div>
<!-- /Block mymodule -->

...

Code Block
titlemymodule_page.tpl
borderStylesolid

Welcome to my shop!
Code Block
titlemymodule_page.php
borderStylesolid

<?php
global $smarty;
include( '../../config/config.inc.php' );
include( '../../header.php' );

$smarty->display( dirname(__FILE__) . '/mymodule_page.tpl' );

include( '../../footer.php' );
?>

...

Code Block
titlemymodule_page.php
borderStylesolid

<?php
global $smarty;

include( '../../config/config.inc.php' );
include( '../../header.php' );

$mymodule = new MyModule();
$message = $mymodule->l( 'Welcome to my shop!' );
$smarty->assign( 'messageSmarty', $message ); // creation of our variable
$smarty->display( dirname(__FILE__) . '/mymodule_page.tpl' );

include( '../../footer.php' );
?>

...

Code Block
titlemymodule_page.tpl
borderStylesolid

{$messageSmarty}

PrestaShop incluye una serie de variables. Por ejemplo, {$HOOK_LEFT_COLUMN} será remplazado por el contenido de la columna izquierda, es decir, el contenido de todos los módulos que han sido unidos al hook de la columna izquierda.

...

Si necesita que se muestren todas las páginas actuales de variables de Smarty, agregue la siguiente función:

Code Block

{debug}

Los comentarios se basan en asterisco:

Code Block

{* This string is commented out *}

{*
This string is too!
*}

...

Code Block
titlemymodule.php (partial)
borderStylesolid

...
$this->displayName = $this->l( 'My module' );
$this->description = $this->l( 'Description of my module.' );
...

...

Code Block
xml
titlemymodule.tpl (partial)
borderStylesolid
xml

<li>
  <a href="{$base_dir}modules/mymodule/mymodule_page.php" title="Click this link">Click me!</a>
</li>

...

Code Block
xml
titlemymodule.tpl (partial)
borderStylesolid
xml

<li>
  <a href="{$base_dir}modules/mymodule/mymodule_page.php" title="{l s='Click this link' mod='mymodule'}">{l s='Click me!' mod='mymodule'}</a>
</li>

...

Code Block
xml
titlemymodule_page.tpl
xml

<h4>Welcome!</h4>
...
Click me!

...

Code Block
xml
titlemymodule.tpl
borderStylesolid
xml

<h4>{l s='Welcome!' mod='mymodule'}</h4>
...
{l s='Click me!' mod='mymodule'}

...

Code Block
titlemymodule.tpl
borderStylesolid

<?php

global $_MODULE;
$_MODULE = array();
$_MODULE['<{mymodule}prestashop>mymodule_2ddddc2a736e4128ce1cdfd22b041e7f'] = 'Mon module';
$_MODULE['<{mymodule}prestashop>mymodule_d6968577f69f08c93c209bd8b6b3d4d5'] = 'Description de mon module';
$_MODULE['<{mymodule}prestashop>mymodule_c66b10fbf9cb6526d0f7d7a602a09b75'] = 'Cliquez sur ce lien';
$_MODULE['<{mymodule}prestashop>mymodule_f42c5e677c97b2167e7e6b1e0028ec6d'] = 'Cliquez-moi \!';
$_MODULE['<{mymodule}prestashop>mymodule_page_c0d7cffa0105851272f83d5c1fe63a1c'] = 'Bienvenue dans ma boutique \!';

...

Code Block
titleTest.php
borderStylesolid

<?php
class Test extends ObjectModel
  {
  /** @var string Name */
  public $test;

  protected $fieldsRequired = array( 'test' );
  protected $fieldsSize = array( 'test' => 64 );
  protected $fieldsValidate = array( 'test' => 'isGenericName' );
  protected $table = 'test';
  protected $identifier = 'id_test';

  public function getFields()
    {
    parent::validateFields();
    $fields[ 'test' ] = pSQL( $this->test );
    return $fields;
    }
  }
?>

...

Code Block
titleAdminTest.php
borderStylesolid

<?php
include_once( PS_ADMIN_DIR . '/../classes/AdminTab.php' );

class AdminTest extends AdminTab
  {
  public function __construct()
    {
    $this->table = 'test';
    $this->className = 'Test';
    $this->lang = false;
    $this->edit = true;
    $this->delete = true;
    $this->fieldsDisplay = array(
      'id_test' => array(
        'title' => $this->l( 'ID' ),
        'align' => 'center',
        'width' => 25 ),
      'test' => array(
        'title' => $this->l( 'Name' ),
        'width' => 200 )
    );

    $this->identifier = 'id_test';

    parent::__construct();
    }

  public function displayForm()
    {
    global $currentIndex;

    $defaultLanguage = intval( Configuration::get( 'PS_LANG_DEFAULT' ) );
    $languages = Language::getLanguages();
    $obj = $this->loadObject( true );

    echo '
      <script type="text/javascript">
        id_language = Number('.$defaultLanguage.');
      </script>';

    echo '
      <form action="' . $currentIndex . '&submitAdd' .  $this->table . '=1&token=' . $this->token . '" method="post" class="width3">
        ' . ($obj->id ? '<input type="hidden" name="id_' . $this->table . '" value="' . $obj->id . '" />' : '').'
        <fieldset><legend><img src="../img/admin/profiles.png" />' . $this->l( 'Profiles' ) . '</legend>
          <label>'.$this->l( 'Name:' ).' </label>
          <div class="margin-form">';
    foreach ( $languages as $language )
      echo '
          <div id="name_' . $language['id_lang'|'id_lang'] . '" style="display: ' . ($language['id_lang'|'id_lang'] == $defaultLanguage ? 'block' : 'none') . '; float: left;">
            <input size="33" type="text" name="name_' . $language['id_lang'|'id_lang'] . '" value="' . htmlentities( $this->getFieldValue( $obj, 'name', intval( $language['id_lang'|'id_lang'] ) ), ENT_COMPAT, 'UTF-8' ) . '" /><sup>*</sup>
          </div>';
    $this->displayFlags( $languages, $defaultLanguage, 'name', 'name' );
    echo '
          <div class="clear"></div>
        </div>
        <div class="margin-form">
          <input type="submit" value="' . $this->l( ' Save ' ) . '" name="submitAdd' . $this->table . '" class="button" />
        </div>
        <div class="small"><sup>*</sup> ' . $this->l( 'Required field' ) . '</div>
      </fieldset>
    </form> ';
    }
  }
?>

...