Magento 2

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

In what order Plugins are called

1) Before Plugin 2) Around Plugin 3) Around plugin 4) After Plugin

What is di.xml is used for

1) Preferences 2) Plugin 3) Virtual Type 4) Augment replacement 5) Constructor arguments 6) Abstraction-implementation mappings When the constructor signature of a class requests an object by its interface. The object manager uses these mappings to determine what the default implementation is for that class for a particular scope. The preference node specifies the default implementation: <!-- File: app/etc/di.xml --> <config> <preference for="Magento\Core\Model\UrlInterface" type="Magento\Core\Model\Url" /> </config> 7) Object lifestyle configuration The lifestyle of an object determines the number of instances that can exist of that object. You can configure dependencies in Magento to have the following lifestyles: singleton(default) - One instance of this class exists. The object manager creates it at the first request. Requesting the class again returns the same instance. Disposing or ending the container registered to it releases the instance. transient - The object manager creates a new instance of the class for every request. The shared property determines the lifestyle of both argument and type configurations. <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <type name="Magento\Filesystem" shared="false"> <arguments> <argument name="adapter" xsi:type="object" shared="false">Magento\Filesystem\Adapter\Local</argument> </arguments> </type> </config> In this example Magento\Filesystem is not shared, so all clients will retrieve separate instances of Magento\Filesystem. Also, every instance of Magento\Filesystem will get separate instance of $adapter, because it too is non-shared.

Design patterns of magento 2

1. Composite Pattern 2. Strategy Pattern 3. Factory Method Pattern 4. Observer Pattern 5. Object Manager (which consist of 11+ Design Patterns) 6. Decorator Pattern 7. Proxy Pattern

Magento 2.2 Features

A ) B2b Features like 1) Company Accounts 2) Shared Catalog Offer a curated product selection with custom pricing for specific companies, while continuing to offer the standard catalog with regular pricing for general customers. 3) Quick Order Reduces the order process to several clicks for shoppers who know the name or SKU of the products they want to order. SKUs can be entered manually or uploaded from a CSV file. 4) Requisition Lists Maintain up to 99 different requisition lists to save time with frequently ordered products. Add items directly to the cart, or transfer items from one requisition list to another. 5) Quotes Buyers can negotiate directly with the seller for a custom discount. The system saves a snapshot of the catalog, and the history of all activity related to the quote. 6) Payment On Account Give companies the convenience of charging purchases to their account, up to the credit limit that that you determine for the company. B) Bundled extensions. This release of Magento includes the first third-party extension that we are bundling with Magento Commerce - Magento Social. This extension establishes a connection between your store and your corporate Facebook account, and creates a page with products from your catalog. When shoppers click a product, they are redirected to the corresponding product page in your Magento store. C) Integrated Signifyd fraud protection. D) Upgraded technology stack. We've dropped support for PHP 5.6, Varnish 3, and Solr. We now support PHP 7.1 and Varnish 5, along with Redis 3.2 and MySQL 5.7. All third-party libraries have been upgraded to the latest stable version. Note: Although we've dropped support for Solr with this release, Solr code will remain in the Magento code base until a later release. E) Pipeline deployment, a new deployment process, enables build and deployment stages to minimize production system downtime for site updates. Resource-intensive processes can run on the build server. Pipeline deployment supports easy management of configuration between environments, too. Read more about pipeline deployment here. F) Performance gains from improvements in indexing, cart, and cache operations. Customers can browse and shop on a storefront while indexers are running with no visible impact to their experience. Additionally, long-running indexers operate in batches to better manage memory and run times. Cart improvements enable a buyer to create a cart with more than 300 line items, and merchants can process a cart with at least 300 line items. Varnish cache configuration now includes saint and grace mode to ensure Varnish is always presenting a cached page to a shop's customers. Enhancements to cache invalidation logic and optimization of edge side include blocks for frequently changing data that significantly boost cache hit ratios.

What is a service contract?

