In this blog post, you’ll learn how to create a custom storefront controller in Shopware 6.
Prerequisites
First, you need to create your own custom plugin as a base. Therefore, you can follow this plugin base tutorial.
In your plugin directory, custom/plugins/( YOUR_PLUGIN ) create the file routes.xml in this path: src/Resources/config/routes.xml and add the following code.
<?xml version="1.0" encoding="UTF-8" ?>
<routes xmlns="http://symfony.com/schema/routing"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/routing
https://symfony.com/schema/routing/routing-1.0.xsd">
<import resource="../../Storefront/Controller/**/*Controller.php" type="annotation" />
</routes>
Now let’s inject the container into the controller. Create the file services.xml in this pate: src/Resources/config/services.xml and add the following code.
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
<services>
<service id="SwagBasicExample\Storefront\Controller\ExampleController" public="true">
<call method="setContainer">
<argument type="service" id="service_container" />
</call>
</service>
</services>
</container>
Now we just need to create the controller file on the path: src/Storefront/Controller/ExampleController.php and add the following code.
<?php declare(strict_types=1);
namespace SwagBasicExample\Storefront\Controller;
use Shopware\Core\Framework\Routing\Annotation\RouteScope;
use Shopware\Core\Framework\Routing\Annotation\Since;
use Shopware\Storefront\Controller\StorefrontController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
/**
* @RouteScope(scopes={"storefront"})
*/
class ExampleController extends StorefrontController
{
/**
* @Route("/hello-world", name="frontend.helloworld", methods={"GET"})
*/
public function helloworld()
{
echo 'This is the first storefront controller which we just created!';
exit;
}
Now, we have a controller working in Shopware 6! Visit your site: example.com/hellow-world as you can see the output in the below screenshot.
Please contact us at manish@bay20.com or call us at +91-8800519180 for any support related to shopware. You can also visit the Shopware development page to check the services we offer.