1

I need to pull product data out of Magento 2 via an external PHP command line script.

I am using the example here: How can I bootstrap Magento 2 in a test.php script?

In the run method, I extract my product collection and parse my product data into a new array without any problem.

public function run()
{
   // create collection

   // parse collection

   // build $_products data array

    return ['data' => $_products];

}

If I dump or echo $_products out in run() I can see the product data ok, I need to return the product data to the calling function but cannot see how to retrieve the data. I am initiating my app with

$app = $bootstrap->createApplication('Getapp');
$bootstrap->run($app);

How can I access the data returned from Getapp and how can I pass variables into Getapp?

Utsav Gupta
  • 1,243
  • 1
  • 18
  • 48
paj
  • 5,785
  • 5
  • 21
  • 43

1 Answers1

1

To return data from run() using the command line external php script example here How can I bootstrap Magento 2 in a test.php script?

use $app->launch() instead of $bootstrap->run($app) set the response variable and return it

public function launch()
{
    $this->_response=$this->run();
    return($this->_response);
}

Access the data with

$mydata=$app->launch();

You can also save the data in a class variable in run()

 $this->_mydata=$data

And access it via $app

$mydata=$app->_mydata

To make variables available to run() add the variables in an array to the bootstrap construct

    $app = $this->__bootstrap->createApplication(
        'Magento',
        array(
            'variables' => array(
                'product_id' => '65')
            )
    );

Add this to the "AbstractApp"

abstract class AbstractApp implements AppInterface
{
    public function __construct(
        \Magento\Framework\ObjectManagerInterface $objectManager,
        Event\Manager $eventManager,
        AreaList $areaList,
        RequestHttp $request,
        ResponseHttp $response,
        ConfigLoaderInterface $configLoader,
        State $state,
        Filesystem $filesystem,
        \Magento\Framework\Registry $registry,
        array $variables = []
    ) {

        $this->_objectManager = $objectManager;
        $this->_eventManager = $eventManager;
        $this->_areaList = $areaList;
        $this->_request = $request;
        $this->_variables=$variables;
        $this->_response = $response;
        $this->_configLoader = $configLoader;
        $this->_state = $state;
        $this->_filesystem = $filesystem;
        $this->registry = $registry;
    }

Access the variable array in run()

$product_id=$this->_variables['product_id'];
paj
  • 5,785
  • 5
  • 21
  • 43