Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 42 ยท Practice and Review

Practice Exercises with Solutions

Five hands-on Magento exercises on dependency injection, plugins, events, collections and layouts, each with a task, hints and a runnable plain-PHP stand-in solution.

Reading about Magento is one thing; building with it is how the ideas stick. This lesson gives you five exercises, one for each big idea in the track: dependency injection, plugins, events, collections and layouts. Each has a task, the real Magento files you would write (read-only), and a runnable stand-in solution in plain PHP.

Magento itself cannot run on this site, so the stand-ins are small imitations written for learning. They follow the same shape as the real thing but are not Magento code. Try each exercise on paper or in your own editor before you open the solution. Struggling for ten minutes teaches more than reading the answer.

flowchart LR
    E1["1. DI<br/>preference"] --> E2["2. Plugins<br/>ordering"]
    E2 --> E3["3. Events<br/>transport object"]
    E3 --> E4["4. Collections<br/>filters and paging"]
    E4 --> E5["5. Layout<br/>move and remove"]

Five exercises, from wiring objects to shaping a page.

Exercise 1: swap an implementation with a preference

Task. A module depends on MailerInterface. In production the implementation sends real email; in development you want one that only writes to a log. Without changing the class that uses the mailer, make the container pick the log version, and make sure the log version receives its own logger through the constructor.

In real Magento this is a preference in di.xml. You would write (read-only):

XML
<preference for="Acme\Notice\Api\MailerInterface"
            type="Acme\Notice\Model\LogMailer"/>

Hints. The container reads constructor type hints with reflection. A preference maps an interface name to a class name. Dependencies are built first.

Solution. The stand-in container resolves interfaces through a preference table, then builds constructor arguments recursively. Real Magento's object manager also caches definitions and honors shared settings; this keeps only the core idea.

PHP Exercise 1: a container with preferences

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

WelcomeService was never edited, yet it behaves differently per container: that is the payoff of coding against an interface. If your answer put new LogMailer() inside WelcomeService, revisit The Object Manager and Constructor Injection.

Exercise 2: plugin order

Task. A PriceFormatter::format(float $amount) method returns something like $10.00. Write two plugins: one before plugin that rounds the amount to whole units (sort order 10), and one after plugin that appends " incl. tax" (sort order 20). Predict the output for 9.6, then run it. Add a second after plugin with sort order 5 that wraps the result in brackets, and predict how the nesting changes.

In real Magento the declaration is:

XML
<type name="Acme\Shop\Model\PriceFormatter">
    <plugin name="acme_round" type="Acme\Shop\Plugin\RoundAmount" sortOrder="10"/>
    <plugin name="acme_tax_label" type="Acme\Shop\Plugin\TaxLabel" sortOrder="20"/>
</type>

with methods named beforeFormat() and afterFormat() on the plugin classes.

Hints. A before plugin returns the (possibly changed) arguments as an array. An after plugin receives the result and returns the new result. In Magento's documented model, plugins with a lower sort order wrap the ones with a higher number, so the lower one sees the final result last. Confirm the exact order in your own version by logging from each plugin.

Solution. The stand-in builds a chain: for each plugin from the lowest sort order, run its before step, then call the rest of the chain, then run its after step. This is the nesting idea, not the real generated interceptor code.

PHP Exercise 2: before and after plugins with sort order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

In the second run Brackets wraps everything, so its after step sees the finished string and runs last. If your prediction was off, trace the nesting by hand: the first plugin in the list starts first and finishes last. Plugin Best Practices and Pitfalls goes deeper into ordering.

Exercise 3: let observers adjust data with a transport object

Task. A shipping class computes a delivery price and dispatches an event acme_shipping_price_calculate before returning it. Observers must be able to change the price, but an observer's return value is ignored. How do you let them influence the result? Implement a free-shipping observer for subtotals of 100 and above.

Hints. Observers cannot return data (see Events and Observers). Core Magento often passes a mutable DataObject (commonly named transport) in the event data. The dispatching code creates it, the observers modify it, and the dispatcher reads it afterwards.

In real Magento you would dispatch with ['transport' => $transport] where $transport = new \Magento\Framework\DataObject(['price' => $price]) and read $transport->getPrice() afterwards. The observer calls $observer->getEvent()->getData('transport')->setPrice(0.0).

Solution.

PHP Exercise 3: a transport object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Because objects are passed by handle, the observer's change is visible to the dispatcher. Several observers can adjust the same transport, which is why you should not rely on their order. A plugin on price() would also work, but the event leaves the extension point open to every module.

Exercise 4: filter, sort and page a collection

Task. Given a product list, return page 2 (page size 2) of the products whose name contains "mug" or whose price is above 40, sorted by price descending, and also report the total size. Use the Magento vocabulary: addFieldToFilter, setOrder, setPageSize, setCurPage, getSize.

In real Magento a product collection has these methods. Conditions use arrays such as ['like' => '%mug%'] or ['gt' => 40]. Putting two conditions on one call as an array of arrays means OR, as covered in Collections, Filters and SearchCriteria. The real call chain would look like this (read-only):

PHP
$collection->addFieldToFilter(
    ['name', 'price'],
    [['like' => '%mug%'], ['gt' => 40]]
);
$collection->setOrder('price', 'DESC')->setPageSize(2)->setCurPage(2);

Hints. getSize() counts all matching rows ignoring paging; count() counts what is loaded for the current page. Separate calls to addFieldToFilter combine with AND; the array form inside one call combines with OR.

Solution.

PHP Exercise 4: a filterable collection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Five products match (three mugs, the lamp and the chair), sorted by price: chair, gift set, lamp, travel mug, blue mug. Page 2 therefore holds the lamp and the travel mug. If you added a second addFieldToFilter('price', ['lt' => 100]) call it would be ANDed with the group.

Exercise 5: change a page with layout instructions

Task. A page layout has a header container with logo and search blocks and a sidebar container with newsletter. Using layout-style instructions, (a) remove the newsletter block, (b) move search into the sidebar placed first, and (c) change the logo block's template argument.

In real Magento this is layout XML in your module or theme (read-only):

XML
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="newsletter" remove="true"/>
        <move element="search" destination="sidebar" before="-"/>
        <referenceBlock name="logo">
            <arguments>
                <argument name="template" xsi:type="string">Acme_Theme::logo-small.phtml</argument>
            </arguments>
        </referenceBlock>
    </body>
</page>

Hints. Instructions are applied to the already merged tree. remove hides an element for good, move changes its parent and position, and referenceBlock modifies a block someone else declared.

Solution.

PHP Exercise 5: move, remove and reference

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The final tree has logo alone in the header and search before categories in the sidebar. Real layout merging also handles handles, ordering with before and after names, and multiple files, which you met in Layout XML and Handles.

Bonus questions (answer in your head)

  1. Why does a plugin on a final class or a private method not work?
  2. You need to react after an order is placed, but you must not slow checkout. Which two features from the Order Events project combine to solve that?
  3. A product attribute value shows in the admin but not in category tiles. Which attribute flag is the first thing to check? (See the product badge project.)
  4. What is the difference between getSize() and count() on a collection?

Answers: plugins are built from generated interceptor subclasses, so only public, non-final, non-static methods of non-final classes can be intercepted; an observer plus a queue message; whether the attribute is flagged for product listings; getSize() counts all matches ignoring paging, count() counts the loaded page.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In the container exercise, why did WelcomeService not need any change?

    Constructor injection against an interface lets configuration decide the implementation.
  2. 2. How can observers influence a value if their return value is ignored?

    The dispatcher creates a DataObject, passes it in the event, and reads it back after dispatching.
  3. 3. What does addFieldToFilter(['name', 'price'], [['like' => '%mug%'], ['gt' => 40]]) express?

    Arrays of fields and conditions inside one call are joined with OR; separate calls are joined with AND.
  4. 4. Which layout instruction changes a block declared by another module without redeclaring it?

    referenceBlock targets an existing block by name so you can remove it, change its arguments or add children.
  5. 5. A collection has 5 matching rows and page size 2. What do getSize() and count() return on page 3?

    getSize() ignores paging and returns 5; page 3 holds the single remaining row, so count() is 1.

Summary

  • Preferences and constructor injection let configuration pick implementations without touching consumers.
  • Before plugins adjust arguments, after plugins adjust results, and sort order decides the nesting; always verify ordering in your own version.
  • Observers cannot return data: pass a mutable transport object when they must adjust a value.
  • Collection filters in one call are OR, separate calls are AND, and getSize() ignores paging.
  • Layout instructions (remove, move, referenceBlock) modify the merged tree without editing the original file.

Ready to test your recall? Continue with Magento Interview Questions.