magento - 按顺序运行多个 Magento DataFlow 配置文件

标签 magento

我正在开发一个 Magento 扩展,允许用户将类别、产品和其他类型的数据从不同的网上商店解决方案导入到 Magento 中。为了实现这一目标,我设置了几个负责导入的 DataFlow 高级配置文件。

到目前为止,它工作正常,但配置文件需要按适当的顺序运行(首先是类别,然后是产品,等等)。为了使非技术用户尽可能简单,并最大限度地减少人为错误的可能性,我想按顺序自动运行配置文件。理想情况下,您只需按一个“运行配置文件”按钮,然后在 DataFlow 处理配置文件的同时观察草的生长几个小时。

我似乎无法完成这个任务。我的主要问题是 - 这可能吗?如果是,那么如何?

我尝试将多个配置文件合并到同一个 XML 文件中(实际上只是将 2 个配置文件复制粘贴到一个 XML 中),但这不起作用。输入文件已被解析,但不知何故,负责实际导入的适配器类并未运行。

是否有一种方法可以告诉配置文件在完成后开始另一个配置文件(例如通过“完成”方法)? 或者也许我应该编写一个小控制面板,您可以在其中单击“运行”按钮,然后控制面板通过一些 AJAX 巫术处理序列?

不幸的是,使用命令行脚本不是一个选项,使用 Magmi 也不是一个选项。

为了完整起见,我必须提及所有配置文件都包含:

  • 读取 CSV 文件的 IO 适配器
  • 自定义 CSV 解析器(从默认的 DataFlow CSV 解析器复制,并进行一些调整以解决输入文件中的怪癖)
  • 执行导入的自定义适配器

最佳答案

这就是我运行单个配置文件作为更大的 cron 作业的一部分的方式。让它运行多个配置文件应该很容易。而且您应该能够通过按下按钮来使其运行。 该脚本伪造管理员用户登录后端并按下一些按钮。它看起来有点复杂,但这是在其他一些方法由于脚本作为 cron 作业运行而无法正常工作之后唯一的工作方法。

将两个脚本文件放入 magento 根目录的 shell 文件夹中:

mag_import.php:

<?php

/**
 * Path to the root of your magento installation
 */
$root = '/absolute/path/to/your/magento/root/';

/**
 * Url to your magento shop.
 */
$url = 'http://www.mygreatwebshop.url/';

/**
 * relative path from the magento root to the login file.
 */
$login = 'shell/mag_login.php';

/**
 * name of the logfile, will be places in magentoroot/var/log/
 */
$logFileName = 'import.log';

/**
 * how many products will be parsed at each post. Usually 10-50.
 */
$atOnce = 25;

/**
 * Dataflow profile id
 */    
$profileId = 8;

/**
 * DO NOT EDIT BELOW THIS LINE
 */
function convert($size) {
    $unit = array('b', 'kb', 'mb', 'gb', 'tb', 'pb');
    return @round($size / pow(1024, ($i = floor(log($size, 1024)))), 2) . ' ' . $unit[$i];
}

set_time_limit(0);

if (!isset($profileId)) {
    exit("\nPlease specify a profile id. You can find it in the admin panel->Import/Export->Profiles.\nUsage: \n\t\t php -f $argv[0] PROFILE_ID\n\t example: php -f $argv[0] 7\n");
}

$recordCount = 0;

require_once $root . 'app/Mage.php';
ob_implicit_flush();
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);

//starting the import
Mage::log("\n\n", null, $logFileName);
Mage::log(convert(memory_get_usage()) . " - " . "STARTING IMPORT", null, $logFileName);

$profile = Mage::getModel('dataflow/profile');
$userModel = Mage::getModel('admin/user');
$userModel->setUserId(0);

Mage::getSingleton('admin/session')->setUser($userModel);

if ($profileId) {
    $profile->load($profileId);
    if (!$profile->getId()) {
        Mage::getSingleton('adminhtml/session')->addError('ERROR: Could not load profile');
    }
}

/**
 * get the login information.
 */
exec("/usr/bin/php -f {$root}{$login}", $result);

$loginInformation = json_decode($result[0]);
$sessionId = $loginInformation->sessionId;
$formKey = $loginInformation->formKey;

//clean dataflow_batch_import table so it doesn't get amazingly big.
$db = Mage::getSingleton('core/resource')->getConnection('core_write');
$db->query("TRUNCATE TABLE `dataflow_batch_import`");
Mage::log(convert(memory_get_usage()) . " - " . "Table dataflow_batch_import cleaned", null, $logFileName);

//load profile
if ($profileId) {
    $profile->load($profileId);
    if (!$profile->getId()) {
        Mage::getSingleton('adminhtml/session')->addError('ERROR: Could not load profile');
    }
}
Mage::register('current_convert_profile', $profile);

