Chapter 7. Backend Development

Backend development is a term that is most commonly used to describe work closely related to the server side. This usually implies the actual server, application code, and the database. For example, if we open a storefront of a web shop, add a few products to the cart, and then check out, the application will store the information provided. This information is managed on a server with a server-side language, such as PHP, and then saved in a database. In Chapter 4, Models and Collections, we took a look at the backbone of backend development. In this chapter, we will explore other backend-related aspects.

We will use the Foggyline_Office module that was defined in one of the previous chapters as we go through the following topics:

  • Cron jobs
  • Notification messages
  • Sessions and cookies
  • Logging
  • The profiler
  • Events and observers
  • Caches
  • Widgets
  • Custom variables
  • i18n (internationalization)
  • Indexers

These individual isolated units of functionality are mostly used in everyday backend-related development.

Cron jobs

Speaking of cron jobs, it is worth noting one important thing. A Magento cron job is not the same as an operating system cron job. An operating system cron is driven by a crontab (short for cron table) file. The crontab file, is a configuration file that specifies shell commands that need to be run periodically on a given schedule.

A Magento cron job is driven by a periodic execution of PHP code that handles entries in the cron_schedule table. The cron_schedule table is where Magento cron jobs are queued once they are picked up from the individual crontab.xml file.

The Magento cron jobs cannot be executed without the operating system cron job being set to execute the php bin/magento cron:run command. Ideally, an operating system cron job should be set to trigger Magento's cron:run every minute. Magento will then internally execute its cron jobs according to the way an individual cron job is defined in the crontab.xml file.

To define a new cron job in Magento cron, we first need to define a crontab.xml file in the module. Let's create a app/code/Foggyline/Office/etc/crontab.xml file with the following content:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation= "urn:magento:module:Magento_Cron:etc/crontab.xsd">
    <group id="default">
        <job name="foggyline_office_logHello" instance= "FoggylineOfficeModelCron" method="logHello">
            <schedule>*/2 * * * *</schedule>
        </job>
    </group>
</config>

Note that the XSD schema location points to crontab.xsd from within the Magento_Cron module.

The id attribute of a group element is set to the default value. In its modules, Magento defines two different groups, namely default and index. We used the default value, as this is the one that gets executed when the standard php bin/magento cron:run command is triggered on the console.

Within the group element, we have individual jobs defined under the job element. The job element requires us to specify the name, instance, and method attributes. The name attribute has to be unique within the group element. The value of the instance and method attributes should point to the class that will be instantiated and the method within the class that needs to be executed.

The schedule element nested within the cron job specifies the desired time of job execution. It uses the same time expression as that of the entries in an operating system crontab file. The specific example that we will look at defines an expression (*/2 * * * *) that is executed every two minutes.

Once we have defined the crontab.xml file, we need to define the FoggylineOfficeModelCron class file, as follows:

namespace FoggylineOfficeModel;

class Cron
{
    protected $logger;

    public function __construct(
        PsrLogLoggerInterface $logger
    )
    {
        $this->logger = $logger;
    }

    public function logHello()
    {
        $this->logger->info('Hello from Cron job!');
        return $this;
    }
}

The preceding code simply defines a logHello method used by the cron job. In the logHello method, we used the logger method that was instantiated via the constructor. The logger method will make a log entry in the var/log/system.log file once it is executed.

Once the command is executed, you will see the Ran jobs by schedule message in the console. Additionally, the cron_schedule table should get filled with all the Magento cron jobs that were defined.

At this point, we should trigger the php bin/magento cron:run command in the console.

The cron_schedule table contains the following columns:

  • schedule_id: The auto-increment primary field.
  • job_code: The value of the job name attribute, as defined in crontab.xml file, which equals to foggyline_office_logHello table in our example.
  • status: Defaults to the pending value for the newly created entries in the table and allows for a pending, running, success, missed or error value. Its value changes as the cron job traverses through its life cycle.
  • messages: Stores the possible exception error message if the exception has occurred during a job's execution.
  • created_at: The timestamp value that denotes when a job was created.
  • scheduled_at: The timestamp value that denotes when a job was scheduled for execution.
  • executed_at: The timestamp value that denotes when a job's execution started.
  • finished_at: The timestamp value that denotes when a job has finished executing.

Unless we have already set the operating system cron to trigger the php bin/magento cron:run command, we need to trigger it on our own a few times every two minutes in order to actually execute the job. The first time a command is run, if the job does not exist in the cron_schedule table, Magento will merely queue it, but it won't execute it. The subsequent cron runs will execute the command. Once we are sure that the cron job entry in the cron_schedule table has the finished_at column value filled, we will see an entry that looks like [2015-11-21 09:42:18] main.INFO: Hello from Cron job! [] [] in the var/log/system.log file.

Tip

While developing and testing cron jobs in Magento, we might need to truncate the cron_schedule table, delete Magento's var/cache value, and execute the php bin/magento cron:run command repetitively until we get it tested and working.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.1.239