non Magento PHP classes can't be instantiated inside Magento 2 Helper or or Controller or Models

magento.stackexchange https://magento.stackexchange.com/questions/121883

  •  30-09-2020
  •  | 
  •  

Pregunta

Questions

  • What is the BEST way to instantiate such 3rd party non Magento classes in Magento 2?
  • What is the BEST way to connect to MS SQL server to run a query? I am using PDO.

Issues

I am not able to instantiate any core PHP classes or custom classes inside the helper / module files of Magento 2. I have tried the following but nothing worked.

$connection = new PDO('dblib:host='.$host.';dbname='.$dbname.';charset=utf8', $username, $password);

I had also tried to do the same for PHPExcel code as well, I had kept PHPExcel code inside lib folder and tried to use it

require_once BP.'/lib/internal/PHPExcel/PHPExcel/IOFactory.php';
PHPExcel_IOFactory::createReader($inputFileType);

None of the above worked and Magento is always trying to look for these classes under its name spaces and auto loading process.

Error Details

Fatal error: Uncaught Error: Class 'Datamart\M3Connector\Helper\PDO' not found in web/app/code/Datamart/M3Connector/Helper/M3MsSqlDb.php:19 Stack trace: #0 web/app/code/Datamart/CustomerOrders/Controller/UploadOrder/Index.php(30): Datamart\M3Connector\Helper\M3MsSqlDb->getConnection() #1 web/var/generation/Datamart/CustomerOrders/Controller/UploadOrder/Index/Interceptor.php(24): Datamart\CustomerOrders\Controller\UploadOrder\Index->execute() #2 web/vendor/magento/framework/App/Action/Action.php(102): Datamart\CustomerOrders\Controller\UploadOrder\Index\Interceptor->execute() #3 [internal function]: Magento\Framework\App\Action\Action->dispatch(Object(Magento\Framework\App\Request\Http)) #4 web/vendor/magento/framework/Interception/ in web/app/code/Datamart/M3Connector/Helper/M3MsSqlDb.php on line 19

¿Fue útil?

Solución

Magento 2 uses namespaces, which means you have to as well. Rather than new PDO(...), you would have to specify new \PDO(...). The backslash says 'look for this class in the root namespace, rather than the current namespace context'. Think of it like folders and absolute vs. relative paths.

As for the best way to connect to an MsSQL database, Magento's database layer is built on Zend_Db_Adapter. Magento only uses it for MySQL, but it supports MsSQL as well (if your server has the right plugins). See here for basic instructions on how to use it: http://framework.zend.com/manual/1.12/en/zend.db.adapter.html

You could instantiate \Zend_Db_Adapter_Pdo_Mssql to get an MsSQL DB connection.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a magento.stackexchange
scroll top