We use cookies to make your experience better. To comply with the new e-Privacy directive, we need to ask for your consent to set the cookies. Learn more.
What is $context variable in Shopware 6?
The variable $context is all over Shopware 6 – it's everywhere. The $context variable will be present whether you wish to create a product, list customers, or place an order! But why is that? Simple. Shopware will operate differently and conduct certain operations depending on the given context (source, laws, language, currency, etc.). Uh, vague. Let me give you a few examples.
Example: Product language and currency
Entities in Shopware 6 (such as goods, category, CMS sites, etcetera) can have data that shares different languages and currencies. Please keep in mind that even statistics in the same language (in our instance, English) may change from nation to nation. Let's look at an example of a product:
Sales Channel | Name | Price | Description |
Racket Match (German DE) | Fußball | €84.71 | Das ist ein Fußball. |
Racket Match (English US) | Soccer ball | $99.99 | This is a soccer ball. |
Racket Match (English UK) | Football ball | £72.59 | This is a football. |
Racket Match (Spanish ES) | Pelota de fútbol | 77.12 € | Esta es una pelota de fútbol. |
Racket Match (Italian IT) | Pallone da calcio | 39.44 € | Questo è un pallone da calcio. |
Furthermore, please keep in mind that currencies will be shown differently in different nations:
Symbols are $, €, £, ¥
In different countries symbols can be displayed before or after the price
- In US Dollar (before): $9.99
- In Euro (depends on the locale)=€9.99 (before), 9.99 € (after)
Separators for thousands and decimals are formatted differently:
- US Dollar: 100,000.00
- Euro: 100.000,00 (There are even more differences across countries.)
These are only a few reasons why $context is required. Shopware needs to know what source, laws, language, currency (... and other information) you're referring to when displaying, generating, changing, and deleting data, for example.
As a result, $context is generally asked everywhere in the code. It could be readily set up worldwide, but from an architecture standpoint, that would be a horrible idea because any code would be closely attached to the Shopware application. Furthermore, this would result in one of many errors, making debugging and correcting them extremely difficult.
Let’s check the code:
I hope you've realized how important $context is at this point.
Anyway, The good news is that $context will only be created once, at the start of every request. Either through the New Store or through the API. The $context variable will be passed from class to class automatically throughout the system, and it will be available for the majority of the time. As a result, you won't have to worry about learning new languages or currencies on your own, or about getting prices to display correctly across the system. All of this will be handled by Shopware.
In my HelloWorldController controller, I'm using $context (Shopware\Core\Framework\Context)
<?php declare(strict_types=1); namespace MageSpark\HelloWorld\Controller; use Shopware\Core\Framework\Context; use Shopware\Core\Framework\Routing\Annotation\RouteScope; use Shopware\Storefront\Controller\StorefrontController; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Annotation\Route; /** * @RouteScope(scopes={"storefront"}) */ class PrintContextController extends StorefrontController { /** * @RouteScope(scopes={"storefront"}) * @Route("/print-context", name="frontend.print.context", methods={"GET"}) * @param Context $context * @param Request $request * @return void */ public function showContext(Context $context, Request $request){ echo "Currency ID: ". $context->getCurrencyId(). "<br/>"; echo "Language ID: ".$context->getLanguageId(). "<br/>"; exit(); } }
The browser output is as follows:
As previously stated, the $context variable will be present in every controller and event subscriber, allowing you to send it to services. However, there will be times when $context is unavailable. That will be addressed in the next section.
Context::createDefaultContext() should be used carefully:
$context will not be available in some areas, such as command lines, cron tasks, and testing. Yes, you could use Context::createDefaultContext() in those cases. This method will generate a default context for you, utilizing the default language and currency(among other things).
What is the matter with repeatedly calling Context::createDefaultContext()? Simple. It DOES NOT CONTAIN IMPORTANT CONNECTION VARIABLES. This has the potential to inflict damage on everything.
It is essential to note that the first option (in most cases) should be Shopware's default $context. When you create a $context instance on your own, you run the risk of forgetting to set important variables or setting them incorrectly.
That would result in *significant* inconsistencies. Different contexts necessitate different operations. Forgetting to set up rules in $context is a great example of this.
Admin users can create dynamic rules in Shopware using the admin Rule Builder. These rules can have a significant impact on how things interact with one another. Assume that admin users make the following rule: 90 percent off for customers from a specific country (Switzerland) during a specific holiday (The Swiss National Day 2022-08-01). This massive discount will not be applied when placing an order.
Please do not misuse Context:: createDefaultContext() method. use in moderation. If you use it oftenly, there is a good chance you are using it incorrectly.
When you require a different context... not the default one.
That's fine; no worries. You may select any other context. You can create the object and pass whatever parameters you want.
$germanContext = new Context( new SystemSource(), [], 'b7d2554b0ce847cd82f3ac9bd1c0dfca', ['2b6036f22dea4e5b931d449305a8d519'], ); $this->productRepository->update( [ /* update product listing German data */ ], $germanContext );
Of course, other parameters can be passed when you're creating $context, but for the purpose of easiness, we only carried these few. Please see Shopware/Core/Framework/Context on the __construct method for the other parameters.
What's the deal with $salesChannelContext?
$salesChannelContext is similar to $context, but it contains more variables related to the sales context. Look at Shopware\Core\System\SalesChannel\SalesChannelContext. for more information.
I hope this post has shed some light on why the $context variable appears in so many places in Shopware 6. Thank you very much!
Starting Your Own Shopware Store?
Get a free consultation from Shopware experts
on do's and don't