10个最坏Magento的用法(10 worst Magento practices)

本文列举了Magento开发中的十大常见错误实践,并提供了详细的改进案例。通过避免这些错误,可以显著提升网站性能和用户体验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Wrong Magento implementation can have critical consequences as dropping conversion rates. How to save your eCommerce before bad practices? It should be in our best interest to optimize code and therefore improve user experience. PHP code issues can be easier to find and fix than infrastructure ones.

I will introduce you the 10 worst Magento development practices followed by detailed examples. I picked the most common and the most important ones. I hope this article will help many to save their eCommerce before bad practices and to optimize their code.

1. Overriding core files
Magento uses nice event hooking system, following the Observer Pattern, allowing additional functionality to be plugged in and out without modifying the core code.
Very often developers rewrite a core file when there’s a possible way to accomplish the functionality with an event observer. Magento provides a lot of events that are dispatched at different times. All of these events can be observed, and the objects provided by the events can be modified.
There’s is no possible way to rewrite the same core file more than once without creating extends chain. By using event observers multiple modules can exist at the same time without conflicting — many modules can observe the same event.

2. Collections – query results limitation
In order to improve code performance and scalability remember to apply limitation on the collection’s query results — it’s much better to do **$collection->getSize() instead of $collection->count() or count($collection)** because that ways, all of the items will be loaded from the database and than iterated.

3. Memory – fetching large result set
Method fetchAll() used to fetch and iterate over larger result sets will lead to a very long execution time, moreover PHP will probably run out of memory. The better solution is to fetch row by row using the fetch() method. For example:
Wrong:

