Hello Everyone, This is MO. In this blog, we are going to explain how to optimize the time during the Magento local development environment. This will speed up the development process. It makes a huge difference in the development process of Magento projects.
1. Stop Typing So Much: bin/magento
Typing bin/magento within local development environments is one of the biggest wastes of time for a developer, as are the aliases that go along with it.
bin/magento
bin/magento cache:flush
bin/magento setup:upgrade
bin/magento setup:di:compile
bin/magento setup:static-content:deploy
bin/magento module:status
bin/magento indexer:reindex
bin/magento deploy:mode:show
bin/magento deploy:mode:set
Set up bash aliases for bin/magento to save a ton of time. To set up, bash aliases follow the.
below steps
Alias bin/magento to m2:
echo "alias m2=bin/magento" >> ~/.bash _ profile
Then reload your bash prompt to make the alias active:
source ~/.bash_profile
Then, use command shortcut aliases for bin/magento (or now, "m2"), to save a TON of compounding time daily.
m2 se:up
m2 se:d:co
m2 se:s:d
m2 in:rei
m2 d:m:sh
m2 d:m:se
2. Stop Using Hard-Coded Values
The usage of hardcoded values is not explicit, hard to understand and the usage isn't descriptive.
$result = $this->getCollection(10);
Implementing constants for hardcoded values make values descriptive, easy to diagnose, and understandable. Locate all of your constants at the top of the files and make sure they are very descriptive and without ambiguity.
const RESULT_LIMIT = 10;
$result = $this->getCollection(self::RESULT_LIMIT);
3. Stop Saving Data Objects
Data objects should not be responsible for saving themselves. Calling on a model entity is deprecated.
namespace Mo\Tutorial\Controller\Sample;
use Mo\Tutorial\Model\Sample;
class Index
{
const VALUE = 10;
/** @var Sample */
private $sample;
/**
* @param Sample $sample
*/
public function __construct(Sample $sample)
{
$this->sample= $sample;
}
public function execute( )
{
$this->sample->setValue(self::VALUE);
$this->sample->save() ;
}
}
Saving data objects with resource models creates a separation of concern so data models only represent data entities and resource models only interact with the database. To ensure you are always saving new objects to the database, create these new data entities with factories
namespace Mo\Tutorial\Controller\Sample;
use Mo\Tutorial\Model\Sample;
use Mo\Tutorial\Model\SampleFactory;
use Mo\Tutorial\Model\ResourceModel\Sample as SampleResource;
class Index
{
const VALUE = 10;
/** @var SampleFactory */
private $sampleFactory;
/** @var SampleResource */
private $sampleResource;
/**
* @param SampleFactory $sampleFactory
* @param SampleResource $sampleResource
*/
public function __construct(
SampleFactory $sampleFactory,
SampleResource $sampleResource
) {
$this->sampleFactory= $sampleFactory;
$this->sampleResource= $sampleResource;
}
public function execute( )
{
/**
* Create a sample object from the automatically generated
* sample factory. This ensures a new object is created
* every time the code is running.
*/
/** @var Sample $sample */
$sample=$this->sampleFactory->create();
$sample->setValue(self::VALUE);
/**
* save the sample with the sample resource instead of
* saving the sample object directly from the model.
* This Usage separates concerns of responsibility.
*/
$this->sampleResource->save($sample) ;
}
}
4. Use Ternary Operators
Setting a variable value and then re-setting it based on the value of an existing or boolean conditional introduces unneeded cyclomatic complexity, and is not DRY (don’t repeat yourself ) from the multiple uses of the same variable name. The code is unnecessarily long and isn’t too easy to read.
public function getCustomerGroupId()
{
$customerGroupId = (int)
$this->getRequest()->getParam(‘cid’);
// Existence or boolean condition to check the just-set value
If ($customerGroupId == null) {
// Re-sets
existing variable that was just set above
$customerGroupId = $this->httpContext->getValue(Context::CONTEXT_GROUP);
}
// $customerGroupId is repeated throughout the code
return $customerGroupId;
}
Using a ternary operator greatly simplifies code readability when checking against the existence of a boolean conditional. A null coalesce operator aligns perfectly with this citation and keeps the code DRY. Since the function name is very descriptive and a single responsibility, there is also no need for a variable assignment within this function; just return the computed value.
public function getCustomerGroupId()
{
return (int)$this->getRequest()->getParam(‘cid’)?:$this->httpContext->getValue(Context::CONTEXT_GROUP):
}
5. Stop Using Object Manager
The usage of Object Manager is officially discouraged from Magento. Implementing Object Manager into your code (as below) circumvents Magento’s dependency injection object creation process and could make your code incompatible, and prone to errors during upgrades
public function execute() { …... $quote->setWebsite( $this->_objectManager->get(\Magento\Store\Model\StoreManagerInterface::class) ->getWebsite($websiteId); …... }
Rather than using Object Manager directly in your code. One should instantiate objects within the constructor of your class. Doing so puts Magento in charge of instantiating your objects and makes code much more compatible with others’ code as well as upgrades.
use Magento\Store\Model\StoreManagerInterface; ….. Class Sample { /** @var StoreManagerInterface */ Private $storeManager; /** * @param StoreManagerInterface $storeManager */ Public function __construct( StoreManagerInterface $storeManager ) { $this->storeManager = $storeManager; } public function execute() { …. $quote->setWebsite($this->storeManager->getWebsite($websiteId)); ….. } }
6. Variable Scope Naming
Prefixing a private or protected class variable with an underscore was done before IDEs were able to determine the variable scope.
/**
* Load data for preview flag
*
* @var bool
*/
protected $_previewFlag;
Eliminate the underscore prefix, it’s no longer needed! IDEs are now powerful enough to understand the variable scope. Using underscores is an outdated practice.
/**
* Load data for preview flag
*
* @var bool
*/
protected $previewFlag;
7. Use Command query separators
This function not only returns the desired value but carries out other actions. An external call is made which modifies other variables, modifies the value being returned, and/or does “other stuff” (side effects) which causes unexpected and unknown results to occur. These side effects make code hard to test and are unbeknownst to the calling code.
/**
* Retrieve the title, and do other stuff.
*
* @return string
*/
public function getTitle()
{
//This is where “Other stuff” happens --a side effect
$this->build();
return $this->title;
}
This function does just one thing; it returns the desired value.
/**
* Retrieve the title.
*
* @return string
*/
public function getTitle()
{
//Don’t do anything else; just get the value of the title
return $this->title;
}
8. Use Type Hinting variables
When creating specific objects ( say, from factory objects) your IDE’s intelligence will be unable to find the proper method. This makes debugging difficult.
$sampleCollection = $this->sampleCollectionFactory->create( )
->addAttributeToFilter(self::ID, $this->getData(‘id’))
->addAttributeToSelect(‘*’);
// ‘->count( )’ shows ‘Method ‘count’ not found’ within intellisense
if ($sampleCollection->count( )) {
$this->setData(‘sample’, $sampleCollection>getFirstItem( ));
}
use Mo\Tutorial\Model\ResourceModel\Sample\Collection;
…..
/** @var Collection $sampleCollection */
$sampleCollection = $this->sampleCollectionFactory->create( )
->addAttributeToFilter(self::ID, $this->getData(‘id’))
->addAttributeToSelect(‘*’);
// ‘->count( )’ is now found with intellisense
if ($sampleCollection->count( )) {
$this->setData(‘sample’, $sampleCollection>getFirstItem( ));
}
9. XML schema resolution
Specifying a relative path for an XML schema location in Magento is not recommended. The location of the Magento Framework or modules should not be pre-determined, as this location could change over time.
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../../../../../../lib/MagentoFramework/Acl/etc/acl.xsd">
Specifying a Uniform Resource Name (URN) for an XML schema location is
Magento’s preferred implementation method. This decouples hard-coded XML schema locations by replacing them with addresses that may be dynamically changed at a later date.
Module location uses -- urn:magento:module:Mohith_Tutorial:(relative_path)
Magento Framework uses -- urn:magento:framework:Module/(relative_path)
Run ‘bin/magento dev:urn-catalog:generate’ to generate URNs for your IDE.
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Acl/etc/acl.xsd">
10. Stop using Fully Qualified Class Names
Repeating the use of fully qualified class names make code harder to read, reason about, and understand.
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
‘Mo_Tutorial’,
__DIR__
);
By Importing all classes at the top of your file. You are making your code easier to read,
understand, and reason about.
use Magento\Framework\Component\ComponentRegistrar;
ComponentRegistrar::register(ComponentRegistrar::MODULE,‘Mo_Tutorial’,__DIR__);
Thank you for Reading. Are you fascinated to know more about Magento, What are you waiting for? Check out the other blogs in the Magento section and follow us through Youtube and Instagram to know more about us.
0 Comments