PHPackages                             bdc/module-simplenews - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. bdc/module-simplenews

ActiveMagento2-module

bdc/module-simplenews
=====================

BDCrops SimpleNews module for Magento 2 extensions.

323JavaScript

Since Dec 23Pushed 6y ago1 watchersCompare

[ Source](https://github.com/bdcrops/module-simplenews)[ Packagist](https://packagist.org/packages/bdc/module-simplenews)[ RSS](/packages/bdc-module-simplenews/feed)WikiDiscussions master Synced 2d ago

READMEChangelogDependenciesVersions (1)Used By (0)

Magento 2 SimpleNews module
===========================

[](#magento-2-simplenews-module)

**Magento 2 Module development** or **Magento 2 SimpleNews Module** Create a full-fledged Module Step by Step. You could just follow my code to create this module from the scratch. Or you can directly download the compressed tar file and install it and play it.

PREREQUISITES
-------------

[](#prerequisites)

- No prerequisites
- May be More benefited Who are know Magento 2 Basic frontend , backend &amp; install local/server .
- Fundamentals of Magento 2 Development or Module Development as a first step.

Goal:
-----

[](#goal)

- Develop Full-fledged Module Step by Step .
- Magento 2 Certified [Associate](mcad.md)/[Professional](mcpd.md) Developer exam Preparation hands-on practice.

 Magento 2 SimpleNews Module Step By Step (BDCrops)
-----------------------------------------------------------------------------------

[](#-magento-2-simplenews-module-step-by-step-bdcrops-)

### [PartA: News Module Basic (Architecture &amp; Customization)](#PartA)

[](#parta-news-module-basic-architecture--customization)

- [Step 2A1: Create a directory for the module like above format](#Step2A1)
- [Step 2A2: Declare module by using configuration file module.xml](#Step2A2)
- [Step 2A3: Register module by registration.php &amp; composer.json](#Step2A3)
- [Step 2A4: Configure declarative schema (create table etc/db\_schema.xml)](#Step2A4)
- [Step 2A5: Schema whitelist (etc/db\_schema\_whitelist.json) ](#Step2A15)
- [Step 2A6: Enable the module](#Step2A6)
- [Step 2A7: Develop data &amp; schema patches(Installing &amp; upgrading data)](#Step2A7)
- [Step 2A8: Create Model News for business Logic](#Step2A8)
- [Step 2A9: Create Model's ResourceModel to handle real database transaction](#Step2A9)
- [Step 2A10: Create Model's collection class](#Step2A10)
- [Step 2A11: Setup the frontend route](#Step2A11)
- [Step 2A12: Create IndexController](#Step2A12)

### [Part B: News Module for Back End](#PartB)

[](#part-b-news-module-for-back-end)

- [Step 2B1: Setup Module's backend configuration](#Step2B1)
- [Step 2B2: Create a custom source model](#Step2B2)
- [Step 2B3: Create a role for this config section](#Step2B3)
- [Step 2B4: Set some default value for configuration options](#Step2B4)
- [Step 2B5: Create a Helper Data class](#Step2B5)
- [Step 2B6: Create the menu for Magento backend](#Step2B6)
- [Step 2B7: Create backend route file](#Step2B7)
- [Step 2B8: Update the acl.xml to add more roles](#Step2B8)
- [Step 2B9: Create layout for grid](#Step2B9)
- [Step 2B10: Create layout for Grid Container](#Step2B10)
- [Step 2B11: Create layout for ajax load](#Step2B11)
- [Step 2B12: Create news status option file](#Step2B12)
- [Step 2B13: Create News Block for backend](#Step2B13)
- [Step 2B14: Create Grid block file for Ajax load](#Step2B14)
- [Step 2B15: Create backend controller for child action class to extend](#Step2B15)
- [Step 2B16: Create Backend Action file Index.php](#Step2B16)
- [Step 2B17: Create another Action for ajax](#Step2B17)
- [Step 2B18: Create layout file simplenews\_news\_edit.xml for edit form](#Step2B18)
- [Step 2B19: Create the layout for create form](#Step2B19)
- [Step 2B20: Create a form container block](#Step2B20)
- [Step 2B21: create a block for the left-side tabs](#Step2B21)
- [Step 2B22: Create a block for Form information](#Step2B22)
- [Step 2B23: Create a block to declare the fields for the edit form](#Step2B23)
- [Step 2B24: Create a controller action for create a new News](#Step2B24)
- [Step 2B25: Create Edit Action for the Edit form](#Step2B25)
- [Step 2B26: A Save Action for the edit form](#Step2B26)
- [Step 2B27: Delete Action for the edit Form](#Step2B27)
- [Step 2B28: The mass delete action the grid list](#Step2B28)
- [Step 2B29: Backend Menu and Grid List](#Step2B29)

### [Part C : News Module for Front End](#PartC)

[](#part-c--news-module-for-front-end)

- [Step 2C1: Create Layout file for page handle](#Step2C1)
- [Step 2C2: Create another layout file by update the previous layout](#Step2C2)
- [Step 2C3: Create Block NewList file](#Step2C3)
- [Step 2C4: Create frontend template file list.phtml](#Step2C4)
- [Step 2C5: Create an abstract class by extending Magento Core Action class](#Step2C5)
- [Step 2C6: Update Index Controller by extends the abstract class 'New.php'](#Step2C6)
- [Step 2C7: Create a layout file for news detail page](#Step2C7)
- [Step 2C8: Create News view action](#Step2C8)
- [Step 2C9: create view news block](#Step2C9)
- [Step 2C10: Create news view template file](#Step2C10)
- [Step 2C11: Create CSS file for styling the frontend Page](#Step2C11)
- [Step 2C12: Create Latest New Block](#Step2C12)
- [Step 2C13: Create a Block for positioning the latest news: Left or Right](#Step2C13)
- [Step 2C14: Create the template file for Latest News](#Step2C14)
- [Step 2C15: Frontend view for the module](#Step2C15)

### [Part D : News Console/Command](#PartD)

[](#part-d--news-consolecommand)

- [Step 2D1: Adding a new command Dependency Injection](#Step2D1)
- [Step 2D2: Adding a new command class](#Step2D3)
- [Step 2D3: Adding a new command Helper class](#Step2D3)

### [Part E : Create/Set / Configure Custom Cron Jobs](#PartE)

[](#part-e--createset--configure-custom-cron-jobs)

- [Step 2E.1: Create crontab.xml ](#Step2E1)
- [Step 2E.2: defined to run the execute method of class](#Step2E3)
- [Step 2E.3: Run all cron jobs ](#Step2E3)
- [Step 2E.4: Create custom cron group ](#Step2E4)
- [Step 2E.5: Run new cron group cron jobs ](#Step2E5)

### [Part F : Create REST WEB API](#PartF)

[](#part-f--create--rest-web-api)

- [Step2F1: Web API Routes/Configuration](#Step2F1)
- [Step2F2: Define Interface– etc/di.xml](#Step2F2)
- [Step2F3: Declare API Interface](#Step2F3)
- [Step2F4: Declare Data API Interface](#Step2F4)
- [Step2F5: Create Model](#Step2F5)
- [Step2F6: Communicating with new API call](#Step2F6)
- [Step2F7: Adding ACL Web API](#Step2F7)

### [PartG: Dependency Injection configuration ](#PartG)

[](#partg-dependency-injection-configuration-)

- [Step2G.1: DI Preference,Arguments &amp; Virtual Types Implements](#Step2G1)
- [Step2G.2: DI Observer Implements](#Step2G2)
- [Step2G.3: DI Plugins (Interceptors)](#Step2G3)

### [PartH : Customization Layout Configuration &amp; JavaScript ](#PartH)

[](#parth--customization-layout-configuration--javascript-)

- [Step2H.1: Layout Configuration](#Step2H1)
- [Step2H.2: Customization JavaScript Map &amp; Mixin](#Step2H2)

### [PartI : UI Components Library](#PartI)

[](#parti--ui-components-library)

- [Step2I1: Rendering Grid(collections &amp; listing component configuration)](#Step2I1)
- [Step2I.2: Rendering Form ()](#Step2I2)

### [PartJ : Entity-Attribute-Value (EAV)](#PartJ)

[](#partj--entity-attribute-value-eav)

- [Step2J1: Rendering Grid(collections &amp; listing component configuration)](#Step2J1)
- [Step2J2: ](#Step2J2)

---

Part A : News Module for Basic  [Go to Top](#top)
----------------------------------------------------------------------------------

[](#part-a--news-module-for-basic--go-to-top)

#### Explain Magento 2 Basic Directory Structure ?

[](#explain-magento-2-basic-directory-structure-)

- app – is used for additional elements; as a rule, app contains the following subdirectories:
    - code – contains the installed modules;
    - design – contains the installed themes. The frontend themes are located at the frontend folder; themes for admin panel – in the adminhtml folder;
    - etc – contains the Magento 2 configuration files;
    - i18n – contains the installed language packs.
- bin – contains Magento file responsible for the execution of CLI-commands in Magento 2.
- dev – contains Integration and Functional test files.
- generated – utilized for generated classes in Magento 2.
- lib – contains Magento 2 libraries and non-module based code.
- phpserver – contains Router.php file, implemented to realize the built-in PHP server.
- pub – used for static files storage:
    - errors – contains files responsible for displaying errors in the browser (this behavior is by default disabled);
    - media – contains all media-files from the website;
    - static – contains the generated theme and module files.
- var – contains temporary files, like:
    - cache – contains all the cached objects, except for pages;
    - composer\_home – root directory of the installation wizard;
    - log – stores Magento 2 logs;
    - page\_cache – contains pages cached with Full Page Cache;
    - view\_preprocessed – contains minified templates and compiled LESS.
- vendor – contains core files of Magento 2. Moreover, this directory can contain the additionally installed modules. You should perform operations with components from this directory via Composer.

#### What is Model View ViewModel (MVVM) Architecture ?

[](#what-is-model-view-viewmodel-mvvm-architecture-)

[![](doc/MVVMPattern.png)](doc/MVVMPattern.png)

- Model: Holds business logic of application &amp; depends on an associated class—the ResourceModel—for database access. Models rely on service contracts to expose their functionality to other layers of application.
- View: Structure &amp; layout of what a user sees on a screen - the actual HTML. This is achieved in the PHTML files distributed with modules. PHTML files are associated to each ViewModel in the Layout XML files, which would be referred to as binders in the MVVM dialect. The layout files might also assign JavaScript files to be used in the final page.
- ViewModel: Interacts with Model layer, exposing only necessary information to View layer handled by the module’s Block classes. Note that this was usually part of the Controller role of an MVC system. On MVVM, the controller is only responsible for handling the user flow, meaning that it receives requests and either tells the system to render a view or to redirect the user to another route.

#### Magento 2 architecture is split into 4 (PDSP)layers?

[](#magento-2-architecture-is-split-into-4-pdsplayers)

[![](doc/archi_diagrams_layers_alt4.jpg)](doc/archi_diagrams_layers_alt4.jpg)

- Persistence layer: describes resource model, which is responsible for extracting and modifying data in the database using CRUD requests.Additional business logic capabilities are also implemented here, for example, data validation and database functions implementation.
- Domain layer: responsible for the business logic, which does not contain resource-specific or database-specific information. Domain layer can also include service contracts.Each data model at the level of domain layer depends on the resource model, which is responsible for accessing the database.
- Service layer: interlayer between presentation layer and domain layer. It implements service contracts, which are defined using PHP interfaces. Service contracts allow to add or change business logic resource model using dependency injection file (di.xml). Service layer is also used for granting access to API (REST/SOAP or other modules).Service interface is declared in /Api namespace of the module. Data (entity) interface is declared in /Api/Data. Data entities are data structures passed to and returned from service interfaces.
- Presentation Layer: upper layer. It contains all the View elements (including layouts, blocks, templates, css, js) and controllers.Presentation Layer usually calls service layer using service contracts. But, depending on the implementation, it may overlap with business logic.

#### Magento has 5 areas types?

[](#magento-has-5-areas-types)

- Magento Admin (adminhtml): entry point for this area is index.php or pub/index.php. The Admin panel area includes the code needed for store management. The /app/design/adminhtml directory contains all the code for components you’ll see while working in the Admin panel.
- Storefront (frontend): entry point for this area is index.php or pub/index.php. The storefront (or frontend) contains template and layout files that define the appearance of your storefront.
- Basic (base): used as a fallback for files absent in adminhtml and frontend areas.
- Cron (crontab): In cron.php, the \\Magento\\Framework\\App\\Cron class always loads the 'crontab' area. You can also send requests to Magento using the SOAP and REST APIs. These two areas:
- Web API REST (webapi\_rest): entry point for this area is index.php or pub/index.php. The REST area has a front controller that understands how to do URL lookups for REST-based URLs.
- Web API SOAP (webapi\_soap): entry point for this area is index.php or pub/index.php.

#### Module folder holds one part of the architecture, as follows?

[](#module--folder-holds-one-part-of-the-architecture-as-follows)

- Api or Api/Data: Service contracts, defining service interfaces &amp; data interfaces
- Adapter:Classes follow adapter pattern &amp; wrap around classes from third-party libraries allow to use functionality from third-party libraries in code by converting the third-party class interfaces into an interface that is expected by native code.( module-search/Adapter/)
- Block: ViewModels of our MVVM architecture
- Collector: module-deploy/Collector/Collector.php
- Command: directory is used for storing the PHP files that are responsible for console programs execution. In our case, Console/Command/ImagesResizeCommand.php processes commands for product images resizing.
- Controller: Responsible for handling the user’s flow while interacting with the system
- Config: module-deploy/Config/BundleConfig.php
- Cron: We use the directory to store the files, which are later executed on the Cron launching.
- CustomerData: directory contains PHP files responsible for processing information for sections. Magento 2 has a special functionality, which allows for processing, updating and transferring the information asynchronously.
- etc: Configuration XML files module defines itself &amp; its parts (routes, models, blocks, observers, and cron jobs) within this folder, also be used by non-core modules to override the functionality of core modules.

    - [etc/acl.xml](etc/acl.xml)
    - [etc/adminhtml/menu.xml](etc/adminhtml/menu.xml)
    - [etc/adminhtml/system.xml](etc/adminhtml/system.xml)
    - etc/{area}/routes.xml
    - etc/{area}/events.xml
    - etc/crontab/events.xml
    - etc/config.xml
    - etc/cron\_groups.xml
    - etc/crontab.xml
    - [etc/db\_schema.xml](etc/db_schema.xml)
    - [etc/di.xml](etc/di.xml)
    - etc/events.xml
    - etc/module.xml
    - etc/setup/events.xml
    - etc/webapi.xml
    - etc/webapi\_rest/di.xml
    - etc/webapi\_rest/events.xml
    - etc/webapi\_soap/events.xml [ReadDevDoc](https://devdocs.magento.com/guides/v2.3/config-guide/config/config-files.html)
- Exception: (module-sales/Exception/)
- Files: Sample file (module-inventory-import-export/Files/)
- fixtures: Sample Data module (module-sales-sample-data/fixtures/orders.csv)
- Gateway: (module-paypal/Gateway)
- Helper: Classes that hold code used in more than one application layer. For example, in the Cms module, helper classes are responsible for preparing HTML for presentation to the browser.
- i18n: Holds internationalization CSV files, used for translation
- Indexer: IndexHandler (module-inventory-indexer/Indexer)
- Model: For Models and ResourceModels
- Observer: Holds Observers, or Models which are “observing” system events. Usually, when such an event is fired, the observer instantiates a Model to handle the necessary business logic for such an event.
- Package: module-deploy/Package
- Pricing: Final price model (module-msrp-grouped-product/Pricing)
- Process: module-deploy/Process
- Plugin: directory comprises plugin files allow us to modify certain module’s functions if necessary described in the configuration file: vendor/magento/module-catalog/etc/di.xml
- SearchAdapter: module-elasticsearch/SearchAdapter
- ReportXml :vendor/magento/module-analytics/ReportXml
- Setup: Migration classes, responsible for schema &amp; data creation
- Service: \[exam\] (module-media-storage/Service/ImageResize.php,module-deploy/ or module-catalog-url-rewrite/Service/V1/StoreViewService.php )
- src : vendor/magento/magento2-functional-testing-framework/src/Magento/
- Strategy: module-deploy/Strategy
- Source: module-deploy/Source
- Test: Unit tests
- Ui: Elements such as grids &amp; forms used in admin application
- view – Layout (XML) files &amp; template (PHTML) files for front-end &amp; admin application contains template files, CSS and JS files, module media files. These files are located in subfolders depending on the area of use: adminhtml, frontend or base (common files for the administrative and frontal parts of the site). These subdirectories, in turn, including static view files, design templates, email templates, and layout files:

    - view/{area}/email – contains emails templates.
    - view/{area}/layout – contains files for layout modifications.
    - view/{area}/page\_layout – contains files for page\_layout modifications.
    - view/{area}/templates – contains files of the module templates (phtml).
    - view/{area}/ui\_component – contains XML-files of the UI module components.
    - view/{area}/ui\_component/templates
    - view/{area}/web – contains CSS, JS, static and media module files.
    - view/{area}/web/js – contains js
    - view/{area}/web/template – contains html
    - view/{area}/requirejs-config.js
- ViewModel: (module-sales/ViewModel)

### Step 2A1: Create a directory for the module like above format

[](#step-2a1-create-a-directory-for-the-module-like-above-format)

In this module, we will use `BDCrops` for Vendor name and `SimpleNews` for ModuleName. So we need to make this folder: `app/code/BDC/SimpleNews`

### Step 2A2: Declare module by using configuration file module.xml

[](#step-2a2-declare-module-by-using-configuration-file-modulexml)

Magento 2 looks for configuration information for each module in that module’s etc directory. We need to create folder etc and add module.xml:

- Create [etc/module.xml](/etc/module.xml) And the content for this file:

    Source```
    ```

    ```

    ```

In this file, we register a module with name `BDC_SimpleNews` and the version is `1.0.0`.

#### Notes\[u can skip\]:

[](#notesu-can-skip)

- Magento 2 need Two Mandatory File to run/activate Module etc/module.xml &amp; registration.php

###  Step 2A3: Register module by registration.php

[](#-step-2a3-register-module-by-registrationphp)

All Magento 2 module must be registered in the Magento system through the magento ComponentRegistrar class. This file will be placed in module root directory. In this step, we need to create this file:

- Create [registration.php](registration.php) and insert this following code into it:

    Source```
    \Magento\Framework\Component\ComponentRegistrar::register(
        \Magento\Framework\Component\ComponentRegistrar::MODULE,
        'BDC_SimpleNews', __DIR__
    );

    ```

Modules in vendor folder would update using composer And all the modules in app/code would not be updated through composer That's why when you need to override any module you add it in app/code

- Create [composer.json](composer.json) and insert this following code into it:

    Source```
    ```
    {
      "name": "bdc/module-simplenews",
      "description": "BDCrops SimpleNews module for Magento 2 extensions.",
      "type": "magento2-module",
      "version": "1.0.3",
      "license": [
          "OSL-3.0",
          "AFL-3.0"
      ],
    "authors": [{
              "name": "Abdul Matin",
              "email": "matinict@gmail.com",
    		      "company": "BDCrops Inc"
          }
      ],
    "homepage": "https://www.bdcrops.com",
      "autoload": {
          "files": [
              "registration.php"
          ],
          "psr-4": {
              "BDC\\SimpleNews\\": ""
          }
      }
    }

    ```

    ```

### Step 2A4: Configure declarative schema (create table schema Installation file)

[](#step-2a4-configure-declarative-schema-create-table--schema-installation-file)

- Create [etc/db\_schema.xml](etc/db_schema.xml) &amp; insert this following code into it:

    Source```
    ```

    ```

    ```

#### Note:

[](#note)

[Tutarials module-declarative](https://github.com/bdcrops/module-declarative)

### Step 2A5: Schema whitelist (etc/db\_schema\_whitelist.json)

[](#step-2a5-schema-whitelist-etcdb_schema_whitelistjson-)

You will not be able to run a declarative mode without creating a schema whitelist. Note: it is recommended to generate a new whitelist for every release for the double-check purposes.Before running the upgrade command you need to add your schema to db\_whitelist\_schema.json file by running the following command. For that, you need a /etc/db\_schema\_whitelist.json file that will store all the content added with declarative schema. To generate this file, run:

[![db_schema](https://github.com/bdcrops/BDC_Declarative/raw/master/view/adminhtml/web/images/whitelist.png)](https://github.com/bdcrops/BDC_Declarative/blob/master/view/adminhtml/web/images/whitelist.png)

```
php bin/magento setup:db-declaration:generate-whitelist [options]
php bin/magento setup:db-declaration:generate-whitelist --module-name=vendor_module
php bin/magento setup:db-declaration:generate-whitelist --module-name=BDC_SimpleNews

```

Now, there are db\_whitelist\_schema.json file will be create in /vendor/module/etc folder. [![db_whitelist_schema](https://github.com/bdcrops/BDC_SimpleNews/raw/master/doc/db_schema_whitelist.png)](https://github.com/bdcrops/BDC_SimpleNews/blob/master/doc/db_schema_whitelist.png)

### Step 2A6: Enable the module

[](#step-2a6-enable-the-module)

By finish above step, you have created an empty module. Now we will enable it in Magento environment.Before enable the module, we must check to make sure Magento has recognize our module or not by enter the following at the command line:

```
php bin/magento module:status

```

If you follow above step, you will see this in the result:

```
List of disabled modules:
BDC_SimpleNews

```

This means the module has recognized by the system but it is still disabled. Run this command to enable it:

```
php bin/magento module:enable BDC_SimpleNews

```

The module has enabled successfully if you saw this result:

```
The following modules has been enabled:
- BDC_SimpleNews

```

This’s the first time you enable this module so Magento require to check and upgrade module database. We need to run this comment:

```
php bin/magento setup:upgrade

```

Now you can check under `Stores -> Configuration -> Advanced -> Advanced` that the module is present.

Also you can check Database Table from PhpMyAdmin or Your Favorite tools:

[![Table db_schema](https://github.com/bdcrops/BDC_SimpleNews/raw/master/doc/dbTableCreatedDeclarativeSchema.png)](https://github.com/bdcrops/BDC_SimpleNews/blob/master/doc/dbTableCreatedDeclarativeSchema.png)

### Step 2A7: Develop data and schema patches (Insert data Installing and upgrading data)

[](#step-2a7--develop-data-and-schema-patches-insert-data-installing-and-upgrading-data)

Since in the old method, we used to write scripts in Install Schema or Upgrade schema when a table was created, but now in the new version, this will be done through Patch system.A data patch is a class that contains data modification instructions. It is defined in a /&lt;Module\_Name&gt; /Setup/Patch/Data/&lt;Patch\_Name&gt;.php file and implements \\Magento\\Setup\\Model\\Patch\\DataPatchInterface. A schema patch contains custom schema modification instructions. These modifications can be complex. It is defined in a/&lt;Module\_Name&gt;/Setup/Patch/Schema/&lt;Patch\_Name&gt;.php file and implements \\Magento\\Setup\\Model\\Patch\\SchemaPatchInterface. So to add data to the bdc\_simplenews table create AddData.php file inside folder BDC/SimpleNews/Setup/Patch/Data and write the following code

- Create [Setup/Patch/Data/AddData.php](Setup/Patch/Data/AddData.php)

    Source```
    ```

    ~~~

    ```

After define the route, the URL path to our module will be: `http://example.com/news/`

#### Note: Controllers, Routers and Responses

[](#note-controllers-routers-and-responses)

- Routers: define name for a module which we can use in the url to find the module and execute the controller action.
- Controllers:Controllers in Magento 2 differ from typical controllers in MVC applications. Magento 2 controllers are responsible for only one specific URL and contain only one execute method. This method is responsible for returning result object and occasional processing of input POST data. All controllers inherit \\Magento\\Framework\\App\\Action\\Action class. The required controller is searched in the Base Router, and then it’s called in the Front Controller.
- Responses: The controller in Magento 2 can return several response types depending on the purpose and the necessary result.
- Frontend route: Please look into the code, you will see it’s very simple to register a route. You must use the standard router for the frontend. This route will have a child which define the module for it and 2 attributes:

1. The id attribute is a unique string which will identify this route. You will use this string to declare the layout handle for the action of this module
2. The frontName attribute is also a unique string which will be shown on the url request. For example, if you declare a route like this: The url to this module should be: And the layout handle for this action is: samplenews\_controller\_action.xml So with this example path, you must create the action class in this folder: {namespace}/{module}/Controller/{Controller}/{Action}.php

### Step 2A12: Create IndexController

[](#step-2a12-create-indexcontroller)

- Factory Object We are done with creating the database table, CRUD model, resource model and collection. So how to use them?

In this part, we will talk about Factory Object for model. As you know in OOP, a factory method will be used to instantiate an object. In Magento, the Factory Object do the same thing.

The Factory class name is the name of Model class and append with the ‘Factory’ word. So for our example, we will have NewsFactory class. You must not create this class. Magento will create it for you. Whenever Magento’s object manager encounters a class name that ends in the word ‘Factory’, it will automatically generate the Factory class in the var/generation folder if the class does not already exist. You will see the factory class:

```
use BDC\SimpleNews\Model\NewsFactory;
var/generation///Model/ClassFactory.php
var/generation/BDC/SimpleNew/Model/NewsFactory.php

```

To instantiate a model object we will use automatic constructor dependency injection to inject a factory object, then use factory object to instantiate the model object.

#### Magento 2 Registry &amp; Register?

[](#magento-2-registry--register)

Magento 2 authorizes you to register global variable that supports the static registry method. Magento 1, as well as Magento 2, authorize you to register global variable that supports the static registry method. To implement that, maybe you used to work with Mage::register() and Mage::registry() in Magento 1, but now in Magento 2 platform, there is a difference in running the registry. You will be required to apply \\Magento\\Framework\\Registry, that accepts the settings and the registry of the restored data. However, first of all, you need to learn how to create or use the own custom registry and also show you how to retrieve global Magento 2 registry objects like current product, category, cms page, cms block, etc. And that is lucky because all of them will be referred here. The topic today will help you be familiar with Magento 2 registry objects.

#### How to get and set custom attribute in registry / register

[](#how-to-get-and-set-custom-attribute-in-registry--register)

```
/**
  * @var \Magento\Framework\Registry
  */

 protected $_registry;
 /**
 * ...
 * ...
 * @param \Magento\Framework\Registry $registry,
 */
public function __construct(
    ...,
    ...,
    \Magento\Framework\Registry $registry,
    ...) {
    $this->_registry = $registry;
    ...
    ...
}

 /**
 * Setting custom variable in registry to be used
 *
 */
public function setCustomVariable() {
     $this->registry->register('custom_var', 'Added Value');
}

/**
 * Retrieving custom variable from registry
 * @return string
 */
public function getCustomVariable() {
     return $this->registry->registry('custom_var');
}

```

- Create controller [Controller/Index/Index.php](Controller/Index/Index.php):

    Source```

                BDC

                Simple News
                bdc
                BDC_SimpleNews::system_config

                    General Settings

                        Enable in frontend
                        Magento\Config\Model\Config\Source\Yesno

                        Head title
                        Fill head title of news list page at here
                        required-entry

                        Lastest news block position
                        BDC\SimpleNews\Model\System\Config\LastestNews\Position

    ```

    ```

#### Note: [System configuration](https://inviqa.com/blog/how-use-system-configuration-and-helpers-magento-2) :

[](#note-system-configuration-)

System configuration values in Magento 2 are stored in the core\_config\_data database table, which is exactly the same as in Magento 1. But the xml config files differ. The system.xml is a configuration file which is used to create configuration fields in Magento 2 System Configuration. the system config file is at etc/adminhtml/system.xml

The system.xml is a configuration file which is used to create configuration fields in Magento 2 System Configuration. You will need this if your module has some settings which the admin needs to set. You can go to Store -&gt; Setting -&gt; Configuration to check how it look like.

#### Note:- [MCAD: 5.4 Set up a menu item](https://belvg.com/blog/magento-2-custom-system-configuration.html)

[](#note--mcad-54-set-up-a-menu-item)

- How do you add a new menu item to a given tab?
- How do you add a new tab to the Admin menu?

### Step 2B2:Create Custom Source Model

[](#step-2b2create-custom-source-model)

- Create file [Model/System/Config/LastestNews/Position.php](Model/System/Config/LastestNews/Position.php):

    Source```
    ```

    ```

    ```

#### Note:- 5.3 Define / identify basic terms and elements of ACL

[](#note--53-define--identify-basic-terms-and-elements-of-acl)

- How would you add a new ACL resource to a new entity?
- How do you manage the existing ACL hierarchy?

### Step 2B4: Set some default value for configuration options

[](#step-2b4--set-some-default-value-for-configuration-options)

- Create file [etc/config.xml](etc/config.xml) and insert this following code into it:

    Source```
    ```

                    1
                    BDC - Simple News
                    1

    ```

    ```

### Step 2B5: Create a Helper Data class

[](#step-2b5--create-a-helper-data-class)

#### Why need to Create Helper?

[](#why-need-to-create-helper)

Magento 2, the Helper can be called in controllers, models, views and even in other helpers. Helpers can be considered as global and always available elements. They can even be created as single objects’ instances. Besides, they can be called everywhere once you inject them in the class. Helpers are mainly created to offer methods for the most common functionalities. For instance, you can use helpers to build logs in the application of Magento. Magento 2 Helper Class includes various functions and methods which are used commonly throughout the application. All the methods which have been declared as Helpers can be called anywhere including file, model, block, controller class or from another helper in Magento 2.

#### What is Helper?

[](#what-is-helper)

In the early version of Magento 2, a Helper Factory is available, which enables developers to instantiate helper methods. Besides, you can use the below code to use ObjectManager to instantiate the Helper Factory.

```
$object_manager = \Magento\Core\Model\ObjectManager::getInstance();
$helper_factory = $object_manager->get('\Magento\Core\Model\Factory\Helper');
$helper = $helper_factory->get('\Magento\Core\Helper\Data');

```

However, this code still exist some problems. Luckly, a better concept has been introducted which is Dependency Injection in Magento 2.

Using this concept, the environment will create and provide you an object instead of instantiating it. For instance, if a class is written like the following:

```
class Helper{
   public function __contruct(Helper $xyz){
       $this->xyz= $xyz;
   }
}

```

In the Helper class constructor, an object of Helper class is auto-created and assigned the reference, $xyz. This is Dependency Injection.

Via this concept, high-value loose coupling modules together concept is provided by Magento 2. If you want to inject it into a specific class, just add an object to the constructor of it. However, you need to remember that you cannot inject one dependency twice.

- Create file: [Helper/Data.php](Helper/Data.php) and insert this following code into it:

    Source```

    ```

    ```

[![MenuLinkAdmin](https://github.com/bdcrops/BDC_SimpleNews/raw/master/doc/adminhtmlMenu.png)](https://github.com/bdcrops/BDC_SimpleNews/blob/master/doc/adminhtmlMenu.png)

### Step 2B7: Request Flow Processing / Create backend route file

[](#step-2b7-request-flow-processing--create-backend-route-file)

#### How to Create Admin route ?

[](#how-to-create-admin-route-)

This route will be same as the frontend route but you must declare it in adminhtml folder with router id is admin. File: app/code/BDC/SampleNews/etc/adminhtml/routes.xml

The url of the admin page is the same structure with frontend page, but the admin\_area name will be added before route\_frontName to recognize this is a admin router. For example, the url of admin cms page:

[http://example.com/index.php/admin/bdc\_samplenews/controller/action](http://example.com/index.php/admin/bdc_samplenews/controller/action)The controller action for admin page will be added inside of the folder Controller/Adminhtml. For example for above url:

```
{namespace}/{module}/Controller/Adminhtml/{Controller}/{Action}.php

```

- Create file [etc/adminhtml/routes.xml](etc/adminhtml/routes.xml)Purpose: The router of your module for backend will be declared here insert this following code into it:

    Source```
    ```

    ```

    ```

#### Note:

[](#note-1)

- Admin Route: This route will be same as the frontend route but you must declare it in adminhtml folder with router id is admin. /etc/adminhtml/routes.xml The url of the admin page is the same structure with frontend page, but the admin\_area name will be added before route\_frontName to recognize this is a admin router. For example, the url of admin cms page:

```
http://example.com/index.php/admin/simplenews/controller/action  {namespace}/{module}/Controller/Adminhtml/{Controller}/{Action}.php

```

### Step 2B8: Update the acl.xml to add more roles

[](#step-2b8--update-the-aclxml-to-add-more-roles)

#### How to add/Create our module to ACL role?

[](#how-to-addcreate-our-module-to-acl-role)

As in the Admin Menu and System Configuration article, you saw that we alway have a resource attribute when create it. Now we will register that resources to the system, so Magento can realize and let us set a role for them. To register the resource, we use the acl.xml file which located in

```
app/code/{namespace}/{module}/etc/acl.xml

```

#### ACL Rules for Developers?

[](#acl-rules-for-developers)

As a module developer, ACL rules present a few interesting challenges. First, there are several places that you, as a module developer, are expected to add ACL rule checks to your module. A few examples

- Every URL endpoint/controller in the admin application must implement an \_ isAllowed method that determines if a user can access the URL endpoint.
- Every Menu Item in the left hand navigation also has a specific ACL rule that controls whether or not the menu displays for the logged in user. This is often the same rule from \_ isAllowed)
- Every configuration field in System -&gt; Configuration has a specific ACL rule that controls whether or not the menu displays

Despite being required fields, there are no hard and fast rules as to how a module developer should setup and structure their own rules. Also, a module developer will likely want additional rules that are specific to their module. This article can’t answer these hard questions for you, but we will show you how to check the current user against a specific ACL rule, look up ID values for existing rules, and how to create your own tree of ACL rules.

#### Explain Magento\_Backend::admin,Id Title, sortOrder?

[](#explain-magento_backendadminid-title-sortorder)

- Magento\_Backend::admin: Our resource will be placed as child of Magento\_Backend::admin. Each resource will have an Id, title and sortOrder attribute:
- Id: attribute is the identify of this resource. You can use this when define resource in Admin menu, configuration and limit access to your module controller. This is a unique string and should be in this format: Vendor\_ModuleName::resource\_name.
- Title: attribute is the label of this resource when showing in resource tree.
- sortOrder: attribute define the position of this resource in tree.
- Open this file [etc/acl.xml](etc/acl.xml) and modify the source code into here like this:

    Source```
    ```

    ```

    ```

### Step 2B9: Create layout for grid

[](#step-2b9--create-layout-for-grid)

- Create file: [view/adminhtml/layout/simplenews\_news\_index.xml](view/adminhtml/layout/simplenews_news_index.xml) (Purpose: This file is used to declare grid container block) and insert this following code into it:

    Source```

    ```

### Step 2B10: Create layout for Grid Container

[](#step-2b10--create-layout-for-grid-container)

- Create file: app/code/BDC/SimpleNews/view/adminhtml/layout/simplenews\_news\_grid\_block.xml (Purpose: This file is used to declare the content of grid block) and insert this following code into it:

    Source```
    ```

                     newsGrid
                     BDC\SimpleNews\Model\Resource\News\Collection
                     id
                     desc
                     true
                     true

                         1

                            id
                            news

                                    Delete
                                    */*/massDelete
                                    Are you sure you want to delete?

                                */*/edit

                                    getId

                                ID
                                number
                                id
                                id

                                Title
                                title

                                Summary
                                summary

                                Status
                                status
                                options

                                action
                                Action
                                action
                                getId
                                false
                                false
                                stores
                                true

                                        Edit

                                            */*/edit

                                        id

                                col-actions
                                col-actions

    ```

    ```

### Step 2B11: Create layout for ajax load

[](#step-2b11--create-layout-for-ajax-load)

- Create file: app/code/BDC/SimpleNews/view/adminhtml/layout/simplenews\_news\_grid.xml (Purpose: This file is used to declare the content of grid when you use ajax to reload the grid) and insert this following code into it:

    Source```

    ```

###  Step 2B12: Create news status option file

[](#-step-2b12--create-news-status-option-file)

- Create file: app/code/BDC/SimpleNews/Model/System/Config/Status.php (Purpose: This file is used to get News status options) and insert this following code into it:

    Source```
    ```

    ```

### Step 2B19: Create the layout for create form

[](#step-2b19--create-the-layout-for-create-form)

- Create file: app/code/BDC/SimpleNews/view/adminhtml/layout/simplenews\_news\_create.xml and insert this following code into it:

    Source```
    ```

    ```

    ```

###  Step 2B20: Create a form container block

[](#-step-2b20--create-a-form-container-block)

- Create file: app/code/BDC/SimpleNews/Block/Adminhtml/News/Edit.php (Purpose: This is the block file of form container) and insert this following code into it:

    Source```
    ```

```

### Step 2C2: Create another layout file by update the previous layout

[](#step-2c2--create-another-layout-file-by-update-the-previous-layout)

- Create file: app/code/BDC/SimpleNews/view/frontend/layout/news\_index\_index.xml (this file will declare blocks for using in the news list page) and insert this following code into it:

```

```

### Step 2C3: Create Block News List file

[](#step-2c3--create-block-news-list-file)

- Create file: app/code/BDC/SimpleNews/Block/NewsList.php (this file will set the news data collection and declare pagination for them) and insert this following code into it:

```

```

###  Step 2C9: create view news block

[](#-step-2c9--create-view-news-block)

- Create file: app/code/BDC/SimpleNews/Controller/Index/View.php and insert this following code into it:

```

```

[![FrontendNewsDetails](https://github.com/bdcrops/BDC_SimpleNews/raw/master/doc/FrontendNewsDetails.png)](https://github.com/bdcrops/BDC_SimpleNews/blob/master/doc/FrontendNewsDetails.png)

### Step 2C12: Create Latest New Block

[](#step-2c12--create-latest-new-block)

- Open file: app/code/BDC/SimpleNews/view/frontend/layout/news\_news.xml (we will add 2 blocks to the page body) and insert this following code into it:

```

```

###  Step 2C13: Create a Block for positioning the latest news: Left or Right

[](#-step-2c13--create-a-block-for-positioning-the-latest-news-left-or-right)

- Create file: app/code/BDC/SimpleNews/Block/Lastest.php (this file will get the news data) and insert this following code into it:

```

               +

                 BDC\SimpleNews\Console\Command\NewsCreate

    ```

###  Step 2D2: Adding a new command class

[](#-step-2d2-adding-a-new-command--class)

We add the object responsible for executing the script to the class Magento\\Framework\\Console\\CommandList. The constructor of this class is simply an array where class objects are passed on in a similar manner as in the above example.

Let’s proceed to the next step – creating a class for our new command and a helper responsible for adding a new user:

- Create [Console/Command/NewsCreate.php](Console/Command/NewsCreate.php):

    Source```

                * * * * *

    ```

    ```

    Details

Here when defining the crontab for the module we need to define the group name too. Here group\_name is the name of the cron group. The group name doesn’t have to be unique and we can run the cron for one group at a time.

Here,

group id: is a cron group name. job name: is a Unique ID for this cron job. instance: is a class to be instantiated (classpath). method: is a method in job instance to call. schedule: is a schedule in cron format.

```
* * * * * command to be executed
| | | | |
| | | | +----- Day of week (0 - 7) (Sunday=0 or 7)
| | | +------- Month (1 - 12)
| | +--------- Day of month (1 - 31)
| +----------- Hour (0 - 23)
+------------- Minute (0 - 59)

```

### Step 2E.2:Defined to run the execute method of class

[](#step-2e2defined-to-run-the-execute-method-of-class)

This file contains the custom cron code and which will be executed while the cron runs in Magento 2.

- Create [Cron/AddNews.php](Cron/AddNews.php):

    Source```
    ```

            1
            4
            2
            10
            60
            600

    ```

    ```

Where:

- group\_name – Name of the custom group.
- schedule\_generate\_every – Frequency (in minutes) that schedules are written to the cron\_schedule table.
- schedule\_ahead\_for – Time (in minutes) in advance that schedules are written to the cron\_schedule table.
- schedule\_lifetime – Window of time (in minutes) that cron job must start or will be considered missed (“too late” to run).
- history\_cleanup\_every – Time (in minutes) that cron history is kept in the database.
- history\_success\_lifetime – Time (in minutes) that the record of successfully completed cron jobs is kept in the database.
- history\_failure\_lifetime – Time (in minutes) that the record of failed cron jobs is kept in the database.
- use\_separate\_process – This feature is available only for Magento 2.1 and later.

You can check your new cron group in admin panel at: Stores -&gt; Configuration -&gt; Advanced -&gt; System -&gt; Cron (Scheduled Tasks)

[![](https://github.com/bdcrops/BDC_SimpleNews/raw/master/doc/cronGroupAdmin.png)](https://github.com/bdcrops/BDC_SimpleNews/blob/master/doc/cronGroupAdmin.png)

### Step 2E.5: Run new cron group cron jobs

[](#step-2e5--run-new-cron-group-cron-jobs-)

After completing the above steps run the below SSH command in your Magento 2 installed root directory to run the Magento 2 specific group of cron jobs only.

```
php bin/magento cron:run --group="bdc_crongroup"

```

To check whether the cron is working properly, go to Database &amp; run below query.

```
SELECT * FROM `cron_schedule` where `job_code` LIKE "%bdc%"

SELECT * FROM `bdc_simplenews` ORDER BY `id` DESC

```

[![](https://github.com/bdcrops/BDC_SimpleNews/raw/master/doc/cron_cli.png)](https://github.com/bdcrops/BDC_SimpleNews/blob/master/doc/cron_cli.png)

[![](https://github.com/bdcrops/BDC_SimpleNews/raw/master/doc/cron_sampleNews.png)](https://github.com/bdcrops/BDC_SimpleNews/blob/master/doc/cron_sampleNews.png)

### Step 2E.6: Cron Job FAQ

[](#step-2e6-cron-job-faq-)

#### What is cron Job &amp; Where use in magento 2x?

[](#what-is-cron-job--where-use-in-magento-2x)

Cron job is a great feature which is used to do the specific task automatically in exact time and date without manual working. The cron job is the perfect choice to do the repeated action every date or every week.Magento 2 uses cron jobs for,

- Catalog price rules
- Newsletters
- Generating Google sitemaps
- Reindexing
- Automatic updating of currency rates
- All Magento emails (including order confirmation and transactional)
- Customer Alerts and Notifications.
- Private sales (Magento Enterprise Edition only) &amp; more.. In Magento 2, we can create crons easily and it will be listed in the database table (table name: cron\_schedule) to process our tasks in scheduled time.

#### Explain `* * * * * ` ?

[](#explain-schedule-----schedule-)

Schedule is the time the cron will run. In this example, it run in each minute.

```
* * * * * *
| | | | | |
| | | | | +-- Year              (range: 1900-3000)
| | | | +---- Day of the Week   (range: 1-7, 1 standing for Monday)
| | | +------ Month of the Year (range: 1-12)
| | +-------- Day of the Month  (range: 1-31)
| +---------- Hour              (range: 0-23)
+------------ Minute            (range: 0-59)

```

- - - - - - : it is the time the script autorun (each 1 minute)
- www-data: it is the user will run this cript
- php /home/eden/public\_html/magento2/bin/magento cron:run : the command

Part F : Create REST WEB API  [Go to Top](#top)
--------------------------------------------------------------------------------

[](#part-f--create--rest-web-api---go-to-top)

Magento 2 API framework allows developers to create new services for communicating with Magento 2 stores. It supports REST and SOAP web services and is based on CRUD operations (Create, Read, Update, Delete) and a Search Model.

#### What is Magento 2 REST API?

[](#what-is-magento-2-rest-api)

At the moment, Magento 2 uses the following three authentication methods as is described in Magento 2 REST API documentation.

- OAuth 1.0a authentication for third-party applications.
- Tokens to authenticate mobile applications.
- Admins &amp; customers authentication with login credentials.

According to the Magento 2 API documentation, these authentication methods can only access the resources assigned to them. Magento 2 API framework first checks whether the call has appropriate authorization to perform the request. The API framework also supports field filtering of API responses to preserve cellular bandwidth. Developers use Magento 2 APIs for a wide range of tasks. For instance, you can create a shopping app and integrate it with your Magento 2 store. You can also build a web app which your employee could use to help customers make purchases. With the help of APIs, you can integrate your Magento 2 store with CRMs, ERPs or POS systems.

#### How Using Magento 2 REST API?

[](#how-using-magento-2-rest-api)

Using REST API in Magento 2 is a piece of cake. But for that, you need to understand the flow to call APIs in PHP. If you want to use token-based Magento 2 REST API, first you will need to authenticate and get the token from Magento 2. Then, you will have to pass it in the header of every request you perform. To get started with the REST API in Magento 2 using token-based authentication, you will need to create a web service User Role and register that role to a new Magento 2 Admin User. Keep in mind that creating a new role and user is necessary because it’s not a good practice to use Magento Owner User in a web service.

#### Why SOAP for eCommerce?

[](#why-soap-for-ecommerce)

When it comes to e-Commerce websites, APIs play the big role of reading and writing information from and to the server. Be it a customer’s name or his already saved credit card details, every piece of information shown to the end user has to either read from or written to the web server. This is taken care by REST and SOAP APIs. REST and SOAP are models for web services, however, one that’s most recommend for eCommerce websites. Though REST is fast, efficient and simple, SOAP is standardized, secure and apt for payments.

#### How Create Web Service Role in Magento 2?

[](#how-create-web-service-role-in-magento-2)

To create a web service role in Magento 2, follow these steps:

- Login to the Magento 2 Admin Panel.
- Go to System &gt;&gt; User Roles and tap the Add New Role
- Enter the Role Name.
- In Your Password field, enter the current password of your Magento 2 Admin.
- Now, on the left side, click Role Resources.
- In the Resource Access, select only those that are required for your web service.
- Once done, hit the Save Role

#### How Create Web Service User in Magento 2?

[](#how-create-web-service-user-in-magento-2)

Now, create a new user for the newly created role through these steps:

- Go to System &gt;&gt; All Users and hit the Add New User
- Enter the required information including User Name, First and Last Name, Email, Password, etc.
- Now, on the left side, click User Role and select the newly created role.
- Once done, click the Save User

#### How Magento 2 REST API Authentication?

[](#how-magento-2-rest-api-authentication)

As I mentioned earlier, I will authenticate REST API through Token authentication. This means that I will pass a username and password in the initial connection and receive the token . This token will be saved in a variable, which will be passed in the header for further calls.

#### How Get Modules Using REST API in Magento 2?

[](#how-get-modules-using-rest-api-in-magento-2)

You can fetch almost everything using Magento 2 REST API. The List of REST APIs for Magento EE and CE is a good guide on this topic.To demonstrate the API, I am going to get all the installed modules on a Magento 2 store. Here is the script:

 Source```
  ```
