In Magento 1
we were used to place our classes in these directories
- Block
- Helper
- Model
- Resource
and use a simple class name without any capital letters in the middle of the name.
If we take a look at some cases in Magento 2 Core
Helpers
Location:
– \Foo\Bar\Helper
Name:
– *.php
Examples:
– \Magento\ImportExport\Helper\Report
– \Magento\Cms\Helper\Wysiwyg\Images
Observers
Location:
– \Foo\Bar\Observer
Name:
– *.php
– *Observer.php
Examples:
– \Magento\CustomerCustomAttributes\Observer\SalesOrderAddressAfterLoad
– \Magento\CustomerBalance\Observer\ProcessBeforeOrderPlaceObserver
Plugins
Location:
– \Foo\Bar\Plugin
Name:
– *.php
– *Plugin.php
Examples:
– \Magento\Catalog\Plugin\Block\Topmenu
– \Magento\PageCache\Model\App\FrontController\BuiltinPlugin
Source: http://devdocs.magento.com/guides/v2.0/extension-dev-guide/plugins.html#declaring-a-plugin
ConfigProvider
Location:
– \Foo\Bar\Model
Name:
– *ConfigProvider.php
Examples:
– \Magento\Tax\Model\TaxConfigProvider
– \Magento\Payment\Model\IframeConfigProvider
My questions are :
- If there is any
good
/bad
/best
practices for that inMagento 2
? - If I want to create a custom
DataProvider
for example what it will be ?\Foo\Bar\Provider\CustomDataProvider
\Foo\Bar\DataProvider\Custom
\Foo\Bar\Model\Provider\CustomDataProvider
\Foo\Bar\Helper\Provider\CustomDataProvider
- How to determine the construction of the class name and location, a folder at the root of the module, in Model, in Helper, etc?
- Does it depends on retrieved data source / data type ?
- When do we have to add the suffix to the class name ?
A part of a response for the Virtual Types
: https://community.magento.com/t5/Magento-DevBlog/Virtual-Types-Naming-Convention/ba-p/61510
Best Answer
Magento 2 is not restricted as Magento 1 to only a few folders like block, helper, model and so on.
You can basically place a class in any folder you want. It's up to you since the class are instantiated using the full class name not with aliases as in Magento 1.
My recommendation is to group them by the functionality.
Vendor/Module/Observer
.Vendor/Module/Plugin
Vendor/Module/DataProvider
.Vendor/Module/Ui
but try to avoid name duplication. I mean
Vendor/Module/DataProvider/CustomDataProvider
would be redundant.Maybe the suffix can be added for interfaces only, although people would argue against it.
To summarize, it's up to you how you do it, just be consistent in it.
From the functionality point of view it's not important where you place the classes. You can even go crazy with them and place all of them directly in
Vendor/Module
folder, but you probably don't want that.I think (but not completely sure) that the only restriction is that controllers must be in the folder
Controller
.