$rowSet = $this->_getReadAdapter()->fetchAll($select);foreach ($rowSet as $row) {
    //process row}

Good:

$query = $this->_getReadAdapter()->query($select);
while ($row = $query->fetch()) {
    //process row}

4. Counting array
PHP Function count() is fast but when used in a loop this changes really severely. Calculating the size of an array on each iteration of a loop, if the array or collection contains a lot of items, will result in much longer execution time. Counting size should be done outside the loop not on each iteration.
Wrong:

for ($i = 0; $i < count($array); $i++){
    // do something}

Good:

$size = count($array);for ($i = 0; $i < $size; $i++){
    // do something}

5. SQL queries inside a loop
Very common bad practice is to load Magento models and process it inside a loop. Running SQL query is very expensive operation, and doing it in a loop tends to make it even worse. Instead of doing that we could use data collections to load models and then process it. We also need to be careful when working with collection to do not exceed memory.
Wrong:

foreach ($this->getProductIds() as $productId){
    $product = Mage::getModel('catalog/product')->load($productId);
    $this->processProduct($product);}

Good:

$collection = Mage:getResourceModel('catalog/product_collection')
    ->addFieldsToFilter('entity_id', array($this->getProductIds()))
    ->addAttributeToSelect(array('name'));

foreach ($collection as $product){
    $this->processProduct($product);}

6. Models loading
We need to remember that each time of executing load() method, separate query’ll be executed on a database. Also, loading multiple models separately, slows down our code. Models should be loaded only once, with a single SQL query.
Wrong:

$attr = Mage::getModel(‘catalog/product’)->load($productId)->getAttr();
$sku = Mage::getModel(‘catalog/product’)->load($productId)->getSku();

Good:

$product = Mage::getModel(‘catalog/product’)->load($productId);
$attr = $product->getAttr();
$sku = $product->getSku();

We also don’t always need the whole model to be loaded — we can do it only when its necessary. In other cases, load only attributes which are needed.

$productId = Mage::getModel(‘catalog/product’)->getIdBySku($sku);  

7. Cron misconfiguration
Many developers use Daemons but the most common way to schedule tasks is through Cron jobs. Magento has a cron.php file that allows developers to add a crontab node to modules configuration. You must ensure that your system has a cronjob for doing it that way.

<crontab>
    <jobs>
        <catalogrule_apply_all>
            <schedule>
                <cron_expr>0 1 * * *</cron_expr>
            </schedule>
           <run><model>catalogrule/observer::dailyCatalogUpdate</model>
            </run>
        </catalogrule_apply_all>
    </jobs>
</crontab>

8. Invalid cache usage
Speed up your Magento project by caching View parts. The HTML output of a block can be saved in the Magento cache. There’re nearly no blocks saved in the default Magento store, except the frontend and admin headers. The cache management has to be written in the constructor of the Block:
class {NS}{Module}_Block{View} extends Mage_Core_Block_Template {

    protected function _construct()
    {
        $this->addData(array(
            'cache_lifetime'    => 120,
            'cache_tags'        => array(Mage_Catalog_Model_Product::CACHE_TAG),
        ));
    }   

}

The output code will be saved in a cache until the “Product” cache will be deleted. If cache_lifetime is equal to false, it means that the cache will never expire.

9. Theme for mobile browsers
Good practice is to use optimized templates for mobile browsers. Magento can check Browser Agent and than serve a different theme, optimized for mobile. Magento allows to add exception to the most of the configuration parameters. It takes a regular expression string and compare it with the user’s browser agent.
You can use it to check what browser user’s using and set a different package, template, skin or layout. In other words, you can set a different them for mobile browsers.
Doing it is simple, just go to System -> Configuration -> General -> Design -> Package and Themesection and set-up appropriate settings.

10. Image Optimization
If you want to serve different images for mobile site, always declare width and height for them. The recommended image dimensions for mobile Magento store are:

    * Product image – 250px / 250px
    * Thumbnail120px / 120px

Don’t make the dimension larger and make sure that all your product images are of the same dimensions for height and width.
Photo by Robert Agthe

内容概要:本文详细介绍了900W或1Kw,20V-90V 10A双管正激可调电源充电机的研发过程和技术细节。首先阐述了项目背景,强调了充电机在电动汽车和可再生能源领域的重要地位。接着深入探讨了硬件设计方面,包括PCB设计、磁性器件的选择及其对高功率因数的影响。随后介绍了软件实现,特别是程序代码中关键的保护功能如过流保护的具体实现方法。此外,文中还提到了充电机所具备的各种保护机制,如短路保护、欠压保护、电池反接保护、过流保护和过温度保护,确保设备的安全性和可靠性。通讯功能方面,支持RS232隔离通讯,采用自定义协议实现远程监控和控制。最后讨论了散热设计的重要性,以及为满足量产需求所做的准备工作,包括提供详细的PCB图、程序代码、BOM清单、磁性器件和散热片规格书等源文件。 适合人群:从事电力电子产品研发的技术人员,尤其是关注电动汽车充电解决方案的专业人士。 使用场景及目标:适用于需要高效、可靠充电解决方案的企业和个人开发者,旨在帮助他们快速理解和应用双管正激充电机的设计理念和技术要点,从而加速产品开发进程。 其他说明:本文不仅涵盖了理论知识,还包括具体的工程实践案例,对于想要深入了解充电机内部构造和工作原理的人来说是非常有价值的参考资料。
内容概要:本文档详细介绍了机器人/AGV/AMR与电梯系统之间的模式切换操作指南。涵盖人工切换模式、智能自动切换以及智慧软件调控三大方面。通过AGV模式切换读卡器实现人工与机器人模式间的转换,利用无源触点隔离技术和多协议适配接口确保电梯与机器人系统的无缝对接,并设有硬件级互锁电路保障安全。智能自动切换中,机器人通过485通讯、TCP/IP等与电梯控制系统交互,在确认安全条件下启动专用模式并及时恢复。故障应急响应策略包括三级容错机制、智能诊断系统和安全优先策略,确保电梯运行的安全性和可靠性。智慧软件调控则根据场景需求灵活调整模式,提升物流高峰时段的运输效率,同时兼顾日常的人性化需求。硬件协同部分介绍了AGV电梯控制主板、楼层触点扩展板、电梯状态检测器、楼层传感器和外呼控制器等组件的作用。 适合人群:从事机器人、AGV、AMR研发与维护的技术人员,以及负责电梯系统集成和管理的专业人士。 使用场景及目标:①实现机器人/AGV/AMR与电梯系统的无缝对接;②确保模式切换过程中的安全性与可靠性;③提高物流高峰时段的运输效率;④优化日常运营中的人性化需求。 其他说明:本文档不仅提供了具体的操作步骤和技术细节,还强调了系统设计的安全性和智能化特点,适用于各类主流电梯品牌,并通过多种通信协议实现了广泛的兼容性。
内容概要:本文详细介绍了如何利用西门子200SMART PLC与两台三菱E700变频器通过Modbus RTU协议实现通信的方法。文中涵盖了硬件准备、通信协议设置、PLC程序设计、变频器设置与响应、源程序及其注释、相关软件工具和使用说明。具体来说,文章首先介绍了所需的硬件设备如PLC、变频器、通信电缆和触摸屏,然后讲解了Modbus RTU通信协议的具体设置,包括波特率、数据位等参数的配置。接着,文章展示了PLC程序的设计思路,重点在于如何用Modbus指令完成数据交互,并通过详细的注释使程序易于理解。此外,还涉及了变频器作为从站的设置方法,确保其能正确响应PLC发出的命令。最后,提供了昆仑通泰触摸屏软件、200SMART V2.4编程软件、变频器应用说明书等辅助工具,方便用户更好地掌握整个系统的运作。 适用人群:从事工业自动化领域的工程师和技术人员,尤其是那些需要深入了解PLC与变频器间通信机制的人群。 使用场景及目标:适用于希望构建高效稳定的工业控制系统的企业和个人开发者。通过学习本文提供的实例,读者可以掌握PLC与变频器之间的Modbus通信技术,从而实现对生产设备的精准控制,提升工作效率的同时减少能源消耗。 其他说明:本文不仅提供了理论指导,还有实际的操作指南和完整源代码,有助于读者快速上手实践。同时,配套的软件和文档资料也为后续的学习和项目开发打下了坚实的基础。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值