A service contract is a set of PHP interfaces that are defined for a module. A service contract includes data interfaces, which preserve data integrity, and service interfaces, which hide business logic details from service requestors such as controllers, web services, and other modules. If developers define data and service interfaces according to a set of design patterns, the result is a well-defined, durable API that other modules and third-party extensions can implement through Magento models and resource models.

In which file vender path stored and at which location?

App/etc/vendor_path.php

Javascript Bundling in Magento 2

Bundle is used to optimize loading of dynamic required scripts that use Require.js. And merge option is used to speed up loading of old way embedded scripts. When both Magento 2 Bundle and Merge modes are enabled it can lead to unstable work and decrease effect of each separate mode.

Cacheable and Uncacheable pages

Cacheable and uncacheable are terms we use to indicate whether or not a page should be cached at all. (By default, all pages are cacheable.) If any block in a layout is designated as uncacheable, the entire page is uncacheable. To create an uncacheable page, mark any block on that page as uncacheable in the layout using cacheable="false". Examples of uncacheable pages include the compare products, cart, checkout pages Cacheable page checklist -Pages use GET requests -Pages render only cacheable blocks -Pages render without sensitive private data; session and customer DTO objects are empty -Functionality specific to both current session (customer) and page should be written using JavaScript (e.g., related product listing should exclude items that are already in the shopping cart) -Model and block level should identify themselves for invalidation support -Declare a custom context variable if you plan to show different public content with the same URL Non-cacheable page checklist -Use POST requests to modify Magento state (e.g., adding to shopping cart, wishlist, etc.) -Blocks that can't be cached should be marked as non-cacheable in the layout. However, be aware that adding a non-cacheable block to a page prevents the full page cache from caching that page. -Controllers that don't use layouts should set no-cache HTTP headers

Di compile command

Code compilation includes the following (in no particular order): 1) Application code generation (factories, proxies) 2) Area configuration aggregation (optimized dependency injection configurations per area) 3) Interceptor generation (optimized code generation of interceptors) 4) Interception cache generation 5) Repositories code generation (generated code for APIs) 6) Service data attributes generation (generated extension classes for data objects)

Magento Modes

Developer mode In developer mode: -A symlink to a static view file is published to the pub/static directory for each requested file Uncaught exceptions display in the browser -System logging in var/report is verbose -An exception is thrown in the error handler, rather than being logged -An exception is thrown when an event subscriber cannot be invoked - As side note it's good to keep in mind that the /index.php file is used when running as developer mode and /pub/index.php is used when running as production mode Production mode In production mode: Static view files are not materialized, and URLs for them are composed on the fly without going through the fallback mechanism. (Static view files are served from cache only.) Errors are logged to the file system and are never displayed to the user Default mode - Errors are logged to the file reports at server, and never shown to a user - A symlink to a static view file is published to the pub/static directory for each requested file -Default mode is not optimized for a production environment, primarily because of the adverse performance impact of static files being dynamically generated rather than materialized. In other words, creating static files and caching them has a greater performance impact than generating them using the static files creation tool

What is EAV

EAV, stands for Entity Attribute Value, is a technique which allows you to add unlimited columns to your table virtually. EAV also known as object attribute value model and open schema. Entity (E): Entity actually refers to data item. For example we can consider it as customer, category or product. Attribute (A): Attribute refers to the different attributes of the Entity. Like for example product have different attributes like color, size, price, etc. Value (V): Value refers to the actual value of the attribute of the entity. Like color has value red, price has value $25, etc. In EAV, you have one table which holds all the "attribute" (table field names) data, and other tables which hold the "entity" (id or primary id) and value (value for that id) against each attribute. In Magento, there is one table to hold attribute values called eav_attribute and 5-6 tables which holds entity and data in fully normalized form, eav_entity, eav_entity_int (for holding Integer values), eav_entity_varchar (for holding Varchar values), eav_entity_datetime (for holding Datetime values), eav_entity_decimal (for holding Decimal/float values), eav_entity_text (for holding text (mysql Text type) values). EAV is expensive and should only be used when you are not sure about number of fields in a table which can vary in future. To just get one single record, Magento joins 4-5 tables to get data in EAV. But this doesn't mean that EAV only has drawbacks. The main advantage of EAV is adding the table column will not affect the previously saved records (also the extra space will not get allocated!) and all the new records will seamlessly have data in these columns without any problem.

What are Extension Attributes

Extension attributes are new in Magento 2. They are used to extend functionality and often use more complex data types than custom attributes. These attributes do not appear in the MAgento Admin. You must create a <Module>/etc/extension_attributes.xml file to define a module's extension attributes:<config> <extension_attributes for="Path\To\Interface"> <attribute code="name_of_attribute" type="datatype"> <resources> <resource ref="permission"/> </resources> <join reference_table="" reference_field="" join_on_field=""> <field>fieldname</field> </join> </attribute> </extension_attributes> </config>

Factories in magento

Factories are service classes that instantiate non-injectable classes, that is, models that represent a database entity. They create a layer of abstraction between the ObjectManager and business code. Unless you require specific behavior for your factory classes, you do not need to explicitly define them because they are an automatically generated class type. When you reference a factory in a class constructor, Magento's object manager generates the factory class if it does not exist.

What are the features of Magento 2?

Here are the following key features of Magento 2: Open and flexible architecture Enhanced business agility and productivity Engaging shopping experiences Grade scalability and performance of the enterprise Easier upgrades and maintenance Secure Payments Backup/Rollback system

What are proxy classes

If a class's constructor is particularly resource-intensive, this can lead to unnecessary performance impact when another class depends on it, if the expensive object does not end up being needed during a particular request. Magento has a solution for this situation: proxies. Proxies extend other classes to become lazy-loaded versions of them. That is, a real instance of the class a proxy extends created only after one of the class's methods is actually called. A proxy implements the same interface as the original class and so can be used as a dependency anywhere the original class can. Unlike its parent, a proxy has only once dependency: the object manager. Proxies are generated code and therefore do not need to be manually written. (See Code generation for more information.) Simply reference a class in the form \Original\Class\Name\Proxy, and the class is generated if it does not exist. Using the preceding example, a proxy can be passed into the constructor arguments instead of the original class, using DI configuration as follows: <type name="FastLoading"> <arguments> <argument name="slowLoading" xsi:type="object">SlowLoading\Proxy</argument> </arguments> </type> With the proxy used in place of SlowLoading, the SlowLoading class will not be instantiated—and therefore, the resource intensive constructor operations not performed—until the SlowLoading object is used (that is, if the getSlowValue method is called).

Which class is necessary to inject in constructor to instantiate block?

If you want to instantiate a block you need to add to inject in the constructor an instance of \Magento\Framework\View\LayoutFactory

Dependency Injection

Inside a project, classes interact with each other. So we can say, a class depends on other classes. And there are 2 ways the connection can be made. The class locates its dependencies. The dependencies are provided to the class. Magento 1 takes the first approach. Here is a random example. In this example, the category model depends on the url rewrites instance. So it instantiates it. Magento 2 takes the second approach. When building a class, all the dependencies are specified in the constructor. When used, the class is instantiated via a factory method that reads the signature of the class constructor, to check what dependencies are required. Magento 2 also has a dependency injection container (DIC) which is basically a big array with the classes that get instantiated. When trying to instantiate a class, it checks if it's dependencies are already present in the DIC. If they are, they are provided to the constructor, if not, the dependency class is instantiated in the same way as the current class you are trying to instantiate. This is it in a nutshell. In practice is a bit more complicated because configuration files are involved also (di.xml), some dependencies might be interfaces which cannot be instantiated, but this factory method supplies a class that implements that interface when your class gets instantiated, based on the contents of the same di.xml file. Also some dependencies are not objects. They can be arrays, string, ... They are supplied to the class via the same di.xml file.

When plugin cannot be used

Limitations Plugins cannot be used with any of the following: - Objects that are instantiated before Magento\Framework\Interception is bootstrapped - Final methods - Final classes - Any class that contains at least one final public method - Non-public methods - Static methods - __construct - Virtual types

Why use Magento 2?

Magento was stripped down and rebuilt from scratch to what is now a quicker, easier, and safer Magento 2 version. Some of its advantages include: It is very fast It's have New File Structure It's have New Layout Elements CSS Preprocessing Magento UI Library Improved performance and scalability Reducing upgrade efforts and costs

getSize() vs getCount()

Most (if not all) the collections extend Varien_Data_Collection_Db. Here are the 2 methods from this class public function getSize() { if (is_null($this->_totalRecords)) { $sql = $this->getSelectCountSql(); $this->_totalRecords = $this->getConnection()->fetchOne($sql, $this->_bindParams); } return intval($this->_totalRecords); } public function count() //inherited from Varien_Data_Collection { $this->load(); return count($this->_items); } There is a difference. For getSize() the collection is not loaded. For count() it is. Usually collection models use the same getSize() method as above and only override

magento2 performance enhancement

Server - Software Recommendations The following is a list of recommended software for production instances in order of impact: Varnish cache PHP 7 (Enterprise only) Use the Elasticsearch & Elasticsearch Search Adapter Nginx and PHP-FPM For multi-server deployments or for merchants planning on scaling their business we recommend the following: Redis for sessions (from 2.0.6+) A separate Redis instance as your default cache Do not use this instance for page cache Server - Composer Optimization After running setup:di:compile to generate classes, use composer to update the autoloader. Run the following composer command to generate an optimized composer class map that supports faster auto-loading. composer dump-autoload -o Server - PHP Configuration We recommend enabling and tuning PHP opcache for maximum performance. Edit your opcache.ini file to include the following: opcache.enable_cli=1 opcache.memory_consumption=512 opcache.max_accelerated_files=100000 opcache.validate_timestamps=0 opcache.consistency_checks=0 When you fine tune the memory allocation for opcache, take into account the size of Magento's code base and all your extensions. Magento's performance team uses the values in the preceding example for testing because it provides enough space in opcache for the average number of installed extensions. If you are on a low memory machine and you do not have many extensions or customizations installed, use the following settings to get a similar result: opcache.memory_consumption=64 opcache.max_accelerated_files=60000 Server - Redis Configuration & Tuning Sessions Consider how sessions are flushed from the cache and your merchants abandoned cart strategy. Caches Estimate a memory size to fit the total number of effective skus, product pages and content pages you expect will be used. Magento - Performance Optimizations Enable these performance optimizations to improve the store front responsiveness of your Magento instance. Go to the Admin in default of developer mode and change the following settings for store front asset optimization: Server - MySQL Configuration & Tuning for Indexing Performance In Magento 2.2.0, you can tune indexers performance by adjusting the index batching size variables. This controls how many entities are processed at a time by the indexer. In some situations we've seen significant decreases in indexing time. For example, if you are running a profile similar to B2B Medium, you can override the configuration value batchRowsCount in app/code/Magento/catalog/etc/di.xml and override the default value of 5000 to 1000. This reduces the full indexing time from 4 hours down to 2 hours with a default MySQL configuration! Please note that we have not enabled batching for the catalog rules indexer. Merchants with a large number of catalog rules need to adjust their MySQL configuration to optimize indexing time. In this case editing your MySQL configuration file and allocating more memory to TMP_TABLE_SIZE and MAX_HEAP_TABLE_SIZE configuration value (default is 16M for both) will improve performance for this indexer but will result in MySQL consuming more RAM.

Get Model and getSingleton equivalent in magento2

Singleton equivalent in magento are factory classes Get Model equivalent is using objectManager();

Why is Pub folder used

The pub directory is a security measure in order block public access to your root directory assets, namely the app directory. The reason that index.php is also located in the root directory is presumed to address individuals whose webhost make it difficult or impposible to change your webroot. When utilizing the pub/index.php the app source folder will not be able to be accessed while it could be it be if index.php was being ran from the root directory. This practice is also seen in Symfony and Zend 2. This way none of the Magento application configurations, templates, etc are exposed.

