我想在magento2中覆盖抽象类的受保护函数
这是我的代码
di.xml
text-overflow: fade;
AbstractPdf.php(自定义/销售/型号/订购/ PDF / AbstractPdf.php)
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Magento\Sales\Model\Order\Pdf\AbstractPdf" type="Custom\Sales\Model\Order\Pdf\AbstractPdf" />
</config>
我已使用上述文件覆盖核心模型,但我无法获得解决方案。
请帮我解决这个问题。
答案 0 :(得分:5)
您无法覆盖受保护的功能。但是,您可以覆盖调用该受保护方法的公共方法。在我的情况下,我需要覆盖名为insertLogo
的方法。然而,这是我无法覆盖的受保护方法。所以我重写了在insertLogo
方法中调用getPdf
的Invoice.php。在同一个文件中,我重新定义了insertLogo
更新
这是文件
app/code/Vendor/Modulename/Model/Order/Pdf/Invoice.php
代码
namespace Vendor\Modulename\Model\Order\Pdf;
class Invoice extends \Magento\Sales\Model\Order\Pdf\Invoice
{
public function getPdf($invoices = [])
{
//some code
$order = $invoice->getOrder();
/* Add image */
//$this->insertLogo($page, $invoice->getStore());
/* Calling custom function*/
$this->insertLogoCustom($page, $invoice->getStore());
/* Add address */
$this->insertAddress($page, $invoice->getStore());
//some more code
return $pdf;
}
protected function insertLogoCustom(&$page, $store = null)
{
$this->y = $this->y ? $this->y : 815;
$image = $this->_scopeConfig->getValue(
'sales/identity/logo',
\Magento\Store\Model\ScopeInterface::SCOPE_STORE,
$store
);
if ($image) {
$imagePath = '/sales/store/logo/' . $image;
if ($this->_mediaDirectory->isFile($imagePath)) {
$image = \Zend_Pdf_Image::imageWithPath($this->_mediaDirectory->getAbsolutePath($imagePath));
$top = 830;
//top border of the page
$widthLimit = 270;
//half of the page width
$heightLimit = 270;
//assuming the image is not a "skyscraper"
/* Modified this code to convert pixel in points */
$width = $image->getPixelWidth()* 72 / 96;
$height = $image->getPixelHeight()* 72 / 96;
//preserving aspect ratio (proportions)
$ratio = $width / $height;
if ($ratio > 1 && $width > $widthLimit) {
$width = $widthLimit;
$height = $width / $ratio;
} elseif ($ratio < 1 && $height > $heightLimit) {
$height = $heightLimit;
$width = $height * $ratio;
} elseif ($ratio == 1 && $height > $heightLimit) {
$height = $heightLimit;
$width = $widthLimit;
}
$y1 = $top - $height;
$y2 = $top;
$x1 = 25;
$x2 = $x1 + $width;
//coordinates after transformation are rounded by Zend
$page->drawImage($image, $x1, $y1, $x2, $y2);
$this->y = $y1 - 10;
}
}
}
}
希望它有所帮助!