首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

Magento 2 開發常用代碼片段速查手冊(20 選)

     編輯:PHP 相關知識

Magento 2 開發常用代碼片段速查手冊(20 選)

Magento 模塊開發中高頻復用的核心代碼模式,涵蓋 EAV 屬性、價格格式化、Block 重寫、集合操作、觀察者、佈局動態渲染、數據庫資源模型、後台表單、SKU/庫存編程等 20 大場景,供開發者快速檢索復制。

1. EAV 屬性指定自定義 Source Model

完整類名必須包含命名空間前綴,不能用簡寫:

$setup->addAttribute('customer', 'school', [
    'type' => 'int',
    'input' => 'select',
    'label' => 'School',
    'source' => 'Vendor\Module\Model\Entity\School', // 完整類名
]);

2. 價格格式化輸出(保留兩位小數)

echo $this->helper('Magento\Framework\Pricing\Helper\Data')
    ->currency($product->getPrice(), true, false);

3. config.xml 中 Block 重寫與命名規範

關鍵規則:<blocks> 下所有節點名稱必須小寫:

<global>
  <blocks>
    <catalog>
      <rewrite>
        <category_view>Vendor\Module\Block\Category\View</category_view>
      </rewrite>
    </catalog>
    <!-- 自定義 block 組名也必須小寫 -->
    <vendor_module>
      <class>Vendor\Module\Block</class>
    </vendor_module>
  </blocks>
</global>

4. 獲取列表頁當前排序/分頁狀態

$toolbar = $block->getToolbarBlock(); // Mage_Catalog_Block_Product_List_Toolbar
$currentOrder = $toolbar->getCurrentOrder(); // 'position'/'price'...
$currentDir   = $toolbar->getCurrentDirection(); // 'asc'/'desc'
$currentPage  = $toolbar->getCurrentPage();

5. Collection 添加排序

$collection = $this->_categoryFactory->create()->getCollection();
$collection->setOrder('position', 'ASC');

6. Collection WHERE OR 條件構建

$select = $connection->select()->from($table, 'id')
    ->where('reid = ? OR topid = ?', [$reid, $reid]);

7. 觀察者中修改訂單狀態歷史可見性

class OrderCommentObserver implements ObserverInterface {
    public function execute(EventObserver $observer) {
        $order = $observer->getEvent()->getOrder();
        $comment = $this->request->getParam('customerOrderComments');
        if ($comment) {
            $order->setCustomerNote('<br/><strong>備注:</strong> ' . $comment);
            $order->addStatusHistoryComment('備注:' . $comment)
                ->setIsVisibleOnFront(true)
                ->save();
        }
    }
}

8. 客戶賬戶左側導航模板路徑

Magento_Customer::account/navigation.phtml

9. HTML 實體轉義

echo $this->helper('Magento\Framework\Escaper')
    ->escapeHtml("<b>test</b>");

10. 動態創建 Block 並注入 Layout Action

Controller:

$block = $this->_view->getLayout()
    ->createBlock('Vendor\Module\Block\QuickCart')
    ->setTemplate('Vendor_Module::cart/cart.phtml');
echo $block->toHtml();

Block 構造函數中初始化 Action:

public function __construct(
    Template\Context $context,
    array $data = []
) {
    parent::__construct($context, $data);
    $this->addItemRender('simple', 'Magento\Checkout\Block\Cart\Item\Renderer', 'Vendor_Module::cart/item/view.phtml');
}

11. getTable() 參數映射規則

$table = $this->getTable('vendor_module/entity_name');
對應 etc/db_schema.xml 或舊版 config.xml 中 <entity_name><table>actual_table</table></entity_name>。

12. 實體模型加載更新指定字段

$model = $this->_modelFactory->create()->load($id);
$model->setData('field_name', $value)->save();

13. 後台修改產品列表默認排序

路徑:Stores → Configuration → Catalog → Catalog → Storefront → Default Product Listing Sort By

14. 獲取 Collection 總條數(含分頁)

$collection = $this->_productCollectionFactory->create();
$collection->addAttributeToSelect('*')
    ->addAttributeToFilter('promo_tag', 39)
    ->setPageSize(6);
$totalCount = $collection->getSize(); // 負載所有頁總數
$pageCount  = $collection->getLastPageNumber();

15. Select 查詢限制條數與排序

$select = $connection->select()
    ->from(['a' => $table], ['tid', 'subject'])
    ->limit($size)
    ->order('a.dateline DESC')
    ->where($whereCondition);
return $connection->fetchAll($select);

16. 編程修改產品價格與分組價

$product = $this->_productRepository->getById(614);
$product->setPrice(25);
$product->setGroupPrice([
    ['website_id' => 0, 'cust_group' => 0, 'price' => 97],
    ['website_id' => 0, 'cust_group' => 1, 'price' => 27],
    // ...
]);
$this->_productRepository->save($product);

17. 編程修改產品庫存

$stockItem = $this->_stockRegistry->getStockItemBySku($product->getSku());
$stockItem->setQty(23)->setIsInStock(true);
$this->_stockRegistry->updateStockItemBySku($product->getSku(), $stockItem);

18. 輸出 SQL 語句調試

$select = $connection->select()->from(...);
// 方法一
echo $select->__toString();
// 方法二(推薦)
$this->_logger->debug((string)$select);

19. 後台表單字段添加備註

$fieldset->addField('grade', 'select', [
    'label' => __('Grade'),
    'after_element_html' => __('Grade description help text.'),
    'required' => true,
]);

20. 按非主鍵字段加載模型

$model = $this->_modelFactory->create()->load($value, 'field_name');
$fieldValue = $model->getData('field_name');

提示:Magento 2 建議使用 Service Contracts(Repository/Interface)替代直接調用 Model/Collection,上述代碼為兼容性展示,實際項目請優先注入對應 Repository Interface。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved