Snippets

snake_case, camelCase, UpperCamelCase conversion

\Magento\Framework\Api\SimpleDataObjectConverter::snakeCaseToCamelCase('some_value');
\Magento\Framework\Api\SimpleDataObjectConverter::snakeCaseToUpperCamelCase('some_value');
\Magento\Framework\Api\SimpleDataObjectConverter::camelCaseToSnakeCase('someValue');

Bootstrap script

<?php
use Magento\Framework\App\Area;
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/../app/bootstrap.php';

$bootstrap = Bootstrap::create(BP, $_SERVER);
$obj = $bootstrap->getObjectManager();
/** @var \Magento\Framework\App\State $state */
$state = $obj->get(\Magento\Framework\App\State::class);
$state->setAreaCode(Area::AREA_FRONTEND);

// do something

Optimized iteration over large collections

$collection = $this->collectionFactory->create();
$collection->setPageSize(100);
$lastPageNumber = $collection->getLastPageNumber();

for ($curPage = 1; $curPage <= $lastPageNumber; $curPage++) {
    $collection->setCurPage($curPage);

    foreach ($collection->getItems() as $item) {
        // loop logic goes here
    }

    $collection->clear();
}

Custom logger

Custom logger that logs entries to var/log/custom.log. You can inject it into any class through di.xml (see SampleService class below).

Declaration

app/code/Vendor/Module/di.xml

<virtualType name="Vendor\Module\Log\Handler" type="Magento\Framework\Logger\Handler\Base">
	<arguments>
		<argument name="fileName" xsi:type="string">/var/log/custom.log</argument>
	</arguments>
</virtualType>
<virtualType name="Vendor\Module\Log\Logger" type="Magento\Framework\Logger\Monolog">
	<arguments>
		<argument name="name" xsi:type="string">CustomLogger</argument>
		<argument name="handlers" xsi:type="array">
			<item name="debug" xsi:type="object">Vendor\Module\Log\Handler</item>
		</argument>
	</arguments>
</virtualType>

Usage

app/code/Vendor/Module/di.xml

<type name="Vendor\Module\Model\SampleService">
    <arguments>
        <argument name="logger" xsi:type="object">Vendor\Module\Log\Logger</argument>
    </arguments>
</type>

app/code/Vendor/Module/Model/SampleService.php

<?php
declare(strict_types=1);

namespace Vendor\Module\Model;

class SampleService
{
    /** 
    * @var \Psr\Log\LoggerInterface 
    */
    private $logger;

    public function __construct(\Psr\Log\LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    public function execute()
    {
        $this->logger->debug('this will be saved in var/log/custom.log');
    }
}