//run the profile
Mage::log(convert(memory_get_usage()) . " - " . "Preparing profile...", null, $logFileName);
$profile->run();
Mage::log(convert(memory_get_usage()) . " - " . "...Done", null, $logFileName);

//get to work
$batchModel = Mage::getSingleton('dataflow/batch');
if ($batchModel->getId()) {
    //echo "getId ok\n";
    if ($batchModel->getAdapter()) {

        //echo "getAdapter ok\n";

        $batchId = $batchModel->getId();
        Mage::log(convert(memory_get_usage()) . " - " . "Loaded batch id $batchId", null, $logFileName);

        $batchImportModel   = $batchModel->getBatchImportModel();
        $importIds          = $batchImportModel->getIdCollection();
        $batchModel         = Mage::getModel('dataflow/batch')->load($batchId);
        $adapter            = Mage::getModel($batchModel->getAdapter());
        $postdata           = array();
        $postnum            = 0;
        $totalproducts      = count($importIds);

        Mage::log(convert(memory_get_usage()) . " - 0/{$totalproducts}", null, $logFileName);
        foreach ($importIds as $importId) {
            //echo "importing $importId\n";
            $recordCount++;
            $postdata[] = "rows[]=$importId";
            //echo "$importId ";
            if ($recordCount % $atOnce == 0 || $recordCount == $totalproducts) {
                $postnum++;
                $postdata[] = "batch_id=$batchId";
                $postdata[] = "form_key=$formKey";
                $postdatastring = implode('&', $postdata);
                $postdata = array();
                //print_r($postdatastring);
                Mage::log(convert(memory_get_usage()) . " - Start cURL request #$postnum", null, $logFileName);
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url . "index.php/admin/system_convert_profile/batchRun/?isAjax=true");
                curl_setopt($ch, CURLOPT_TIMEOUT, 200);
                curl_setopt($ch, CURLOPT_COOKIE, "adminhtml=$sessionId");
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $postdatastring);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                $buffer = curl_exec($ch);
                if (empty($buffer)) {
                    Mage::log(convert(memory_get_usage()) . " - {$recordCount}/{$totalproducts} - Response is empty - ERROR" . curl_error($ch), null, $logFileName);
                } else {
                    $result = json_decode($buffer);
                    Mage::log(convert(memory_get_usage()) . " - {$recordCount}/{$totalproducts} [$buffer]", null, $logFileName);
                    if (@count($result->errors)) {
                        foreach ($result->errors as $error) {
                            Mage::log(convert(memory_get_usage()) . " - ERROR: $error", null, $logFileName);
                        }
                    }
                }
                curl_close($ch);
            }
        }

        foreach ($profile->getExceptions() as $e) {
            Mage::log(convert(memory_get_usage()) . " - " . $e->getMessage(), null, $logFileName);
        }
    }
}

Mage::log(convert(memory_get_usage()) . " - " . "Completed!", null, $logFileName);
?>

mag_login.php:

<?php

/**
 * Path to the root of your magento installation.
 * include traing slash.
 */
$root = '/absolute/path/to/your/magento/root/'

/**
 * Backend username that has the rights to import products.
 */
$username = "username";

/**
 * Password
 */
$password = "password";

 /**
  * DO NOT EDIT BELOW THIS LINE
  */

require_once $root.'app/Mage.php';
umask(0);
Mage::app();

$user = Mage::getModel('admin/user');
if ($user->authenticate($username, $password)) 
{    
    Mage::getSingleton('admin/session')->setUser($user);

    if ($user->getId())
    {
        if (Mage::getSingleton('adminhtml/url')->useSecretKey()) {
            Mage::getSingleton('adminhtml/url')->renewSecretUrls();
        }
        $session = Mage::getSingleton("admin/session");

        //Change the owner of the session file on root/var/session/ to the user that runs the webserver
        //exec("chown nobody:nobody {$root}var/session/sess_".$session->getEncryptedSessionId());

        echo json_encode(array('sessionId' => $session->getEncryptedSessionId(), 'formKey' => Mage::getSingleton('core/session')->getFormKey()));
    }
}
?>

我不久前发现了这些脚本,并根据自己的需要对其进行了修改。

关于magento - 按顺序运行多个 Magento DataFlow 配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20288192/

相关文章:

mysql - Magento/Zend 框架 : Custom Join Statement : ERROR : Can't prepare expression when tableName is instance of Zend_Db_Expr

php - 过滤带有图像的产品的 Magento 产品系列

magento - 扩展和模块的区别?

Magento Collection,如何获取特定字段的值数组

magento - 如何获取Magento主题目录?

wordpress - 什么是一个不需要数年时间就能掌握的全面电子商务平台?

javascript - Google 网站优化器有两个 onClick 事件吗?

php - Magento 目录规则违反 MySQL 完整性约束错误

magento - 如何从订单 ID Magento 获取所有订单详细信息,包括付款客户和运输详细信息

java - 如何通过 Soap/Java 在 Magento 中创建具有附加属性的产品