Magento 2 some important coding practice for developers

In my previous blogpost for code sniffer, we have come to know how we can find if our extension is following MEQP2 standards. Today let us see some most common coding practice that will help us while developing Magento extension. This will make our code more magento friendly.

Use dependency injection not object manager

We all love to use object manager though we know it is not a recommended practice by Magento. We should not use it for several reason:-

a. To maintain code consistency
b. Testing become easier(as we can pass mock object as an argument)
c. Dependency injection make dependencies more clear – as everything can be easily found in constructor rather than hidden in middle of the code.
d. It also prevent us from using repeated dependency as we can make use already existing dependency of parent class

There are several exception to this scenario:-

• in static magic methods like __wakeup, serialize, etc
• in case you should make backward compatibility of constructor
• in global scope, like in fixtures of integration test.
• in class that needs only for creation of object like factory, proxy , etc

You can go through for more details about dependency injection.

Do not use session in dependency injection

Whenever you will check your code with MEQP2 standard it will raise an issue if you have used session object in constructor as dependency injection. You will get below error. You can simply replace it from parent class session objects.

“Session object MUST NOT be requested in constructor. It can only be passed as a method argument. “

Use Magento exception library not core PHP – Do not throw exception using PHP keyword.

You can use message manager to show error, warning or ant exception message rather than using throw keyword.
Include \Magento\Framework\Message\ManagerInterface $messageManager in your constructor and call the respective function to show error, warning or exception.

Use magento library function instead of core PHP function

For example for curl request instead of using curl_init, curl_setopt, curl_exec use the function provide by curl class in magento (\Magento\Framework\HTTP\Client\Curl $curl)

Leave a Comment.