How to run custom code in Shopware 6 from external file / script?

Icon NetzkollektivBy Dominik Krebs, Managing Director, CTO

Sometimes you need to run Shopware 6 code externally. While developing or debugging a system this happens quite a lot. There are several cases when you could be in need of that:

  • your customer sends you a stacktrace an and you need to quickly reproduce the error
  • you want to test the behavior of a third-party plugin in a very special case
  • you want to get data out of the system without accessing the database directly
  • you need a quick integration with other frameworks or platforms installed on the same web server
  • you want to do a quick test execution of a method, a class instantation, a cron job or a scheduled task

The Single PHP File Solution

In older PHP systems, like Magento 1, or even Magento 2 it was possible to just create a test.php file, spin up the system, get the class you need and run it. The result may be either an error or just the total sum of a specific order.

For Shopware 6, or Symonfy in general, this does not work as the container does not expose the classes to the public. The classes need to be injected in another class in order to use them. What generally makes sense in terms of modern programming, in this case it just makes things complicated and tedious.

The public = true solution

One solution to the problem would be to make the service publicly available and then call in like in the single PHP example. This may work perfectly in a system you control, but not in a one where you just simply want to debug something and cause no harm to the system.

Call custom code with a Symfony Command

The simple solution to the problem, yet a bit more work than in the old days, is to create a Symfony Command, inject the services and run it from the console.

To make it easy, we already did this for you – just get our debug command extension from Github, adapt it to your needs and run it:

./bin/console debug:test-command

That’s it, now you can test whatever you like! 🙂

Uncategorized Agentur gesucht?

Sie sind auf der Suche nach einer zuverlässigen Agentur, die sich mit Uncategorized auskennt und Ihnen unkompliziert durch den Online-Shop Alltag hilft? NETZKOLLEKTIV betreut Händler seit über 10 Jahren. Rufen Sie uns an!

Jetzt unverbindlich über mein Projekt sprechen