-
I’ve been working with Magento for a long time and I can say that the platform changed a lot over time and I would like to share my personal thoughts on it.
How Magento 2 learned from the past to make some brand-new mistakes
I had my first encounter with Magento in 2011 and, back then, all I knew about it was that it was based on Zend Framework and that it was doing e-commerce (obviously).
I was coming from the Symfony framework world, with a lot of documentation, a great community and a rock-solid implementation. This was still Symfony 1, Symfony 2 was just coming out.
By comparison, Magento had next to no documentation, barely any community and the implementation had a plethora of bugs. In my first few days on the job I was seeing a lot of people debugging deep in the Core, I was just perplexed, I almost never needed to debug Symfony, let alone actually find bugs.
Some may argue that Symfony is a framework and Magento is a platform and the argument is as solid as a guinea pig.
The reason for this situation was simple: they didn’t expect the platform to have so much success; but it did and the reason was simple – it was pretty much the only platform in the PHP world that was built with modularity in mind at that time, period! There were other platforms, but definitely not as versatile, fully featured and modular as Magento.
Moving forward, they’ve spent a lot of time and effort in building ample documentation for Magento1, focused on quality, rock-solid stability, all paired with exceptional support for enterprise partners!
Psych! No, they did not! The documentation for M1 was always sparse and of very poor quality. Basically, the best resource was Ben Marks’ “Fundamentals of Magento Development” course, a book (about which and not entitled to an opinion, since I didn’t read it), some blog posts from individuals or companies that worked with the platform and a lot of StackOverflow questions and answers. All this was paired with exceptionally bad support for enterprise users, extremely slow and low quality solutions and, to top it off, plenty of Core bugs. It wasn’t unusual to find non-standard, half-baked implementations and bugs in the Core. But the Core was simple enough that, with Xdebug and a lot of patience, everything was more or less fixable.
Fixes coming from their support team were close to a myth. If you didn’t want to fix a bug, or just didn’t feel like working, you could open a ticket and in most cases it took days or even weeks to get a proper response. By that time you would have usually fixed it already and (in some cases) even sent the fix to their support so they can also include it in the Core.
And along comes Magento 2
With the burden of the popularity-driven growth of Magento 1, Magento 2 came to the rescue.
It took a long time for Magento 2 to be ready, and I think that is more of a story in itself, but some actions were taken to prevent some of the issues that the first version had.
Let’s look on some of the platform issues:
- classes could only be extended by overwriting;
- the frontend was based on the Prototype framework.
There were many other changes but I think these were among the most important ones.
And now let’s see how Magento 2 managed to fix all these issues
It is a good practice to start with something nice, so I will start with the documentation, Magento2 had documentation from the start and it was both useful and well made!
Regarding the classes overwrite, there were implemented two approaches:
- implementing dependency injection (from Symfony)
- implementing plugins using interceptor pattern.
Dependency injection really helped with the ability to substitute classes and functionality, and the plugins helped a lot with a non-invasive way of extending the functionality. Before plugins, only observers were able to modify data in a non-invasive way, and the big problem was that (in many cases) there just weren’t observers everywhere you needed them to be.
Unfortunately, this created a lot of overhead. Maybe in M1 you could just put a breakpoint and look in the stacktrace to see what methods are changing what, but now… it is just a lot more complex, each method has an interceptor class that triggers the plugin mechanism. Each plugin can be triggered before, after or around the method, the around method can prevent the actual method from getting called. In short, it is a lot more code with a lot more methods and a lot more code to follow. When it is working is a lot more elegant, but when it doesn’t it is a lot worse to debug.
In a dramatic twist, many of the classes were not implemented properly in the Core. You see, when Magento2 was released, a lot of compromises had to be made, and some of the Core modules were just “made to work” in the new framework. Later when everyone was expecting the cleanup to be made… it wasn’t, the reason is simple, why fix the Core when you can break compatibility with the modules already created?
This issue even made Magento Core developers suggest that you should follow the guidelines, not use the Core as an example: do what we say, not what we do.
Frontend was fixed even better! You may ask yourself what is that “prototype” library and why would anyone in their right mind choose it? It made a lot of sense back then, when Magento1 was created and there were several popular js libraries, mainly: jQuery, Prototype and MooTools. There were a lot more than these 3, but these were the popular ones. There was a war between jQuery and Prototype, just like there is now between React, Angular and Vue. The first had a new approach with almost a new language, while the second was aiming at extending the browser capabilities in a more discrete fashion. We now know who won, but back then it wasn’t obvious. As a small note, I was also a fan of Prototype back then.
The Magento 2 team realized over time that it was a mistake and, to fix it, they promised to make something more flexible. The new more flexible solution didn’t involve the Prototype library, but instead included: jQuery, Knockout.js, and Require.js just at the top level, without taking dependencies into consideration.
The idea was to separate the frontend and the backend, to have the ability to make completely new frontend APPs. And, as before, this was never properly finished and now there is a highly complicated system, partially separated, partially single page App and partially… multi page, implemented in a variety of styles. And this is only on the store front, the store backend has a slightly different, more complex system of xml, phtml, html and js files.
As a backend developer I can truly say that it is a lot harder to debug (or just to understand how the frontend part works) now than before.The XML part of generating grids is probably the hardest part, it is extremely difficult to debug anything in it and, if you mess something up, you get no warnings at all, you have to find the class that is building the grid and see if an exception is triggered there, but that is not an obvious solution at all…
And, of course, the entire thing is a lot slower because of all these “new engineering features”. When all the code is generated and the links to static resources and everything set to production mode, it isn’t slow; it isn’t exactly fast, but it isn’t terribly slow either. But when you don’t have cache, and didn’t deploy the static resources, and you are in developer mode, it is just awfully slow, it can take a few minutes to load a simple product page! It is just ridiculous if you ask me, it isn’t an operating system, or a video game, it is a shopping cart, why in the world would it take 5 minutes to display a page, even without a lot of new modules.
Keep in mind that Magento 2 didn’t come with a lot of new features, most of the functionality was in M1, only more “engineered”, so those 5 minutes of code generation and linking and whatever magic is going on in there aren’t adding a lot of new features, just a lot of refactoring of the old system.
The Magento Cloud
Magento offered a Cloud, I don’t know if they are anymore and I don’t care, nobody really cares about it anymore, mostly because it wasn’t what everybody wanted.
People want simple things, you have an app, you push it to the clouds and money starts raining down. That should be it, less things to worry about.
Demandware, who doesn’t have a nice open source core, is doing something exactly like this: you don’t have the same amount of control, but you don’t take care of your website, the gods in the clouds do! The developer only develops, doesn’t need to care about what magic operations are doing, because he is not ops, he is dev!
The Magento Commerce Cloud was aimed to do that, just push this monster in the cloud and some very smart ops will scale it for you! But it wasn’t like this, it was never easy, nor fast. And, on top of that, other hosting providers started making hosting solutions for Magento that were better at scaling then the official one, which is just ridiculous.
A positive note to end on
There is an interesting core underneath it all.There are plenty of very smart features that make the platform so popular. Now you also have tests, so you can even do TDD.
Even with all this (over) engineering challenges, there are still plenty of passionate developers out there that are able and willing to overcome them.
There are also a lot of tools developed by the community to overcome some of the shortcomings, like generate the huge amount of files required for a model, or MSP_DevTools to help with debugging the frontend, or n98-magerun2 to help with crons and lots and lots more.
And lastly, there are still a lot of very brilliant and passionate developers out there that are willing to figure out a way to develop, scale and make sales for one more day!
-
Disclaimer
Please note that this solution is tailored specifically for my needs and, while your needs may vary, don’t worry, everything is on GitHub, so feel free to take what you need.
I would like to add that this is not a “you’ve been using Docker with Magento2 wrong, this is how it’s done” kind of blog, I just want to share what I’m using and how. It may not be the best fit for you, but maybe you will find something useful.
Intro
For almost 2 years I’ve been using Magento2 in Docker containers. I’ve been doing that before, but I must admit that it was because I had to, not because I’ve seen the light, I mean advantages.
As you may know Magento2 is not exactly a small and light app, it’s quite heavy on the resources, especially during development.
Compared to a VM, with Docker you get:
- Speed: I think the speed is one of the biggest advantages, you can stop and start containers very fast, only the first build will take time, after that it will be very fast;
- Light on resources: Compared to a VM, the container does not need to include the entire operating system, so it will not take a lot of space on disk and will not use a lot of processing power, because it’s not an entire OS doing… well… OS stuff, it’s just a server most of the time.
What you don’t get:
- Learning curve: if you don’t know Docker and Docker Compose, it will be less intuitive at first;
- First setup: harder to setup at first, if you have been using a VM for a long time, you will feel that you are going against the tide, but I assure you, in the long term it will be a lot simpler this way.
Taking the above into consideration, I would like to say that when I’ve started with this setup I was using Linux with 8G of RAM. One of my colleagues even wished me good luck on installing Magento2 on a ultraportable 8Gb RAM system. He wasn’t even sarcastic, more like pitying me for my bad workstation selection.
One of the requirements was that I needed some isolation and configuration between projects, I couldn’t just install a server and be done with it.
Previously I’ve been using Vagrant and VirtualBox, a great fit, very easy to use (most of the time). However, for Magento2 I’ve realised that it was heavy enough on its own, it was making me run out of resources fast.
Also, I wanted it to be easy to use, I don’t like to have to remember and type out a 3 word command, I just want to press some tabs and get it over with.
The requirements
There were some specific requirements:
- nginx config – should work out of the box, Magento configuration isn’t very small, I wanted to make use of it with ease;
- SSL – the domain has to also work with HTTPS, mostly because some APIs require it, the certificates don’t need to be valid;
- bash – the Magento command should work as the system user, not as root (as containers usually do). This is required, because I don’t want the files generated by Magento to be generated as root (and therefore only removable with root rights);
- xdebug – must work out of the box and be easily integrated with an IDE.
The implementation and usage
Magento2 offered a Docker container to work with. I will not say anything about it, since it wasn’t at all something I needed.
My main source of inspiration was: https://github.com/markoshust/docker-magento. The project changed a lot since I’ve started, so I definitely think you should check it out.
The starter point is: https://github.com/claudiu-persoiu/magento2-docker-compose
The relevant files are:
- magento2 – it should contain a folder html with the project
- dkc_short – it can reside anywhere, but it should be added to the files ~/.bash_profile or ~/.bashrc, this file contains shortcuts, it’s not necessary, but I like it because it make my life easier;
- docker-compose.yml – it contains all the mappings and relevant containers.
NOTE: I think I should point out that the commands on the PHP container run in two ways, as the system user or as root. This is a limitation of the Linux implementation, please make a note of it, as I will refer to it later.
Step 1:
What you should do when starting a new project with an existing Magento2 repository:
1$ git clone https://github.com/claudiu-persoiu/magento2-docker-compose.git project_name 2$ cd project_name 3$ git clone your_own_magento2_repository magento2/html
Step 2 (optional):
Copy the shortcuts to your bash console:
1$ cp dkc_short ~/ 2$ echo ~/dkc_short >> ~/.bash_profile 3$ source ~/.bash_profile
NOTE: If you don’t have the file ~/.bash_profile on your computer, just use ~/.bashrc
Step 3:
Start the setup:
1$ dkc-up -d
It will take a bit of time the first time, but it will be a lot faster next time you run it.
Step 4:
Run composer install:
1$ dkc-php-run composer install
That’s about it.
What is this dkc stuff?
Well, I like to use tabs when running a command, so I added some aliases that allow me to run a Magento command without typing everything, I just type dkc[tab]p[tab]-[tab] and the command. I just love bash autocomplete.
The command list is very simple:
- dkc-up -d – start the containers in the background
- dkc-down – stop all containers
- dkc-mag [command] – run a Magento2 command
- dkc-clean – clear the cache
- dkc-php-run – run a bash command inside the php container, like composer in the previous example. NOTE: This command is running as the system user, not as root.
- dkc-exec phpfpm [command] – this is same as above, but running as root. You should almost always use the command above.
- dkc-exec [container] [command] – this command needs a bit more explanation:
- container can be:
- app – for Nginx server,
- phpfrm – for php container,
- db – for database,
- cache or fpc – for cache containers;
- container can be:
- the command can be anything that applies to that container, like “bash” or “bash composer”, etc.
I know the commands seem like “one more thing to learn”, but most of the time you will only use the first 4 commands.
How does the magic work?
Well, to see what the above commands translate to, just check the “dkc_short” file.
There are only 2 other interesting repositories:
- https://github.com/claudiu-persoiu/magento2-docker-php – that contains phpfpm,
- https://github.com/claudiu-persoiu/magento2-docker-nginx – that contain the nginx server.
The repositories are pretty small and not very hard to understand.
If you need to modify anything, just feel free to fork the repositories.
The conclusion
That’s about all you need to know about it, I’ve been using this setup for almost 2 years.
For me, it’s working as a charm and I was able to use Magento2 on ultraportable laptop with 8Gb RAM without any issues.
The (happy) end!
-
Over an year ago, I started working on the Magento platform. In last year’s spring, a colleague from Optaros took the Magento Developer Plus certification exam. Since then, I began to like the idea of taking the certification exam, more as a motivation to learn the ins and outs of Magento.
Few months ago I was enrolled into a company study group for the certification. This was the first time I was sponsored for a certification (yes, until now everything was with my money). Preparing in a study group was a whole different experience.
Those who have more experience in a field balance the situation for the others and can give better examples from their own experience. It’s easier to understand from concrete examples then to try to imagine the scenarios yourself.
The certification is available through Prometric. So when you decide that you’re ready you can go to the website to purchase the voucher and schedule the exam.
The price for a voucher is 260$, not exactly cheap, but if you get to convince your boss to pay, it probably won’t be so bad. 🙂
But let’s get to the more interesting subject, the preparation.
Materials
Magento is not doing very good on this subject, there are very few materials and they are not centralized.My sources were:
– Magento® Certified Developer Plus Exam Study Guide – it is compulsive to read the guide and try to find answers to all the questions in it;
– Magento training – especially Fundamentals of Magento Development
– blogs – I don’t want to give any names, there are a lot of people that write about the problems that they encounter and blog about the exam.Unfortunately there isn’t a way like for PHP, ZF and Symfony where you can find all you need in one place, basically it depends on your luck and searching skills, there isn’t an “official version”. Things become weird when you find different approaches that are version specific.
How did I prepare
I began with the video training. It’s not perfect by it’s very helpful. I think the problem with most certifications is that you don’t get to work with all the available modules, just like in PHP you don’t get to work that much with sockets and streams.Even though you don’t get the code and sometimes it is hard to follow and transcribe the examples, I think that the video tutorials are one of the most important sources at the moment.
Secondly, with the Study Guide in my hand, I began to try to answer the questions from it. When I joined the Study Group, the work divided between all the members in the group. My advantage was that it was the second generation of the group and we could profit from the documentation already developed by the first group.
If you’re preparing by yourself, I think the most important thing is to start, that’s the hardest part. And if you don’t know where to start, Google search the Magento questions, there are already a lot of people that are posting the explanations.
Answers for the questions from the first chapters are the easiest to find. As the number of the chapter is getting bigger, the number of Google results decreases.
But after the first questions, you should understand what is all about and in theory you will no longer need the documentation.
Use Mage::log(Varien_Debug::backtrace(true, false)); for stack trace and xdebug (http://xdebug.org/) to see what’s going on behind the scene. With patience, all the questions find their answers.
Because it was a group, the study was easier for me, but even so, to be sure of the explanation I has to dive deep in the code.
The exam
Some of the questions are difficult, but there are also accessible ones. The questions in the exam are off all levels of difficulty.For Plus, the exam takes 2h not 2.5h as it is specified in the guide.
If you opted for Plus, there are 11 questions from Enterprise and advanced difficulty questions, of which 7 correct ones are required to pass. Basically this is the difficulty difference. For this questions it matters how much Enterprise experience you have.
In the guide for each exam, the questions are broken in percentages for each chapter.
Because in the non Plus certification there are no Enterprise questions, you only have to answer the necessary percentage from the full exam in order to pass and it’s not required to have a certain percentage from a certain chapter.
Things that are done regularly are analyzed in detail, it is important to understand how each function that is approached in each chapter works and what is the purpose of all those tags in the xml files.
Usually there are things you work with, or at least with which there is a good probability you have been working from the modules listed in the guide.
Post exam
Before you leave the room you’ll know if you’ve passed or not. When you exit the room you’ll receive a printed paper with the correct number of questions from each section from the total number .In case you haven’t been successful you’ll receive by mail from Magento a voucher with a discount for a future attempt. They state that you should study at least 3 more weeks before you try again. Anyway, after you’ve taken the exam you’ll have a better view over your overall knowledge for a future attempt.
After few days (3 in my case) you will be able to see your profile on the Magento website as a reference.
The diploma got to Romania in about a month, the delivery address is the one from the Magento website account.
Best of luck!
-
Sometimes we need to overwrite an observer. The first way that usually comes in mind is overwriting the model. Usually is named Observer.php, because this is the “best practice”.
And NO, you don’t have to overwrite the model. Observer.php doesn’t extend anything anyway and usually contains all of the module’s observers, so you can’t overwrite the same observer in more than one module.
How it works?
In magento when a new observer is added, it must have an unique identifier. This identifier is the key!Actually, there is another element: “area”. When Mage::dispatchEvent(…) is performed, events will be dispatched using “area” and “identifier”.
For example, the admin notification system, which is observing “controller_action_predispatch”, will run:
1=> "global"(area) 2=> "controller_action_predispatch"(event) 3=> "adminnotification"(identifier)
then:
1=> "adminhtml"(area) 2=> "controller_action_predispatch"(event) 3=> "adminnotification"(identifier)
If the event was in the frontend area, it would be: “global” then “frontend”.
Overwriting
Overwriting is in fact a observer defined in the same config area as the original event (global, frontend or adminhtml), attached to the same event and with the same identifier as the original observer (e.g. adminnotification).Let’s say we have to overwrite “adminnotification”. This observer is in Mage/AdminNotification. The unique identifier is defined in etc/config.xml:
1... 2 <adminhtml> 3... 4 <events> 5 <controller_action_predispatch> 6 <observers> 7 <adminnotification> 8 <class>adminnotification/observer</class> 9 <method>preDispatch</method> 10 </adminnotification> 11 </observers> 12 </controller_action_predispatch> 13 </events> 14... 15 </adminhtml> 16...
From the example above we can see:
– area: adminhtml
– event: controller_action_predispatch
– identifier: adminnotificationThe module activation file will be: app/etc/modules/CP_AdminNotification.xml
1<?xml version="1.0"?> 2<config> 3 <modules> 4 <CP_AdminNotification> 5 <active>true</active> 6 <codePool>local</codePool> 7 <depends> 8 <Mage_AdminNotification/> 9 </depends> 10 </CP_AdminNotification> 11 </modules> 12</config>
I’ve added dependencies because without the original module, this module will be useless.
There’s a “best practice” to name a module that is overwritten with the same name as the original module.
The configuration file for this module, will contain practically everything you’ll need for the overwriting: area, event and identifier. The file is located in app/code/local/CP/AdminNotification/etc/config.xml:
1<?xml version="1.0"?> 2<config> 3 <modules> 4 <CP_AdminNotification> 5 <version>0.0.1</version> 6 </CP_AdminNotification> 7 </modules> 8 <global> 9 <models> 10 <cp_adminnotification> 11 <class>CP_AdminNotification_Model</class> 12 </cp_adminnotification> 13 </models> 14 </global> 15 <adminhtml> 16 <events> 17 <controller_action_predispatch> 18 <observers> 19 <adminnotification> 20 <class>cp_adminnotification/observer</class> 21 <method>overwrittenPreDispatch</method> 22 </adminnotification> 23 </observers> 24 </controller_action_predispatch> 25 </events> 26 </adminhtml> 27</config>
The observer should contain all the new logic. The file is in app/code/local/CP/AdminNotification/Model/Observer.php, just like you would probably expect from the structure above.
1<?php 2 3class CP_AdminNotification_Model_Observer { 4 5 public function overwrittenPreDispatch(Varien_Event_Observer $observer) { 6 // noua logica din observer 7 } 8}
Disabling
Disabling is preaty similar to overwriting, the difference is in the config and the fact that an observer file is not needed anymore, because there isn’t a new logic.The new config.xml file is:
1<?xml version="1.0"?> 2<config> 3... 4 <adminhtml> 5 <events> 6 <controller_action_predispatch> 7 <observers> 8 <adminnotification> 9 <type>disabled</type> 10 </adminnotification> 11 </observers> 12 </controller_action_predispatch> 13 </events> 14 </adminhtml> 15</config>
-
This is not a tutorial about setting up a Shopping Cart Price Rule in Magento, but rather about implementing a new one.
A new type of rule in Magento needs a couple of things:
– modify the admin area to add the new rule using an observer for adminhtml_block_salesrule_actions_prepareform,
– a way to apply the new rule using an observer for salesrule_validator_process.Let’s build an example. Let’s say there is a Shopping Cart Price Rule that offers different discounts according to the number of products in the cart. The value that’s going to be used for the discount increment ($step) will be calculated. The first product will not receive a discount, the second product will receive a discount of $step, the third product will have a discount of 2*$step, until the maximum discount value will be reached. The following products will have a maximum discount. Ex:
Discount Amount = 50
Discount Qty = 5
Step = Discount Amount / Discount Qty = 10Discount outcome:
– 0% prod 1
– 10% prod 2
…
– 50% prod 6
– 50% prod 7The first step is the module activation using the file: app/etc/modules/CP_ProductNrDiscount.xml
1<?xml version="1.0" encoding="UTF-8"?> 2<config> 3 <modules> 4 <CP_ProductNrDiscount> 5 <active>true</active> 6 <codePool>local</codePool> 7 </CP_ProductNrDiscount> 8 </modules> 9</config>
The first observer, adminhtml_block_salesrule_actions_prepareform, must be in the “adminhtml” section of the config, because it will involve the admin. This observer will have access to the admin form, in order to modify it.
The second observer, salesrule_validator_process, can be in the “frontend” or “global” section of the config. If it’s in the frontend section, it will only apply to the frontend section. If it’s in the global section it will also apply to backend. Usually, global is necessary when there are actions on the cart in the backend.
1<?xml version="1.0" encoding="UTF-8"?> 2<config> 3 <modules> 4 <CP_ProductNrDiscount> 5 <version>0.0.1</version> 6 </CP_ProductNrDiscount> 7 </modules> 8 <global> 9 <models> 10 <productnrdiscount> 11 <class>CP_ProductNrDiscount_Model</class> 12 </productnrdiscount> 13 </models> 14 <events> 15 <salesrule_validator_process> 16 <observers> 17 <productnrdiscount> 18 <type>model</type> 19 <class>productnrdiscount/observer</class> 20 <method>salesruleValidatorProcess</method> 21 </productnrdiscount> 22 </observers> 23 </salesrule_validator_process> 24 </events> 25 </global> 26 <adminhtml> 27 <events> 28 <adminhtml_block_salesrule_actions_prepareform> 29 <observers> 30 <productnrdiscount> 31 <type>model</type> 32 <class>productnrdiscount/observer</class> 33 <method>adminhtmlBlockSalesruleActionsPrepareform</method> 34 </productnrdiscount> 35 </observers> 36 </adminhtml_block_salesrule_actions_prepareform> 37 </events> 38 </adminhtml> 39</config>
As you can see above, there must be an Observer model that will have the two methods which modify the admin and apply the discount.
1<?php 2/** 3 * Number of product discount module 4 * 5 * @author Claudiu Persoiu https://blog.claudiupersoiu.ro 6 */ 7class CP_ProductNrDiscount_Model_Observer { 8 9 // The new rule type 10 const PRODUCT_NR_DISCOUNT = 'product_nr_discount'; 11 12 /** 13 * Add the new rule type to the admin menu 14 * 15 * @param Varien_Event_Observer $observer 16 */ 17 public function adminhtmlBlockSalesruleActionsPrepareform 18 (Varien_Event_Observer $observer) { 19 // Extract the form field 20 $field = $observer->getForm()->getElement('simple_action'); 21 // Extract the field values 22 $options = $field->getValues(); 23 // Add the new value 24 $options[] = array( 25 'value' => self::PRODUCT_NR_DISCOUNT, 26 'label' => 'Product Number Discount' 27 ); 28 // Set the field 29 $field->setValues($options); 30 } 31 32 /** 33 * Apply the discount 34 * The discount will be applied for at least 2 products increasing 35 * with a "step" for each product, where "step" is 36 * maximum discount / number of products. 37 * 38 * @param Varien_Event_Observer $observer 39 */ 40 public function salesruleValidatorProcess(Varien_Event_Observer $observer) { 41 42 // $item typeof Mage_Sales_Model_Quote_Item 43 $item = $observer->getEvent()->getItem(); 44 // $rule typeof Mage_SalesRule_Model_Rule 45 $rule = $observer->getEvent()->getRule(); 46 47 // Number of products 48 $qty = $item->getQty(); 49 50 // We must check the rule type in order to isolate our rule type 51 if($rule->getSimpleAction() == self::PRODUCT_NR_DISCOUNT && $qty > 1) { 52 53 // Extract rule details 54 $discountAmount = $rule->getDiscountAmount(); 55 $discountQty = $rule->getDiscountQty(); 56 57 // Discount step 58 $step = $discountAmount/$discountQty; 59 60 // Discount calculation 61 $discount = 0; 62 for($i = 1; $i < $qty; $i++) { 63 $itemDiscount = $i * $step; 64 // If the discount is bigger then the maximum discount 65 // then the maximum discount is used 66 if($itemDiscount > $discountAmount) { 67 $itemDiscount = $discountAmount; 68 } 69 70 $discount += $itemDiscount; 71 } 72 // Effective discount 73 $totalDiscountAmount = ($item->getPrice() * $discount)/100; 74 75 // Discount in percent for each item 76 $item->setDiscountPercent($discount / $qty); 77 78 // Setting up the effective discount, basically this is the discount value 79 $result = $observer->getResult(); 80 $result->setDiscountAmount($totalDiscountAmount); 81 $result->setBaseDiscountAmount($totalDiscountAmount); 82 83 } 84 } 85 86}
This observer will run at each request if there are items in cart that for which the rule is applicable. If the discount should be applied only for specific products, there can be filtered using the rule’s “Conditions” tab, just as you would normally do.