Get Product Collection from Solr Engine

<?php

require 'app/Mage.php';
Varien_Profiler::enable();
Mage::setIsDeveloperMode(true);
ini_set('display_errors', 1);
umask(0);
Mage::app();

$category = Mage::getModel('catalog/category')
 ->load(34);
$collection = Mage::helper('catalogsearch')->getEngine()->getResultCollection()
    ->addCategoryFilter($category);
$collection->setGeneralDefaultQuery();
echo '<pre>';
 foreach ($collection as $key => $value) {

 print_r($value->getData());
 # code...
 }

Model and document file:
/app/code/core/Enterprise/Search/Model/Resource/Collection.php

Get Product Collection from Solr Engine

How to check Full Page Cache is working?

You need ope file and insert the log scripts:

/app/code/core/Mage/Core/Model/App.php

public function run($params)
    {

        $base_url = ( isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']=='on' ? 'https' : 'http' ) . '://' .  $_SERVER['HTTP_HOST'];
        $url = $base_url . $_SERVER["REQUEST_URI"];
        $options = isset($params['options']) ? $params['options'] : array();
        $this->baseInit($options);
        Mage::register('application_params', $params);

        if ($this->_cache->processRequest()) {

            file_put_contents('url_have_fpc.txt', date("H:i:s")." URL: $url \n",FILE_APPEND);
            $this->getResponse()->sendResponse();
            
        } else {
            file_put_contents('url_non_fpc.txt', date("H:i:s")." URL: $url \n",FILE_APPEND);
            
            $this->_initModules();
            $this->loadAreaPart(Mage_Core_Model_App_Area::AREA_GLOBAL, Mage_Core_Model_App_Area::PART_EVENTS);

            if ($this->_config->isLocalConfigLoaded()) {
                $scopeCode = isset($params['scope_code']) ? $params['scope_code'] : '';
                $scopeType = isset($params['scope_type']) ? $params['scope_type'] : 'store';
                $this->_initCurrentStore($scopeCode, $scopeType);
                $this->_initRequest();
                Mage_Core_Model_Resource_Setup::applyAllDataUpdates();
            }

            $this->getFrontController()->dispatch();
        }
        return $this;
    }

Or change this file

/app/code/core/Enterprise/PageCache/Model/Processor.php

// XSS vulnerability protection provided by htmlspcialchars call - escape & " ' < > chars
Enterprise_PageCache_Helper_Url::restoreSid($content, htmlspecialchars($sidCookieValue, ENT_QUOTES));
$base_url = ( isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']=='on' ? 'https' : 'http' ) . '://' .  $_SERVER['HTTP_HOST'];
$url = $base_url . $_SERVER["REQUEST_URI"];
if ($isProcessed) {
    file_put_contents('z_url_have_fpc.txt', date("H:i:s")." URL: $url \n",FILE_APPEND);
    return $content;
} else {
     file_put_contents('z_url_non_fpc.txt', date("H:i:s")." URL: $url \n",FILE_APPEND);
    Mage::register('cached_page_content', $content);
    Mage::register('cached_page_containers', $containers);
    Mage::app()->getRequest()
        ->setModuleName('pagecache')
        ->setControllerName('request')
        ->setActionName('process')
        ->isStraight(true);

    // restore original routing info
    $routingInfo = array(
        'aliases'              => $this->getMetadata('routing_aliases'),
        'requested_route'      => $this->getMetadata('routing_requested_route'),
        'requested_controller' => $this->getMetadata('routing_requested_controller'),
        'requested_action'     => $this->getMetadata('routing_requested_action')
    );

    Mage::app()->getRequest()->setRoutingInfo($routingInfo);
    return false;
}

 

How to check Full Page Cache is working?

Some snippet code in Magento 2

Load a model product

public function __construct(
       \Magento\Catalog\Model\ProductFactory $productFactory,
   ) {
       $this->_productFactory = $productFactory;
   }

   protected function _construct()
   {
       $product = $this->_productFactory->create()->load($this->getRequest()->getParam('id'));
       $this->_headerText = __('Reviews for %1', $product->getName());
   }

Load a model collection product

Option 1:

public function __construct(
    \Magento\Catalog\Model\ProductFactory $productFactory,
) {

    $this->productFactory = $productFactory;
}

  protected function _assignProducts()
    {

        $productCollection = $this->productFactory->create()->getCollection()->setStoreId(
            $this->storeManager->getStore()->getId()
        )->addIdFilter(
            $this->_productIds
        )->addAttributeToSelect(
            $this->salesQuoteConfig->getProductAttributes()
        )->addStoreFilter()->addUrlRewrite()->addOptionsToResult();

    }

Option 2:

public function __construct(
       \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
   ) {

       $this->productCollectionFactory = $productCollectionFactory;

   }
public function rebuildCategory(\Magento\Catalog\Model\Category $category)
   {
       $collection = $this->productCollectionFactory->create()->setStoreId(
           $this->storeManager->getStore()->getId()
       );
   
       $collection->getSelect()->reset(Select::WHERE);
       $collection->getSelect()->reset(Select::HAVING);
       $collection->getSelect()->reset(Select::SQL_HAVING);
       $collection->addAttributeToFilter('entity_id', ['in' => $existingProducts]);
       if (count($existingProducts) > 0) {
           $collection->getSelect()->reset(Select::ORDER);
           $collection->getSelect()
               ->order(new \Zend_Db_Expr('FIELD(e.entity_id, ' . implode(',', $existingProducts) . ')'));
       }

       // Apply 'sort'
       $sortedCollection = $this->sorting->applySorting($category, $collection);

      
   }

Load a Order model

public function __construct(
       \Magento\Sales\Model\OrderFactory $orderFactory
   ) {
       $this->_orderFactory = $orderFactory;
   }

  public function getLastRealOrder()
   {
       $orderId = $this->getLastRealOrderId();
       $this->_order = $this->_orderFactory->create();
       if ($orderId) {
           $this->_order->loadByIncrementId($orderId);
       }
       return $this->_order;
   }

 

CREATE A TABLE BY SQL SETUP

Magento 2 you can have 6 different Setup classes in your module:

  • InstallSchema – this class will run when the module is installed to setup the database structure
  • InstallData – this class will run when the module is installed to initial the data for database table..
  • UpgradeSchema – this class will run when the module is upgraded to setup the database structure
  • UpgradeData – this class will run when the module is upgraded to add/remove data from table.
  • Recurring
  • Uninstall
UpgradeSchema/UpgradeData

The both of this files will run when the module is installed or upgraded. This classes is difference with the Install classes because they will run every time the module upgrade. So we will need to check the version and separate the script by each version.

You create a file under folder:  /app/code/Ovi/YourExtension/Setup/InstallSchema.php

<?php
namespace Ovi\YourExtension\Setup;

use Magento\Eav\Setup\EavSetupFactory;

use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

/**
 * @codeCoverageIgnore
 */
class InstallSchema implements InstallSchemaInterface
{
    /**
     * {@inheritdoc}
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    private $eavSetupFactory;
    private $eavSetup;

    public function __construct(EavSetupFactory $eavSetupFactory, ModuleDataSetupInterface $eavSetup )
    {
        $this->eavSetupFactory = $eavSetupFactory;
        $this->eavSetup = $eavSetup;
    }

    /**
     * {@inheritdoc}
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        $installer = $setup;
        $installer->startSetup();

        $table = $installer->getConnection()->newTable($installer->getTable('a_new_table'))
            ->addColumn(
                'id', \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,10,
                ['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true,'auto_increment' => true],
                'ID'
            )->addColumn(
                'transaction_id',
                \Magento\Framework\DB\Ddl\Table::TYPE_BIGINT,null,
                [ 'nullable' => false],
                'Transaction ID'
            )->addColumn(
                'amount',
                \Magento\Framework\DB\Ddl\Table::TYPE_FLOAT,null,
                ['nullable' => false],
                'Amount'
            )->addColumn(
                'payment_date',
                \Magento\Framework\DB\Ddl\Table::TYPE_DATETIME,null,
                ['nullable' => false ],
                'TYPE_DATETIME'
            )->addColumn(
                'status_code',
                \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,10,
                ['nullable' => TRUE],
                'this is description for this column.'
            )->addColumn(
                'payment_from',
                \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,null,
                ['nullable' => true],
                'Mark which payment get from'
            );

        $installer->getConnection()->createTable($table) ;

        $installer->endSetup();

    }
}

 

Some snippet code in Magento 2

The something need to fix in Magento when migrating from PHP 5.x to PHP 7.0.x

Changes to the handling of indirect variables, properties, and methods

Indirect access to variables, properties, and methods will now be evaluated strictly in left-to-right order, as opposed to the previous mix of special cases. The table below shows how the order of evaluation has changed.

Due to uniform variable syntax the code is now interpreted strictly from left to right.

The Line

$params['object']->$params['method']($this->_file['tmp_name']);

should be

$params['object']->{$params['method']}($this->_file['tmp_name']);

And this list files have this issue:


/app/code/core/Enterprise/TargetRule/Model/Resource/Index.php:
  315:  $v = $this->$callback[0]($v, $callback[1]);

/app/code/core/Mage/Core/Model/Layout.php:
  555:    $out .= $this->getBlock($callback[0])->$callback[1]();

/app/code/core/Mage/ImportExport/Model/Export/Entity/Customer.php:
  250: $data['filter_options'] = $this->$data['options_method']();

/app/code/core/Mage/ImportExport/Model/Export/Entity/Product/Type/Abstract.php:
   99:$data['filter_options'] = $this->$data['options_method']();

/app/code/core/Mage/ImportExport/Model/Import/Uploader.php:
  135: $params['object']->$params['method']($filePath);

/downloader/lib/Mage/Connect/Command.php:
  178: return new $currentCommand['class']();

/lib/Mage/Connect/Command.php:
  134:   return new $currentCommand['class']();

/lib/Varien/File/Uploader.php:
  259: $params['object']->$params['method']($this->_file['tmp_name']);

 

Reference:
http://php.net/manual/de/migration70.incompatible.php
https://wiki.php.net/rfc/uniform_variable_syntax

The something need to fix in Magento when migrating from PHP 5.x to PHP 7.0.x

How to update Magento2 using composer

First off, remove contents of the /vendor folder

rm -rf vendor/*

Edit the composer.js file and change the version of magento in line 5:

    "version": "2.0.4",

and under “require”

"require": {
    "magento/product-community-edition": "2.0.4",

Now run composer update then run

php bin/magento setup:upgrade

And finally re-deploy the static files, which for me is this command:

php bin/magento setup:static-content:deploy de_DE en_US

That worked for me.

How to update Magento2 using composer

Technical resources/document for Magento 2

We trying to collect best Magento 2 Community resources and keep them updated in our Magento 2 Developer Resource List

Technical resources/document for Magento 2

[Magento 2] Create new controller

  1. Create your directory under <magento_root>/app/code/Mydogs/Helloworld/
  2. Create etc/module.xml file under Helloworld directory and define your module.

    <?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">

        <module name="Mydogs_Helloworld" schema_version="0.0.1" setup_version="0.0.1" />

    </config>
    
  3. Create etc/frontend/routes.xml and declare your router for Helloworld module.

    <?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
      xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/App/etc/routes.xsd">
        <router id="standard">
            <route id="helloworld" frontName="helloworld">
                <module name="Mydogs_Helloworld"/>
            </route>
        </router>
    </config>
  4. Create Controller/Index/Index.php and write below code in it.

    <?php
    namespace Mydogs\Helloworld\Controller\Index;
    use Magento\Framework\Controller\ResultFactory;
    use Magento\Framework\View\Result\PageFactory;
    
    class Index extends \Magento\Framework\App\Action\Action
    {
            /**
             * @var \Magento\Framework\View\Result\PageFactory
             */
            protected $resultPageFactory;
    
            /**
             * @param \Magento\Framework\App\Action\Context $context
             * @param \Magento\Framework\View\Result\PageFactory resultPageFactory
             */
            public function __construct(
                \Magento\Framework\App\Action\Context $context,
                PageFactory $resultPageFactory
            )
            {
                $this->resultPageFactory = $resultPageFactory;
                parent::__construct($context);
            }
        /**
         * Default customer account page
         *
         * @return void
         */
        public function execute()
        {
            $params = $this->getRequest()->getParams();
    
            $responseContent = array();
    
            if(isset($params['name'])){
                $name = $params['name'];
            }
        
            $this->getResponse()->representJson(
                $this->_objectManager->get('Magento\Framework\Json\Helper\Data')->jsonEncode($responseContent)
            );
        }
        
    }
    ?>
  5. Create your layout and template files under view/frontend/layout/helloworld_index_index.xml

    <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
        <body>
        	<referenceContainer name="content">
                <block class="Magento\Framework\View\Element\Template" name="hello.world" as="helloWorld" template="Mydogs_Helloworld::hello-how-are-you.phtml" before="-" />
            </referenceContainer>
        </body>
    </page>

    and view/frontend/templates/hello-how-are-you.phtml respectively.

    <h1>Hello World</h1>
    <p>this is hello-how-are-you.phtml</p>
  6. Open /app/etc/config.php and define your module in an array.
  7. Run command line:  php bin/magento setup:upgrade
[Magento 2] Create new controller