Descargar la presentación
La descarga está en progreso. Por favor, espere
1
Herramientas - Documentación
* * 1
2
Herramientas - Git (colaborar en el proyecto prestashop)
- Jira (sistema de seguimiento de bugs. Prestashop forge) - Generador de módulos - Validador de módulos 2
3
Herramientas - Herramientas de desarrollo * Netbeans * Xdebug
* Firebug * PrestaShop norm validator (PHP_CodeSniffer) * Standard coding hook (git) * Testing framework (PHPUnit) * Go to validator in the FAQ module 1.4.0 3
4
Desarrollando módulos
- Ficheros * Directorio del módulo (nombre_del_módulo) * Fichero “hook” (nombre_del_módulo.php) * Ficheros de idioma (en 1.6 van dentro del directorio ./translations/) * Fichero cache de configuración (config.xml) * Controladores ./controllers/ * Clases* sobreescritas ./override/ * Ficheros de vistas (en 1.6 van dentro del directorio ./views/). “./views/css”, “./views/sass”, “./views/js”, “./views/templates/front” (vistas usadas por el controlador), “./views/templates/hooks” (vistas usadas por los hooks del módulo) * Logos (16x16 gif / 32x32 png) * Readme.md * Para versiones superiores a puede haber un directorio ./test con los ficheros de testeo 4
5
Desarrollando módulos
Fichero “hook” <?php if (!defined('_PS_VERSION_')) exit; class HelloWorld extends Module { } 5
6
Desarrollando módulos
La función de inicialización: public function __construct() { $this->name = 'helloworld'; $this->tab = 'front_office_features'; $this->version = '1.0.0'; $this->author = 'Me'; $this->bootstrap = true; // New 1.6 $this->ps_versions_compliancy = array('min' => '1.5', 'max' => '1.6'); // required Prestashop 1.5 $this->dependencies = array('blockcart'); // need blockcart module. ... } Desde este momento el módulo es visible en el backoffice 6
7
Desarrollando módulos
La función de inicialización: public function __construct() { ... parent::__construct(); $this->displayName = $this->l('Hello World'); $this->description = $this->l('This is an example module'); $this->confirmUninstall = $this->l('Are you sure you want to uninstall?'); if (!Configuration::get('HELLO_WORLD_NAME')) $this->warning = $this->l('No name provided'); } Desde este momento el módulo es visible en el backoffice 7
8
Desarrollando módulos
Ejemplo 'blockcategories' (La función de inicialización) } 8
9
Desarrollando módulos
El fichero cache: El fichero cache lo puede crear automáticamente Prestashop, y se va a utilizar para que se generen las listas de módulos de forma más rápida en el backoffice. <?xml version="1.0" encoding="UTF-8" ?> <module> <name>helloworld</name> <displayName>Hello World></displayName> <version>1.0></version> <description>This is an example module></description> <author>Moi</author> ... </module> 9
10
Desarrollando módulos
El fichero cache: El fichero cache lo puede crear automáticamente Prestashop, y se va a utilizar para que se generen las listas de módulos de forma más rápida en el backoffice. <?xml version="1.0" encoding="UTF-8" ?> <module> ... <tab>front_office_features></tab> <confirmUninstall>Are you sure you want to uninstall?</confirmUninstall> <is_configurable>1</is_configurable> <need_instance>1</need_instance> <limited_countries></limited_countries> </module> 10
11
Desarrollando módulos
Ejemplo 'blockbanner' (El fichero cache) </module> 11
12
Desarrollando módulos
La función de instalación: public function install() { if (Shop::isFeatureActive()) Shop::setContext(Shop::CONTEXT_ALL); if (!parent::install() OR !$this->registerHook('leftColumn') OR !$this->registerHook('header') OR !Configuration::updateValue('HELLO_WORLD_NAME', 'World')) return false; return true; } 12
13
Desarrollando módulos
Ejemplo 'blockcategories' (La función de instalación) $tab->module = $this->name; } 13
14
Desarrollando módulos
Ejemplo 'blockcategories' (La función de instalación) !$this->registerHook('leftColumn') || } 14
15
Desarrollando módulos
Ejemplo 'blockcategories' (La función de instalación) } 15
16
Desarrollando módulos
La función de desinstalación: public function uninstall() { if (!parent::uninstall() || !Configuration::deleteByName('HELLO_WORLD_NAME') ) return false; return true; } 16
17
Desarrollando módulos
Ejemplo 'blockcategories' (La función de desinstalación) public function uninstall() { if (!parent::uninstall() || !Configuration::deleteByName('HELLO_WORLD_NAME') ) return false; return true; } 17
18
Desarrollando módulos
Función para mostrar algo en algún hook: public function hookDisplayLeftColumn($params) { $this->context->smarty->assign(array( 'name' => Configuration::get('HELLO_WORLD_NAME') )); return $this->display(__FILE__, 'helloworld.tpl'); } 18
19
Desarrollando módulos
Función para mostrar algo en algún hook (Cont.) Podemos reutilizar el código para otro hook: public function hookDisplayRightColumn($params) { return $this->hookDisplayLeftColumn($params); } 19
20
Desarrollando módulos
Función para mostrar algo en algún hook (Cont.) Si queremos añadir archivos css o js utilizaremos: public function hookDisplayHeader($params) { $this->context->controller->addCSS($this->_path.'views/css/helloworld.css', 'all'); } 20
21
Desarrollando módulos
Función para mostrar algo en algún hook (Cont.) HookDisplay...: Para usar un Hook en un Template usamos Smarty, {hook h='NameOfHook'} </div> Para usar un Hook en un Controller, Hook::exec('NameOfHook') $this->context->smarty->assign('HOOK_LEFT_COLUMN', Hook::exec('leftColumn')); 21
22
Desarrollando módulos
Función para mostrar algo en algún hook (Cont.) HookDisplay... (Cont.) Para usar un Hook en un Módulo debemos crear un método no estático y publico, cuyo nombre comience por "hook", seuido de "Display" o "Action" (según el hook en el que queramos mostrar o ejecutar código), y el nombre del hook que queramos. Al metodo le pasaremos un solo argumento, con información del objeto context. } 22
23
Desarrollando módulos
Función para mostrar algo en algún hook (Cont.) HookDisplay... (Cont.) Para responder a la llamada de un hook en el módulo, este hook debe estar registrado en PrestaShop. El registro se realiza con la función "registerHook". El registro* se crea durante la instalación del módulo. } 23
24
Desarrollando módulos
Función para mostrar algo en algún hook (Cont.) HookDisplay... (Cont.) Podemos crear un nuevo hook, añadiendo un nuevo registro a la tabla "ps_hook"*, y teniendo en cuenta que vamos a tener que incorporar este hook a nuestro tema... $myHook->save(); Desde la versión 1.5, se añaden automaticamente los hook a la tabla 'ps_hook', cuando llamamos a la función registerHook('nameOfHook') en la clase del módulo. 24
25
Desarrollando módulos
Configurar nuestro módulo: public function getContent() { $output = ''; if (Tools::isSubmit('submit'.$this->name)) { $HELLO_WORLD_NAME = strval(Tools::getValue('HELLO_WORLD_NAME')); if (!$HELLO_WORLD_NAME OR empty($HELLO_WORLD_NAME) OR !Validate::isGenericName($HELLO_WORLD_NAME)) $output .= $this->displayError( $this->l('Invalid Configuration value') ); else ... } 25
26
Desarrollando módulos
Configurar nuestro módulo (Cont.) public function getContent() { ... else { Configuration::updateValue('HELLO_WORLD_NAME', $HELLO_WORLD_NAME); $output .= $this->displayConfirmation($this->l('Settings updated')); } } return $output.$this->displayForm(); } 26
27
Desarrollando módulos
Configurar nuestro módulo (Cont.) Para mostrar nuestra página de configuración: public function displayForm() { } 27
28
Desarrollando módulos
Configurar nuestro módulo (Cont.) Para mostrar nuestra página de configuración: public function displayForm() { $default_lang = (int)Configuration::get('PS_LANG_DEFAULT'); // Get default Language $fields_form[0]['form'] = array( // Init Fields form array 'legend' => array( 'title' => $this->l('Settings') ), 'input' => array( … } 28
29
Desarrollando módulos
Configurar nuestro módulo (Cont.) public function displayForm() { 'input' => array( array( 'type' => 'text', 'label' => $this->l('Configuration value'), 'name' => 'HELLO_WORLD_NAME', 'class' => 'fixed-width-xs', // extra small 'required' => true ) ), 'submit' => array( … } 29
30
Desarrollando módulos
Configurar nuestro módulo (Cont.) public function displayForm() { 'submit' => array( 'title' => $this->l('Save'), 'class' => 'button' ) ); … } 30
31
Desarrollando módulos
Configurar nuestro módulo (Cont.) public function displayForm() { … $helper = new HelperForm(); $helper->module = $this; // Module, Token and currentIndex $helper->name_controller = $this->name; $helper->token = Tools::getAdminTokenLite('AdminModules'); $helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name; ... } 31
32
Desarrollando módulos
Configurar nuestro módulo (Cont.) public function displayForm() { … $helper->default_form_language = $default_lang; // Language $helper->allow_employee_form_lang = $default_lang; $helper->title = $this->displayName; // title and Toolbar $helper->show_toolbar = true; // false -> remove toolbar $helper->toolbar_scroll = true; // true- > Toolbar is always visible on the top of the screen. $helper->submit_action = 'submit'.$this->name; … } 32
33
Desarrollando módulos
Configurar nuestro módulo (Cont.) public function displayForm() { … $helper->toolbar_btn = array( 'save' => array( 'desc' => $this->l('Save'), 'href' => AdminController::$currentIndex.'&configure='.$this->name.'&save'. $this- >name.'&token='.Tools::getAdminTokenLite('AdminModules' ), ), 'back' => array( 'desc' => $this->l('Back to list'), 'href' =>AdminController::$currentIndex.'&token='. Tools::getAdminTokenLite('AdminModules') ) ); ... } 33
34
Desarrollando módulos
Configurar nuestro módulo (Cont.) Para mostrar nuestra página de configuración: public function displayForm() { … $helper->fields_value['HELLO_WORLD_NAME'] = Configuration::get('HELLO_WORLD_NAME'); // Load current value return $helper->generateForm($fields_form); } 34
35
Desarrollando módulos
- Ficheros * Directorio del módulo (nombre_del_módulo) * Fichero “hook” (nombre_del_módulo.php) * Ficheros de idioma (en 1.6 van dentro del directorio ./translations/) * Fichero cache de configuración (config.xml) * Controladores ./controllers/ * Clases* sobreescritas ./override/ * Ficheros de vistas (en 1.6 van dentro del directorio ./views/). “./views/css”, “./views/sass”, “./views/js”, “./views/templates/front” (vistas usadas por el controlador), “./views/templates/hooks” (vistas usadas por los hooks del módulo) * Logos (16x16 gif / 32x32 png) * Readme.md * Para versiones superiores a puede haber un directorio ./test con los ficheros de testeo 35
36
Desarrollando módulos
Mecanismo automático de actualización del módulo: Creamos un subdirectorio ./upgrade/ dentro del directorio de nuestro módulo. En la función de inicialización debemos definir cual va a ser la nueva versión de nuestro módulo ($this->version = '1.1';) Creamos un script en php para cada nueva versión (/upgrade/install-1.1.php) /* * File /upgrade/install-1.1.php */ function upgrade_module_1_1($ module) { //Process Module upgrade to 1.1 // .... return true; // Return true if successful . } 36
37
Desarrollando módulos
Modelo: Dentro de nuestro módulo podemos crear nuestro ObjectModel, para acceder a nuestra tabla, incluso podemos crear tantos como tablas . Los métodos principales son: public __construct( integer $id = null, integer $id_lang = null, integer $id_shop = null ) // Build object public boolean add( boolean $autodate = true, boolean $null_values= false ) // Add current object to database public boolean delete( ) // Delete current object from database public new duplicateObject( ) // Duplicate current object to database public array getFields( ) // Fill an object with given data. Data must be an array with this syntax: array(objProperty => value, objProperty2 => value, etc.) ... 37
38
Desarrollando módulos
Modelo (Cont.) Dentro de nuestro módulo podemos crear nuestro ObjectModel, para acceder a nuestra tabla, incluso podemos crear tantos como tablas . Los métodos principales son (Cont.) ... public hydrate( array $data, integer $id_lang = null) // Fill (hydrate) a list of objects in order to get a collection of these objects public static array hydrateCollection( string $class, array $datas, integer $id_lang = null ) public boolean save( boolean $null_values = false, boolean $autodate = true) // Save current object to database (add or update) public boolean toggleStatus( ) // Toggle object status in database public boolean update( boolean $null_values = false ) // Update current object to database // Prepare fields for ObjectModel class (add, update) All fields are verified (pSQL, intval...) 38
39
Desarrollando módulos
Modelo (Cont.) La definición: /** * Example for the CMS Template( CMSCore) */ public static$definition= array( 'table' => 'cms', 'primary' => 'id_cms', 'multilang' => true,//'multilang_shop' => true [multi-idioma + multi-tienda] 'fields' => array( ... 39
40
Desarrollando módulos
Modelo (Cont.) La definición (Cont.) /** * Example for the CMS Template( CMSCore) */ public static$definition= array( … 'fields' => array( 'id_cms_category' =>array('type' => self::TYPE_INT, 'validate'=> 'isUnsignedInt'), 'position' => array('type' => self::TYPE_INT), 'active' => array ('type' => self::TYPE_BOOL), // Lang fields ... 40
41
Desarrollando módulos
Modelo (Cont.) La definición (Cont.) public static$definition= array( … // Lang fields 'meta_description' =>array('type'=>self::TYPE_STRING, 'lang'=>true, 'validate'=>'isGenericName', 'size'=>255), 'meta_keywords' => array('type'=>self::TYPE_STRING, 'lang'=>true, 'validate'=>'isGenericName', 'size'=>255), 'meta_title' => array('type' =>self::TYPE_STRING, 'lang'=>true, 'validate'=>'isGenericName', 'required'=>true, 'size'=>128), 'link_rewrite' => array('type' => self::TYPE_STRING, 'lang'=>true, 'validate'=>'isLinkRewrite', 'required'=>true, 'size'=>128), 'content' => array ('type' => self::TYPE_HTML, 'lang' => true,'validate' => 'isString', 'size' => ), ) ); 41
42
Desarrollando módulos
Modelo (Cont.) Tipos de campos para la definición: * TYPE_BOOL * TYPE_DATE * TYPE_FLOAT * TYPE_HTML * TYPE_INT * TYPE_NOTHING * TYPE_STRING 42
43
Desarrollando módulos
La clase DBQuery: public __toString( ): Generate and get the query public string build( ): Generate and get the query public from( string $table, mixed $alias= null ): Set table for FROM clause public groupBy( string $fields ): Add a GROUP BY restriction public having( string $restriction ): Add a restriction in HAVING clause( each restriction will be separated by AND statement) public innerJoin( string $table, string $alias = null, string $on = null ): Add INNER JOIN clause, E.g. $this->innerJoin('product p ON ...') ... 43
44
Desarrollando módulos
La clase DBQuery (Cont.) … public join( string $join ): Add JOIN clause, E.g. $this->join('RIGHT JOIN '._DB_PREFIX_.'product p ON ...'); public leftJoin( string $table, string $alias= null, string $on= null ): Add LEFT JOIN clause public leftOuterJoin( string $table, string $alias = null, string $on = null ): Add LEFT OUTER JOIN clause public limit( string $limit, mixed $offset= 0 ): Limit results in query public naturalJoin( string $table, string $alias = null ): Add NATURAL JOIN clause publicorderBy( string $fields ): Add an ORDER B restriction public select( string $fields ): Add fields in query selection public where( string $restriction ): Add a restriction in WHERE clause (each restriction will be separated by AND statement) 44
45
Desarrollando módulos
La clase DBQuery (Cont.) $sql = new DbQuery(); $sql->select('*'); $sql->from('cms', 'c'); $sql->innerJoin('cms_lang', 'l', 'c.id_cms = l.id_cms AND l.id_lang = '.(int)$id_lang); $sql->where('c.active = 1'); $sql->orderBy('position'); return Db::getInstance()->executeS($sql); 45
46
Desarrollando módulos
Helpers Continuaremos... 46
Presentaciones similares
© 2025 SlidePlayer.es Inc.
All rights reserved.