SugarCRM: добавление собственного вспомогательного класса

Недавно я попал в SugarCRM, банкомат. Мне нужно реализовать собственный регистратор, идея состоит в том, чтобы получить некоторые соответствующие данные из объекта Bean после сохранения логического хука и поместить их в XML (по запросу). Я думаю, что реализация его как модуля Sugar может быть неправильным подходом.

Вопрос в том, где правильно разместить мой класс, в иерархии каталогов, и как мне его загрузить?

заранее спасибо


person Vova Lando    schedule 07.10.2014    source источник
comment
comment
@MatthewPoer, пожалуйста, прочитайте вопрос, у меня нет проблем с реализацией Logger, у меня проблемы с тем, куда я должен поместить свой код. Здоровья, Вова   -  person Vova Lando    schedule 07.10.2014
comment
Суть в этом сообщении предполагает custom/Company/Helper/Logger.php, что кажется мне странным, я бы создал файл класса в custom/include/MyLogger.php, чтобы его можно было легко найти, запросить и вызвать в логических ловушках.   -  person Matthew Poer    schedule 07.10.2014
comment
Хотя я также задал тот же вопрос в SugarCRM, вот ответ, который я получил: поскольку вы можете указать в logic_hooks.php, что вы хотите выполнить, вы можете поместить свой собственный код, где хотите. Лично я помещаю код, который используется несколькими модулями, в каталог SugarCRM/custom/mystuff/. Я использую каталог .../modules/hooks/ для вещей, специфичных для этого модуля.   -  person Vova Lando    schedule 07.10.2014


Ответы (1)


Вы захотите поместить свой класс в custom/include/SugarLogger и назвать его как-нибудь вроде SugarXMLLogger (это гибко, но следует соглашению внутри SugarCRM). Убедитесь, что имя класса совпадает с именем файла.

Вы должны как минимум реализовать LoggerTemplate и, если вам нужна полная структура регистратора по умолчанию, используемого SugarCRM, вы должны расширить SugarLogger. Однако для простого XML-логгера это не совсем необходимо.

Хотя я знаю, что вы не просили код для фактического ведения журнала, при тестировании фактической сборки пользовательского регистратора я решил сделать его. Это моя попытка очень простого XML-логгера с использованием SimpleXML. Я проверил это на Ping API, чтобы посмотреть, как он работает, используя как фатальные журналы в XML, так и все журналы в XML.

<?php
/** 
 * Save to custom/include/SugarLogger/SugarXMLLogger.php
 * 
 * Usage: 
 * To make one particular log level write to the XML log do this:
 * ```php
 * <?php
 * LoggerManager::setLogger('fatal', 'SugarXMLLogger');
 * $GLOBALS['log']->fatal('Testing out the XML logger');
 * ```
 * 
 * To make all levels log to the XML log, do this
 * ```php
 * <?php
 * LoggerManager::setLogger('default', 'SugarXMLLogger');
 * $GLOBALS['log']->warn('Testing out the XML logger');
 * ```
 */

/**
 * Get the interface that his logger should implement
 */
require_once 'include/SugarLogger/LoggerTemplate.php';

/**
 * SugarXMLLogger - A very simple logger that will save log entries into an XML
 * log file
 */
class SugarXMLLogger implements LoggerTemplate
{
    /**
     * The name of the log file
     * 
     * @var string
     */
    protected $logfile = 'sugarcrm.log.xml';

    /**
     * The format for the timestamp entry of the log
     * 
     * @var string
     */
    protected $dateFormat = '%c';

    /**
     * The current SimpleXMLElement logger resource
     * 
     * @var SimpleXMLElement
     */
    protected $currentData;

    /**
     * Logs an entry to the XML log
     * 
     * @param string $level The log level being logged
     * @param array $message The message to log
     * @return boolean True if the log was saved
     */
    public function log($level, $message)
    {
        // Get the current log XML
        $this->setCurrentLog();

        // Append to it
        $this->appendToLog($level, $message);

        // Save it
        return $this->saveLog();
    }

    /**
     * Saves the log file
     * 
     * @return boolean True if the save was successful
     */
    protected function saveLog()
    {
        $write = $this->currentData->asXML();
        return sugar_file_put_contents_atomic($this->logfile, $write);
    }

    /**
     * Sets the SimpleXMLElement log object
     * 
     * If there is an existing log, it will consume it. Otherwise it will create
     * a SimpleXMLElement object from a default construct.
     */
    protected function setCurrentLog()
    {
        if (file_exists($this->logfile)) {
            $this->currentData = simplexml_load_file($this->logfile);
        } else {
            sugar_touch($this->logfile);
            $this->currentData = simplexml_load_string("<?xml version='1.0' standalone='yes'?><entries></entries>");
        }
    }

    /**
     * Adds an entry of level $level to the log, with message $message
     * 
     * @param string $level The log level being logged
     * @param array $message The message to log
     */
    protected function appendToLog($level, $message)
    {
        // Set some basics needed for every entry, starting with the current
        // user id
        $userID = $this->getUserID();

        // Get the process id
        $pid = getmypid();

        // Get the message to log
        $message = $this->getMessage($message);

        // Set the timestamp
        $timestamp = strftime($this->dateFormat);

        // Add it to the data now
        $newEntry = $this->currentData->addChild('entry');
        $newEntry->addChild('timestamp', $timestamp);
        $newEntry->addChild('pid', $pid);
        $newEntry->addChild('userid', $userID);
        $newEntry->addChild('level', $level);
        $newEntry->addChild('message', $message);
    }

    /**
     * Gets the user id for the current user, or '-none-' if the current user ID
     * is not attainable
     * 
     * @return string The ID of the current user
     */
    protected function getUserID()
    {
        if (!empty($GLOBALS['current_user']->id)) {
            return $GLOBALS['current_user']->id;
        } 

        return '-none-';
    }

    /**
     * Gets the message in a loggable format
     * 
     * @param mixed $message The message to log, as a string or an array
     * @return string The message to log, as a string
     */
    protected function getMessage($message)
    {
        if (is_array($message) && count($message) == 1) {
            $message = array_shift($message);
        }

        // change to a human-readable array output if it's any other array
        if (is_array($message)) {
            $message = print_r($message,true);
        }

        return $message;
    }
}
person RobertGonzalez    schedule 08.10.2014