Magento 2 – PHP Optimize Tips – Part 2

Magento 2 – PHP Optimize Tips – Part 2

Continue of Part 1.

After part 1 you know how to process with large Collection, why we need to use Model Factory instead of Model in __constructor and Customer data sections to load a partition of the web page without disabling FULL page cache.

Today I will provide you with consultation and assist you with some tips when you’re working on data.

Tip 1: Use in condition instead of for each id and load Data Model

You have an array of entity_id or identity id of the collection. please use

$model->getCollection()->addFieldToFilter('entity_id', ['in'=>$ids]);
Code language: PHP (php)

instead of

foreach($ids as $id){ $model->load($id); }
Code language: PHP (php)

Tip 2: Reduce your for-loop time with some tricks.

  • You should Pre-Calc the length before running the loop since the array size (is fixed) isn’t changed while looping.
$size = count($array); for ($i=0; $i<$size; $i++){ //TODO something. }
Code language: PHP (php)
  • Using “===” instead of “==

You can visit for more explained:
——— Not much but it helpful.

Tip 3: Use Insert On Duplicate Update.

– Did you have some task or problem about insert or update if data has existed, Collect database many times about check, if the record exists and update or insert. Do not need that anymore because we have Insert On Duplicate Update. Let me detail it to you.
Ex: You have a table of Zip Code data with Zip Code is a primary key.

Table MyZipCode - zip_code: varchar primary key - city: varchar - country: varchar

You need to update the country of a zip code or insert it to table MyZipCode.
Just use

// Class: \Magento\Framework\App\ResourceConnection $resource // Get Write Connection $connection = $resource->getConnection('write'); // Begin transaction $connection->beginTransaction(); //Insert Data To Database $tableName = "my_zip_code"; // Prepair data to insert and update. $data = [ [ 'zip_code' => 12333, 'city' => "City ABC", 'country' => "Country ABC" ] ] $connection->insertOnDuplicate($tableName, $data, ['city', 'country']);
Code language: PHP (php)

The post is updating.

ps: images (ServerGuy)

Leave a Reply

Your email address will not be published.