How I can call magento 2 commands inside magento 2? I just want to call a command in the UpgradeData.php.
- 5,209
- 13
- 62
- 103
- 131
- 5
-
Does the function have parameters? – André Ferraz Jan 26 '17 at 16:57
-
yes, could have parameters – Jordi Jan 26 '17 at 17:22
-
Its not hard to do. You just need to make sure the Magento code base has been instantiated. You can create a new magenta terminal command which runs functions of a namespace class. I've done this before. – André Ferraz Jan 26 '17 at 19:52
-
If you can refer me to any post showing this matter or a good example would be appreciated. I know how it can be done in Symfony but not in Magento2 (http://symfony.com/doc/current/console/command_in_controller.html) – Jordi Jan 27 '17 at 08:55
1 Answers
Has I said on the comments you can create a new console command. Here is how to create a new magento console command, this will be your starting point Magento 2 How to Create a Custom Console Command. This shouldn't be hard for you because Magento commands are based on Symphony.
You will obviously have to change the functionality of the execute command to instantiate namespace classes and also add options to the class. This can be done with Magentos object manager and with PHP's ReflectionMethod to allow params to be called.
You need to add new options to the command.
use \Symfony\Component\Console\Input\InputOption;
Add this to the
configure()method.$options = [ new InputOption( "namespace", null, InputOption::VALUE_REQUIRED, 'Namespace of class to be debugged' ), new InputOption( "method", null, InputOption::VALUE_REQUIRED, 'Method to run' ) ]; $this->setDefinition($options);Then Instantiate the name space with Magento's object manager.
// First get the options entered $options = $input->getOptions(); $namespace = $options["namespace"]; $method = $options["method"]; if(empty(trim($namespace)) || empty(trim($method))) { throw new \Exception("Your must specify a class namespace and a method"); } $objectManager = \Magento\Framework\App\ObjectManager::getInstance()->create($namespace); $objectManager->$method();
That's really all you need to run classes and methods (without params). If you want to add support for params have a look at ReflectionMethod.
- 3,483
- 6
- 20
- 40