Update proof way to customise Magento code

如果直接修改Magento的文件,Magento每次升级后,又要重新修改,所以这肯定不是个办法。以我最近一次修改/app/code/core/Mage/Core/Model/Email/Template.php为例,修改后Magento使用gmail smtp server来发送邮件。以下我使用update proof way重作一遍。(当前Magento版本是1.1.8)

1. 不直接修改/app/code/core/Mage/Core/Model/Email/Template.php,而是新建一个/app/code/local/(MyNameSpace)/Core/Model/Email/Template.php,其中(MyNameSpace)可以随意命名。

/app/code/local/(MyNameSpace)/Core/Model/Email/Template.php 是 /app/code/core/Mage/Core/Model/Email/Template.php的子类,其中我只重载了send方法,所以,/app/code/local/(MyNameSpace)/Core/Model/Email/Template.php不需要拷贝其他部分,它完整的内容是:

class (MyNameSpace)_Core_Model_Email_Template extends Mage_Core_Model_Email_Template {
public function send($email, $name=null, array $variables = array())
{
if(!$this->isValidForSend()) {
return false;
}

if (is_null($name)) {
$name = substr($email, 0, strpos($email, ‘@’));
}

$variables[’email’] = $email;
$variables[‘name’] = $name;

$mail = $this->getMail();
if (is_array($email)) {
foreach ($email as $emailOne) {
$mail->addTo($emailOne, $name);
}
} else {
$mail->addTo($email, ‘=?utf-8?B?’.base64_encode($name).’?=’);
}

$this->setUseAbsoluteLinks(true);
$text = $this->getProcessedTemplate($variables, true);

if($this->isPlain()) {
$mail->setBodyText($text);
} else {
$mail->setBodyHTML($text);
}

$mail->setSubject(‘=?utf-8?B?’.base64_encode($this->getProcessedTemplateSubject($variables)).’?=’);
$mail->setFrom($this->getSenderEmail(), $this->getSenderName());

$config = array(
‘ssl’ => ‘ssl’, //optional
‘port’ => 465, //optional – default 25
‘auth’ => ‘login’,
‘username’ => ‘your_email’,
‘password’ => ‘your_password’);

$transport = new Zend_Mail_Transport_Smtp(‘smtp.gmail.com’, $config);

try {
$mail->send($transport); //add $transport object as parameter
$this->_mail = null;
}
catch (Exception $e) {
return false;
}

return true;
}
}

2. 新建一个/app/code/local/(MyNameSpace)/Core/etc/config.xml,内容是

<?xml version=”1.0″?>
<config>
<modules>
<(MyNameSpace)_Core>
<version>1.0.0</version>
</(MyNameSpace)_Core>
</modules>
<global>
<models>
<core>
<rewrite>
<email_template>(MyNameSpace)_Core_Model_Email_Template</email_template>
</rewrite>
</core>
</models>
</global>
</config>

据说因为Zend Framework的一个bug,tag <email_template>必须在一行内封闭,其间不得有多余的white space。我试过,确实如此。

3. 最后,在Magento注册本次重载:新建一个/app/etc/modules/(MyNameSpace)_Core.xml,内容是:

<?xml version=”1.0″?>
<config>
<modules>
<(MyNameSpace)_Core>
<active>true</active>
<codePool>local</codePool>
</(MyNameSpace)_Core>
</modules>
</config>

我只是以重载一个model class为例,重载block class也是同样步骤。按Magento的说法,重载controller class有点区别,我尚未亲试。

Leave a comment

Your email address will not be published. Required fields are marked *