Как загрузить продукт или коллекцию заказов вне проекта в magento2
Мне нужно загрузить коллекцию товаров или заказов за пределами magento,
мне нужно поиграть с данными, поэтому мне нужно вызвать collection
в magento1.x мы используем
require_once '../app/Mage.php';
$products = Mage::getModel('catalog/product')->getCollection();
Как это сделать на Magneto2?
6 answers
Спасибо вам всем, я получил это
Я последовал в соответствии с сообщением Как я могу загрузить Magento 2 в test.php сценарий?
В корневой папке, которую я создал script/abstract.php
<?php
use \Magento\Framework\AppInterface as AppInterface;
use \Magento\Framework\App\Http as Http;
use Magento\Framework\ObjectManager\ConfigLoaderInterface;
use Magento\Framework\App\Request\Http as RequestHttp;
use Magento\Framework\App\Response\Http as ResponseHttp;
use Magento\Framework\Event;
use Magento\Framework\Filesystem;
use Magento\Framework\App\AreaList as AreaList;
use Magento\Framework\App\State as State;
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
) {
$this->_objectManager = $objectManager;
$this->_eventManager = $eventManager;
$this->_areaList = $areaList;
$this->_request = $request;
$this->_response = $response;
$this->_configLoader = $configLoader;
$this->_state = $state;
$this->_filesystem = $filesystem;
$this->registry = $registry;
}
public function launch()
{
$this->run();
return $this->_response;
}
abstract public function run();
public function catchException(\Magento\Framework\App\Bootstrap $bootstrap, \Exception $exception)
{
return false;
}
}
А затем script/index.php
<?php
require dirname(__FILE__) . '/../app/bootstrap.php';
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
require dirname(__FILE__) . '/abstract.php';
class Getapp extends AbstractApp
{
public function run()
{
$this->_objectManager->get('Magento\Framework\Registry')
->register('isSecureArea', true);
$datas = $this->_objectManager->create('\Magento\Sales\Model\ResourceModel\Order\Collection');
// $products = $this->_objectManager->create('\Sugarcode\Test\Model\Test'); // custom Module
//$products = $this->_objectManager->create('\Magento\Catalog\Model\Product');
// $products = $products->getCollection();
foreach($datas as $data){
echo $data->getIncrementId().'<br>';
}
}
}
/** @var \Magento\Framework\App\Http $app */
$app = $bootstrap->createApplication('Getapp');
$bootstrap->run($app);
Итак, в index.php напишите свою логику и url/script/index.php
Все работает нормально
Вы можете создать свой собственный файл, который создает экземпляр приложения, как описано здесь:
https://magento.stackexchange.com/a/40848/146
И в этом файле вы можете попробовать следующее:
$collection = $this->_objectManager->create('\Magento\Catalog\Model\ResourceModel\Product\Collection');
$collection->addFieldToFilter(....)
Это неподдерживаемый сценарий.
Я рекомендую использовать официальные API для Magento 2: http://devdocs.magento.com/guides/v2.0/get-started/bk-get-started-api.html
В magento вы можете делать грязные способы:
Итак, проверьте этот вопрос Как я могу загрузить Magento 2 в test.php сценарий?
В magento коллекция продуктов генерируется из Magento\Каталог\Модель\Ресурс\Продукт\Коллекционная фабрика
Для вашего требования вам необходимо изменить класс TestApp
<?php
class TestApp
extends \Magento\Framework\App\Http
implements \Magento\Framework\AppInterface {
public function launch()
{
//dirty code goes here.
//the example below just prints a class name
echo get_class($this->_objectManager->create('\Magento\Catalog\Model\Resource\Product\CollectionFactory'));
$collection=$this->_objectManager->create('\Magento\Catalog\Model\Resource\Product\CollectionFactory');
// addtional:
$collection
->addMinimalPrice()
->addFinalPrice()
->addTaxPercents()
>addAttributeToSelect('*')
->addUrlRewrite() ;
//the method must end with this line
return $this->_response;
}
public function catchException(\Magento\Framework\App\Bootstrap $bootstrap, \Exception $exception)
{
return false;
}
}
Настройка Magento - это пример полностью отдельного приложения (Zend MVC) в ядре Magento, которое имеет доступ к менеджеру объектов Magento. Хорошей отправной точкой для рассмотрения является <magento_project_root>/setup/index.php
(наиболее важной частью здесь является использование начальной загрузки Magento).
Что сработало для меня, так это ответ отсюда, ответ на вопрос о том, как получить товары в корзине. В процессе необходимо загрузить magento, так что две птицы, один камень.
Https://magento.stackexchange.com/a/115127/24870
<?php
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/../app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$obj = $bootstrap->getObjectManager();
// Set the state (not sure if this is neccessary)
$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
// Get whatever object
// example
$quote = $obj->get('Magento\Checkout\Model\Session')->getQuote();