Static content deploy

The static view files deployment command enables you to write static files to the Magento file system when the Magento software is set for production mode. The term static view file refers to the following: "Static" means it can be cached for a site (that is, the file is not dynamically generated). Examples include images and CSS generated from LESS. "View" refers to the presentation layer (from MVC). Static view files are located in the <your Magento install dir>/pub/static directory, and some are cached in the <your Magento install dir>/var/view_preprocessed directory as well. Static view files deployment is affected by Magento modes as follows: Default and developer modes: Magento generates them on demand, but the rest are cached in a file for speed of access. Production mode: Static files are not generated or cached.

Which class Magento 2 helper extend?

\Magento\Framework\App\Helper\AbstractHelper

Service Contracts

http://devdocs.magento.com/guides/v2.1/extension-dev-guide/service-contracts/design-patterns.html

Request Flow in magento2

http://www.dckap.com/blog/request-flow-in-magento-2/ Step 1 : Request hits index.php in root folder of Magento 2. Step 2 : index.php calls static create() method of bootstrap class to create objectmanagerfactory and bootstrap objects. Step 3 : index.php calls createApplication() method of bootstrap object which in turn will initiate ObjectManager using objectManagerFactory. Then, application instance gets created using objectManager and returned to index.php. Step 4 : index.php calls run() method of bootstrap object to run the application, which in turn will call launch() method of application object. Step 5 : HTTP Application instance does initial routing. It takes first part of the URL to find out which area should be loaded (admin/frontend). When the area is defined, configuration for that area is loaded (unlike Magento 1 where all configuration was loaded). Then application object calls Magento\Framework\App\FrontControllerInterface::dispatch of requested area. Step 6 : Front Controller does routing same as in Magento 1. All routers are iterated to match request. The router that matches the request returns instance of ActionController. When FrontController gets instance of action controller it calls dispatch method on it. This process is more efficient because only routers of one area are used (admin router is not used in frontend). Step 7 : Action controller performs its task and returns instance of some implementation of ResultInterface. Step 8 : FrontController just returns ResultInterface to Application Instance that renders the response

What are virtual types class

https://alanstorm.com/magento_2_object_manager_virtual_types/

Magento 2 Create Custom Theme

https://www.magestore.com/magento-2-tutorial/magento-2-theme-create-sample-custome-theme/

What is resource attribute for admin menu item?

o 'resource' attribute defines the ACL rule, that a user must have in order to access this Menu Item. o Predefined ACL rule (Magento_Backend::content) from a standard Magento module. o If the logged in user does not have access to the configured ACL rule, the Menu Item will not render for them.

What is the difference between cache:clean and cache:flush command?

o Cache:clean deletes all items from enabled Magento cache types only. But cache:flush physically removes completely the cache storage. o Cache:clean will not clean Disabled cache types. But cache:flush will disabled cache types also.

What does $this->resultPageFactory->create(); statement means in controller file?

o In Magento 2 all controller actions must return something, opposed to M1, where a controller action would just output something or did a redirect. o resultPageFactory is an instance of \Magento\Framework\View\Result\PageFactory and when calling create() on that class it returns an instance of \Magento\Framework\View\Result\Page described above. o When this is used and the result is returned it means that your action will return HTML. o It has somehow a similar effect as $this->loadLayout(); from Magento 1. When you call create on the resultPageFactory object it actually loads the layout. o When you return a page result object from your execute method, you're telling Magento to kick off the standard layout handle XML file page rendering.

Which files are necessary to install - upgrade database tables and to records in it

o InstallSchema o UpgradeSchema o InstallData o UpgradeData


Ensembles d'études connexes

Auditing 1 ch. 2 Multiple Choice

View Set

Chapter 11—Reflection of Meaning and Interpretation/Reframe: Helping Clients Restory Their Lives

View Set

Nutrition Ch 7: Water Soluble Vitamins

View Set

Ch. 16 The Eukaryotic Cell Cycle, Mitosis, and Meiosis Study Questions and Answer Key

View Set