Как вставить продукт prestashop в другую таблицу в моей базе данных

Я работаю над объединением Unicenta POS с prestashop, чтобы они работали вместе, особенно в плане данных (например, синхронизация продуктов).

моя идея состоит в том, чтобы создать модуль, который делает это, я объединил схему 2 баз данных и отобразил свои продукты POS на вкладке администратора в моем prestashop, и это работает (это был простой запрос sql для выполнения), но теперь то, что я хочу сделать это синхронизировать добавление моих продуктов. моя идея переопределить функцию, которая добавляет продукт в базу данных, и для этого мне нужно распознать эту функцию.

Я посмотрел (ну, не просто смотрел, а потратил время на чтение строки за строкой) в скрипте класса продукта, надеясь найти его, но тщетно, я даже заглянул в руководство разработчика, но безрезультатно. Можете ли вы помочь мне, я новичок в разработке prestashop (2 недели опыта), так что извините мой вопрос, если это может показаться глупым для некоторых:\ .

пожалуйста, помогите мне только подсказка, если это возможно:(

вот что я сделал:

Скрипт модуля:

этот модуль обеспечивает полностью автоматическое переопределение любого класса после его установки, и просто для того, чтобы очистить мой пост, я исполнил этот урок:

[ http://blog.belvg.com/how-to-make-an-override-in-your-module.html][1]

unicentapos.php

<?php 

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

/**
* 
*/
class unicentapos extends Module
{
  public function __construct()
  {
    $this->name = 'unicentapos';
    $this->tab = 'front_office_features';
    $this->version = '1.0';
    $this->author = 'Sasori Sicine';
    $this->need_instance = 0;
    $this->ps_versions_compliancy = array('min' => '1.5', 'max' => '1.6');
    $this->dependencies = array('blockcart');

    parent::__construct();

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

    $this->confirmUninstall = $this->l('Are you sure you want to uninstall?');

    if (!Configuration::get('MYMODULE_NAME'))      
      $this->warning = $this->l('No name provided');
  }


  // the unstallation function
  public function install(){

    return parent::install() &&
    $this->registerHook('backOfficeHeader') &&
    $this->registerHook('header') &&
    $this->registerHook('actionAdminControllerSetMedia') &&
    $this->registerHook('actionProductUpdate') &&
    $this->registerHook('displayAdminProductsExtra');

    // Install overrides
    try {
        $this->installOverrides();
    } catch (Exception $e) {
        $this->_errors[] = sprintf(Tools::displayError('Unable to install override: %s'), $e->getMessage());
        $this->uninstallOverrides();
        return false;
    }
  }

  // the uninstallation function

  public function uninstall(){
    if (!parent::uninstall() || !Configuration::deleteByName('MYMODULE_NAME')){
        Db::getInstance()->Execute('DELETE FROM `'._DB_PREFIX_.'unicentapos`');
        parent::uninstall();
        return false;
    } 
    return true;
  }

  /**
 * Install overrides files for the module
 *
 * @return bool
 */
public function installOverrides()
{
    // Get local path for module
    if (!is_dir($this->getLocalPath().'override'))
        return true;

    $result = true;
    foreach (Tools::scandir($this->getLocalPath().'override', 'php', '', true) as $file)
    {
        $class = basename($file, '.php');
        // Add all methods in a module override to the override class
        if (Autoload::getInstance()->getClassPath($class.'Core'))
            $result &= $this->addOverride($class); 
    }

    return $result;
}

/**
 * Add all methods in a module override to the override class
 *
 * @param string $classname
 * @return bool
 */
public function addOverride($classname)
{
    $path = Autoload::getInstance()->getClassPath($classname.'Core');

    // Check if there is already an override file, if not, we just need to copy the file
    if (!($classpath = Autoload::getInstance()->getClassPath($classname)))
    {
        $override_src = $this->getLocalPath().'override'.DIRECTORY_SEPARATOR.$path;
        $override_dest = _PS_ROOT_DIR_.DIRECTORY_SEPARATOR.'override'.DIRECTORY_SEPARATOR.$path;
        if (!is_writable(dirname($override_dest)))
            throw new Exception(sprintf(Tools::displayError('directory (%s) not writable'), dirname($override_dest)));
        copy($override_src, $override_dest);
        return true;
    }

    // Check if override file is writable
    $override_path = _PS_ROOT_DIR_.'/'.Autoload::getInstance()->getClassPath($classname);
    if (!is_writable($override_path))
        throw new Exception(sprintf(Tools::displayError('file (%s) not writable'), $override_path));

    // Make a reflection of the override class and the module override class
    $override_file = file($override_path);
    eval(preg_replace(array('#^\s*<\?php#', '#class\s+'.$classname.'\s+extends\s+([a-z0-9_]+)(\s+implements\s+([a-z0-9_]+))?#i'), array('', 'class '.$classname.'OverrideOriginal'), implode('', $override_file)));
    $override_class = new ReflectionClass($classname.'OverrideOriginal');

    $module_file = file($this->getLocalPath().'override'.DIRECTORY_SEPARATOR.$path);
    eval(preg_replace(array('#^\s*<\?php#', '#class\s+'.$classname.'(\s+extends\s+([a-z0-9_]+)(\s+implements\s+([a-z0-9_]+))?)?#i'), array('', 'class '.$classname.'Override'), implode('', $module_file)));
    $module_class = new ReflectionClass($classname.'Override');

    // Check if none of the methods already exists in the override class
    foreach ($module_class->getMethods() as $method)
        if ($override_class->hasMethod($method->getName()))
            throw new Exception(sprintf(Tools::displayError('The method %1$s in the class %2$s is already overriden.'), $method->getName(), $classname));

    // Check if none of the properties already exists in the override class
    foreach ($module_class->getProperties() as $property)
        if ($override_class->hasProperty($property->getName()))
            throw new Exception(sprintf(Tools::displayError('The property %1$s in the class %2$s is already defined.'), $property->getName(), $classname));

    // Insert the methods from module override in override
    $copy_from = array_slice($module_file, $module_class->getStartLine() + 1, $module_class->getEndLine() - $module_class->getStartLine() - 2);
    array_splice($override_file, $override_class->getEndLine() - 1, 0, $copy_from);
    $code = implode('', $override_file);
    file_put_contents($override_path, $code);

    return true;
}

  public function hookDisplayAdminProductsExtra($params){
    if (Validate::isLoadedObject($product = new Product((int)Tools::getValue('id_product')))){
      return $this->display(__FILE__, 'views/newproductfields.tpl');
    }
  }
  public function prepareNewTab(){
    $this->context->smarty->assign(array(
        'custom_field' => '',
        'languages' => $this->context->controller->_languages,
        'default_language' => (int)Configuration::get('PS_LANG_DEFAULT')
    ));
  }

  public function getContent(){
      $output = null;
      if (Tools::isSubmit('submit'.$this->name)){
          $my_module_name = strval(Tools::getValue('MYMODULE_NAME'));
          if (!$my_module_name  || empty($my_module_name) || !Validate::isGenericName($my_module_name))
              $output .= $this->displayError( $this->l('Invalid Configuration value') );
          else{
              Configuration::updateValue('MYMODULE_NAME', $my_module_name);
              $output .= $this->displayConfirmation($this->l('Settings updated'));
          }
      }
      return $output.$this->initList();
  }

  private function initList(){

      $this->fields_list = array(
          'REFERENCE' => array(
              'title' => $this->l('Id'),
              'width' => 140,
              'type' => 'text',
          ),
          'NAME' => array(
              'title' => $this->l('Name'),
              'width' => 140,
              'type' => 'text',
          ),
      );
      $helper = new HelperList();

      $helper->shopLinkType = '';

      $helper->simple_header = true;

      // Actions to be displayed in the "Actions" column
      $helper->actions = array('edit', 'delete', 'view');

      $helper->identifier = 'REFERENCE';
      $helper->show_toolbar = true;
      $helper->title = 'POS PRODUCTs LIST';
      $helper->table = $this->name.'products';

      $helper->token = Tools::getAdminTokenLite('AdminModules');
      $helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name;


////////  product with no prefix is the product table for the POS 
      $sql = 'SELECT * FROM products';
      if ($results = Db::getInstance()->ExecuteS($sql))
      foreach ($results as $row){
         $finalrow[$i] = array('REFERENCE' => $row['REFERENCE'],
                            'NAME' => $row['NAME']);
         $i++;
      }
      return $helper->generateList($finalrow,$this->fields_list);
    }


}


?>

это переопределенный класс продукта:

    <?php


    Class Product extends ProductCore
    {
        // here i'll put the extra attributes that concern the pos product tab, i dont need them for now since they have the same business logic    

        public function __construct($id_product = null, $full = false, $id_lang = null, $id_shop = null, Context $context = null)
        {

            parent::__construct($id_product, $full, $id_lang, $id_shop, $context);

        }
//here I'll put the function that i'm looking for  overridden of course by adding an insert sql script into the pos product table.     

    }

Я также сделал переопределение в файле information.tpl, добавив новые поля, но пока не обязательные, потому что я сделал это просто для того, чтобы поиграть с ним и посмотреть, как он выглядит, а также заставить мысли на практике.

это то, что я сделал, и я надеюсь получить некоторую помощь и помощь, чтобы улучшить себя как будущего разработчика prestashop

0 ответов

Другие вопросы по тегам