Sunday 11 June 2023

Overview


Queue means whatever comes first goes out first means first in first out is called the queue. It maintains the sequence.

When the task is time consuming or long running task like sending emails to all users, importing CSV to the database, multiple images upload in the server, etc. So we are using the queue and jobs.

Laravel also connects queues with several drivers like database, Redis, Amazon, Beanstalkd, etc. The Drives are used to store the list of tasks.

Topics

  1. Configure the queue and jobs
  2. Jobs
  3. Dispatching the job

Configure the queue

  • After setting up the laravel project first in the config folder queue.php file there. In this file connection array queue is configure.


  • In this connection array, we using the queue for database and table=> jobs jobs table is created and retry_after=>90 if any queue is failed so after 90 seconds it retry and the queue => ‘default’ is the name of the queue

  • After in the terminal fire the command php artisan queue:table so the one migration file is created like 2022_05_17_051432_create_jobs_tbl_table.php

  • After run the php artisan migrate command to migrate the jobs table.
  • Here all the queue configuration is done.

Jobs

  • After configuring the queue we create the jobs using the php artisan make:job JobName.

  • The jobs are created under the app/Jobs folder and the job must implement the shouldqueue interface and also use the trait file Dispatchable, InteractsWithQueue, Queueable, SerializesModels in the queue class.

  • In this created queue there are __construct and handle functions. Handle function we are writing the over logic the same as the controller function and here if we want to pass the data so we use the pass the argument to the constructor.




Dispatching the Jobs

        There are two method to dispatch the jobs

    1. using the dispatch global helper like dispatch(new JobName);
    2. using the dispatch static method like JobName::dispatch();

  • Job is run in the background so we can not see and browser response is very fast.

  • If we are dispatching the job by giving a particular time means giving the some delay into over jobs so JobName::dispatch()->deley(now()->addSeconds(20)); so the job will be executed after the 20 seconds and if not passing the any second by default job will execute the 1 second.

  • If we are passing some data into the job so we in the JobName::dispatch($some_data) and the job class pass the variable into the __constuct method if not pass then show the error.

  • And in the terminal fire, the command php artisan queue:work otherwise the jobs is not run and not getting the output.


  • If any jobs will be fail so in the failed_jobs table exception column show why the jobs are failing in the below image.

  • In the terminal display the failed jobs like the below:-


  • If we want to remove all failed jobs in failed_jobs table so we fire the php artisan queue:flush so it removes all failed jobs otherwise when fire the php artisan queue:work command it will run the again failed job.

  • Laravel by default 60 second a maximum execution time provide so if the task time takes more than in the jobs class we add the property like public $timeout = 1200; so the jobs will not be terminated.

  • After all, jobs run successfully we need to inform the user or send a message like your csv files data insert successfully.
NOTE: when we change the jobs code so every time we need to clear the cache otherwise it run from the cache and display the error.

php artisan config:cache
php artisan cache:clear
or php artisan o:c (optimize the cache)

Conclusion

  • Laravel queues are very useful to run the application smoothly.

  • In our application the task is heavy and it takes time until the user can not wait for the task to be completed. Here it allows the user to perform any other task and the process is done without the user interrupt and background.

  • When the task is very heavy (ex. upload 1 million records into the database) create big jobs into smaller and create the job batching.

  • You can download the one demo code for creating send email to users when add the post click here to download. Hope this blog is helpful for a basic understanding of Laravel queues and jobs.

Laravel 10: New Features

Overview


Laravel is one of the most famous and extensively employed for developing web applications, which is open-source in nature. Its popularity is because of its easy use, clear and simple documentation, and huge and helping community of developers. Laravel version 10 offers a range of new features and functionality that simplifies web application development.

What are the new features in Laravel 10?


A few new features added in Laravel version 10 are:

  1. Improved performance: Laravel 10 offers improved speed and efficiency compared to earlier versions, which enables your web applications to better handle increased traffic and requests.
  2. Time Testing Helpers: Laravel 10 includes time-testing helpers that allow developers to easily test time-sensitive code by manipulating the time in a test environment.
  3. Improved Routing Speed: The routing system in Laravel 10 has significantly improved routing performance, especially for applications with an extensive number of routes.
  4. Blade Component Attribute Improvements: Laravel 10 includes improvements to Blade component attributes that allow developers to easily pass data between components.
  5. New Rate Limiting Middleware: Laravel 10 includes a new rate-limiting middleware feature that can be used to restrict the number of requests sent to an API endpoint in an application.
  6. Custom Casts Improvements: Laravel 10 includes improvements to custom casts that allow developers to define custom data types for model attributes.
  7. Model Validation Improvements: Laravel 10 includes improvements to model validation that allow developers to validate model data without the need for a separate request class.
  8. Improved Testing Performance: Laravel 10 includes improvements to the testing framework that can significantly improve the speed of unit tests.

Saturday 10 June 2023

Do you know What is Web 4.0?

Introduction

Did you know that an average individual spends 7-6.50 hours daily on the internet. Before the 1980s the internet did not receive any sort of attention, it was between 1985-95 that experts observed the massive rise in the use of the internet. People started exploring the world wide web more, which Tim Bereners Lee developed in 1989. Prior to those innovative developments, the internet was solely used for military purposes.

“At the core human civilizations are explorers, we travel space, depth of the sea, and even the unknowns of the world that we cannot comprehend. So why should we back down without exploring the digital world that we created”.

A digital world: the World Wide Web (WWW) is a network of interconnected systems or devices. It allows people to gain knowledge and share information, send messages, socialize, and perform tasks that were quite complex before its introduction.
As the use of the Web grew both in terms of commercial and personal aspects, scientists were willing to integrate upgrades that would bring value to users. Let’s have a look at one of the most groundbreaking upgrades that the World Wide Web received recently. The Web 4.0!

Trivia – Did you know the first ever website that was launched on the internet was named “The World Wide Web Project”. Launched from the facility contributing to Nuclear Research, in Europe it was about how to use the W3”


Topics

  1. What is Web 4.0?
  2. What are the key contributing technologies?
  3. Industries ready to explore business opportunities

What is Web 4.0?

While exploring the next generation of the internet, we found the idea behind upgrading the web is to make information more accessible, interactive, and personalized. To understand more clearly one needs to perceive what parameters Web 3.0 functions. Here the parameters are technologies that contribute to developing primary attributes of web3.0. The technologies need to unlock the potential as well as establish decentralized, transparent, and immersive qualities of the web.

So how do experts plan to go a step further in terms of digitalization? Well again the answer is innovating with the technology contributing to develop the next generation of internet. The list of technology consists of blockchain, Artificial Intelligence, AR/VR, IoT, and Big Data. At the end of the day the development will highly require these technologies to synergize and provide a more sustainable approach.

Trivia – Do you know there is a nickname for Web 4.0, its ‘Symbiotic Web’, where symbotic is derived from symbiosis. For the technology it means establishing a multiway interactive connection between machines and living organisms.

The features of web 4.0 are still uncertain but it will highly revolve around user generated content made more accessible. It will behave like an intelligent entity of automated tasks performing inhuman functions. Since the primary practicality of the internet was empowering machines to communicate with each other. Web 4.0 is going to diminish the boundaries between human and technology as well as machines even further.

Suspected Features of Web 4.0:
  • To establish a symbiotic connection between humans and tech-enabled machines.
  • The primary advantage would be ultra-progressive internet speed and low latency.
  • The tech stack would consist of AI & ML, VR, AR & XR, Blockchain, IoT, and Big Data.
  • It will improve interactivity, a mechanism for sharing information, and personalization.
  • Unbolting the possibilities of co-creation, self-learning, and integration.

Lastly, it will allow machines to interpret data on an intelligent and semantic level.

As you can see Web 4.0 is quite different from Web 3.0 and Web 2.0 on numerous fundamental levels. The information will be accessed and stimulated in diverse ways through various means of technology. So talking about technologies let's list them down to understand their participation in Web 4.0 in better terms.

What are the key contributing technologies?

The feasibility of Web 4.0 depends upon the technologies that experts are going to use. Be it IoT to gather the data in an innovative or Augmented Reality where digital visualization looks surreal. Technology has always been a significant provider of stepping stones for innovative solutions to progressively modernize.

Artificial Intelligence A web that has conversational qualities to understand its user better and adapt faster decision making practices. The practical implementation of artificial intelligence requires a massive pool of data to understand the basic requirements of people. And an interconnected network of devices is the best practice to direct that surmounting data flow adequately. Through artificial intelligence, users can experience a more personalized web search experience. Google is recently working on a project named “Magi ” that will provide a highly immersive and extensive experience that we are talking about.AI will benefit our information sourcing methods by acting as an agent for performing following tasks such as self-learning, adapting, and faster decision making. This will funnel down search results that are highly dependent on the users’ prerequisites. It’s like a universal AI assistant bot, helping you every day by providing recommendations based on the most optimum results. Quite amazing right.

IoT Yes I can gather information and bridge the gap. The gap between the massive pool of information and humans, but there is another technology that is better than AI to gather information. To understand, assume you need to buy the best bread in town. Artificial intelligence can present your options from its search result of “Top bakeries in the town”. Here IoT goes a step further to determine and make sure that the bakery is actually viable for that search result. IoT means an interconnected system of devices and living organisms or things. Using IoT data is calculated with sensors. If the bakery uses a particular type of electronic sensor that directly feeds the data back to the AI source that is providing your instantaneous information, voila! The results will be authentic and highly personalized.

Blockchain In today’s world the internet pool is overflowing with massive amounts of data. Also frequently it has been factually determined that data is the new currency. Data from various sources like social media, personal space, commercial space, etc is up in the cloud. To validate the ownership of that data helps us in numerous ways. This is where blockchain technology comes into play. Establishing a decentralized network that can be integrated with Web 4.0 allows us to share information without worrying about information theft and impersonation.

BCIs Another means of collecting data to raise the bar of hyper-personalization is through Brain computer interfaces (BCIs) or Smart Brain. Through neuro implants, experts can link us to the devices we would like to control. Sounds amazing to accumulate such personal and deep data but it’s a big maybe. It will require a regulatory body and hence the use of blockchain that will validate the ownership. That makes sense right. A group of scientists have already started to research BCIs on an all-embracing level. They even started to enroll patients for trials, but their government bodies have put a stoppage on projects related to the research.

Metaverse So far we learned how the Web is important for sharing and gathering information. But to present the information in the best way possible. Creating an immersive experience, and conveniently allowing the user to understand the topic in depth is the priority of Web results. A digital universe that is made of data stimulating real-life events, scenarios, and circumstances. The universe conveys data at lightning speed and through immersive characteristics it helps the user to comprehend infuriating things at deeper levels. Metaverse will be a huge step towards enabling Web 4.0 to become more personalized and comprehensive.

Trivia – Soon technologies like low-band 5G, Low Earth Orbit (LEO) Satellite, DOCSIS 3.1, and G. fast will be able to provide us low-latency and high speed internet connectivity all over the world.

Industries ready to explore business opportunities

The iteration of developments that we have seen in technologies have leveled the expectations we once could only imagine. The time is right, experts say. Synergizing technologies will unveil unprecedented potential for many businesses and bring value to them.
Soon there will be new services introduced as these integration of technologies will give birth to new business possibilities. AI and Automation will take over many industry niches and blockchain could disrupt the financial system. IoT will basically at core change how we utilize devices and machine technology currently. All through connected using instantaneous data processing and a more versatile generation of Web.

On commercial terms Web 4.0 Technology will also change how businesses operate. From board meetings & development process to marketing it will revamp everything. Organizations will be able to understand their clients and users competently. For example it will completely change the case study for making a gaming app.

Trivia – Do you know only 64% of global businesses have their own website and out of the rest 35% of them think their business services are limited or too small to have a website of their own.


Conclusion

Web 4.0 is going to revamp how businesses and industries function using digital tools and software. It will bring forth ‘The Internet of Business Possibilities’. Consisting abilities to integrate technologies and provide benefits like: RPA, Immersive data visualization, unorthodox content generation, etc.

Sure it will take some time for people to get adapted and learn about Web 4.0. But once acquainted with the features and functionalities, we are pretty sure that it would revamp the fundamentals of digitalization.

“The introduction of Web 4.0 will be like a crack in the glass that was separating us from the digital world of marvelous innovations”

Wednesday 16 December 2015

Magento 2 - Get Category, Products and Customer data using outside script (Programatically get & edit data)

First Create scripts/abstract.php file and add below code

<?php
use \Magento\Framework\AppInterface as AppInterface;
use \Magento\Framework\App\Http as Http;

use Magento\Framework\ObjectManager\ConfigLoaderInterface;

use Magento\Framework\App\Request\Http as RequestHttp;
use Magento\Framework\App\Response\Http as ResponseHttp;
use Magento\Framework\Event;
use Magento\Framework\Filesystem;
use Magento\Framework\App\AreaList as AreaList;
use Magento\Framework\App\State as State;

abstract class AbstractApp implements AppInterface

{
    public function __construct(
        \Magento\Framework\ObjectManagerInterface $objectManager,
        Event\Manager $eventManager,
        AreaList $areaList,
        RequestHttp $request,
        ResponseHttp $response,
        ConfigLoaderInterface $configLoader,
        State $state,
        Filesystem $filesystem,
        \Magento\Framework\Registry $registry
    ) {
        $this->_objectManager = $objectManager;
        $this->_eventManager = $eventManager;
        $this->_areaList = $areaList;
        $this->_request = $request;
        $this->_response = $response;
        $this->_configLoader = $configLoader;
        $this->_state = $state;
        $this->_filesystem = $filesystem;
        $this->registry = $registry;
    }

    public function launch()

    {
        $this->run();
        return $this->_response;
    }

    abstract public function run();


    public function catchException(\Magento\Framework\App\Bootstrap $bootstrap, \Exception $exception)

    {
        return false;
    }
}
?>

For category Data:

create scripts/categoryData.php and add below code for get category data and edit it programetically.

<?php
require dirname(__FILE__) . '/../app/bootstrap.php';
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
require dirname(__FILE__) . '/abstract.php';

class CategoriesDataApp extends AbstractApp
{

    public function run()
    {
        $this->_objectManager->get('Magento\Framework\Registry')
            ->register('isSecureArea', true);

        $category = $this->_objectManager->create('\Magento\Catalog\Helper\Category');
        $_categories = $category->getStoreCategories();
        foreach($_categories as $cat){
            $_category = $this->_objectManager->create('\Magento\Catalog\Model\Category');
            $_category = $_category->load($cat->getId());
            $_subcategories = $_category->getChildrenCategories();
            if (count($_subcategories) > 0){
                echo $_category->getId().'=>'.$_category->getName().'<br/>';      
                foreach($_subcategories as $_subcategory){
                     echo "sub category: ".$_subcategory->getId().'=>'.$_subcategory->getName().'<br/>';
                }
            }
        }
        
        /* for load Specific category uncomment below code */
        //$_category = $this->_objectManager->create('\Magento\Catalog\Model\Category');
        //$_category = $_category->load(4); // your category Id
        //echo '<pre>';print_r($category->getData());
        //$category->delete();
    }
}

/** @var \Magento\Framework\App\Http $app */
$app = $bootstrap->createApplication('CategoriesDataApp');
$bootstrap->run($app);
?>

Then just run command like php scripts/categoryData.php or direct run categoryData.php in your browser.

For Product Data:

create scripts/productData.php and add below code for get category data and edit it programetically.

<?php
require dirname(__FILE__) . '/../app/bootstrap.php';
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
require dirname(__FILE__) . '/abstract.php';

class ProductsDataApp extends AbstractApp
{

    public function run()
    {
        $this->_objectManager->get('Magento\Framework\Registry')
            ->register('isSecureArea', true);

        $products = $this->_objectManager->create('\Magento\Catalog\Model\Product');
        
        $products = $products->getCollection()
                    ->addAttributeToFilter('type_id', 'simple')
                    ->addAttributeToSelect('*')
                    ->load();
         foreach($products as $product)
         {
            echo $product->getId().'=>'.$product->getName().'=>'.$product->getData('price').'<br/>';
            
            $_product = $this->_objectManager->create('\Magento\Catalog\Model\Product')->loadByAttribute('entity_id',$product->getId());
            
         }
        
    }
}

/** @var \Magento\Framework\App\Http $app */
$app = $bootstrap->createApplication('ProductsDataApp');
$bootstrap->run($app);
?>

Then just run command like php scripts/productData.php or direct run productData.php in your browser.

For Customer Data:

create scripts/customerData.php and add below code for get category data and edit it programetically.

<?php
require dirname(__FILE__) . '/../app/bootstrap.php';
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
require dirname(__FILE__) . '/abstract.php';

class CustomersDataApp extends AbstractApp
{

    public function run()
    {
        $this->_objectManager->get('Magento\Framework\Registry')
            ->register('isSecureArea', true);

        $customers = $this->_objectManager->create('\Magento\Customer\Model\Customer');
        $customers = $customers->getCollection();
        
        foreach($customers as $customer)
        {
            //echo '<pre>';print_r($customer->getData());
            echo $customer->getId().'=>'.$customer->getName().'<br/>';    
            //$_customer = $this->_objectManager->create('\Magento\Customer\Model\Customer')->load($customer->getId()); /// Customer Object for change data or load Customer
        }
        
    }
}

/** @var \Magento\Framework\App\Http $app */
$app = $bootstrap->createApplication('CustomersDataApp');
$bootstrap->run($app);
?>

Then just run command like php scripts/customerData.php or direct run customerData.php in your browser.

Hope this will help you, Thank you.

Thursday 3 July 2014

Date Picker in any form in Magento

open page.xml and put below code in 

<block type="page/html_head" name="head" as="head">between</block>

<action method="addItem"><type>js_css</type><name>calendar/calendar-win2k-1.css</name><params/><!--<if/><condition>can_load_calendar_js</condition>--></action>
<action method="addItem"><type>js</type><name>calendar/calendar.js</name><!--<params/><if/><condition>can_load_calendar_js</condition>--></action>
<action method="addItem"><type>js</type><name>calendar/calendar-setup.js</name><!--<params/><if/><condition>can_load_calendar_js</condition>--></action>

<block type="core/html_calendar" name="head.calendar" as="calendar" template="page/js/calendar.phtml"></block>

now put below code where you want to show calendar:

<div class="field">
  <label for="delivery_date"><?php echo $this->__('Delivery Date') ?></label>
  <div class="input-box">
      <input type="text" id="_dob" name="delivery_date" class="input-text required-entry" /><em>*</em>
      <img title="Select date" id="_dob_trig" src="<?php echo $this->getSkinUrl('images/calendar.gif');?>" class="v-middle" />
   </div>
</div>

<script type="text/javascript">
//<![CDATA[
Calendar.setup({
inputField : '_dob',
ifFormat : '%m/%e/%y',
button : '_dob_trig',
align : 'Bl',
singleClick : true
});
//]]>
</script>

Saturday 31 May 2014

Programmatically get search result in magento

Below code use for get search result programetically

$searchText = 'mobile';
$query = Mage::getModel('catalogsearch/query')->loadByQueryText($searchText);
        $query->setStoreId(1);
        $query = Mage::getModel('catalogsearch/query')->setQueryText($searchText)->prepare();
        $fulltextResource = Mage::getResourceModel('catalogsearch/fulltext')->prepareResult(
                Mage::getModel('catalogsearch/fulltext'), 
                $searchText, 
                $query
                );
        $collection = Mage::getResourceModel('catalog/product_collection');
        $collection->getSelect()->joinInner(
                    array('search_result' => $collection->getTable('catalogsearch/result')),
                    $collection->getConnection()->quoteInto(
                        'search_result.product_id=e.entity_id AND search_result.query_id=?',
                        $query->getId()
                    ),
                    array('relevance' => 'relevance')
                );
using above code you will get your search result programetically in magento where $searchText is your search value.

Hope this code help you,
Thank you.

Tuesday 21 August 2012

Magento - Creating and Showing a static block in Frontend

The content of the blocks are created and modified from Magento Admin panel which can be placed on one or multiple pages. To create a static block you can follow some simple steps which are given bellow.

Creating a Static Block:


A. Go to the Magento Admin panel and then select the  CMS -> Static Blocks.
B. Then Click on the “Add New Block” button from the right top .
C. Now fillup the following fields:
  1. Block Title: Give the Name of the static block here. This will not show on the frontend.
  2. Identifier: Give the id of this block. It used as reference of this block, when adding to a template file or CMS page.
  3. Status: Its define visibility of this static block on the frontend.
  4. Content: Content of static block can be plain text, HTML code and Javascript. PHP code can’t use in this area.
D. After fillup all fields then click on “Save Block” button from the right top .

Showing a Static Block in Frontend:


A static block can be added to display on the frontend by some different ways which are discribed bellow:

1. Adding a static block to a CMS page From the Magento admin:
Go to CMS > Pages and click on a pre-existing page or create a new page where you want to show your static block.
Now use the following code in the Content field of the CMS page:

{{block type="cms/block" block_id="your_block_identifier" template="cms/content.phtml"}}

2. Adding a static block by using template phtml file:
Open your phtml file where you want to add the static block.
For Example: /app/design/frontend/your-instance-name/your_theme/template/callouts/right_col.phtml
Then you can use the following code in your phtml file to show the content of your ststic block:

<?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('your_block_identifier')->toHtml() ?>




3. Adding a static block by using XML layout file:
Use the following code to show the content of static block by using Layout XML file:


<reference name="content/left/right">
       <block type="cms/block" name="your_block_name" before="-">
        <action ethod="setBlockId"><block_id>your_block_identifier</block_id></action>
      </block>
 </reference>


Note: You can use the above code to show the block content in specific page by using “ Layout Update XML ” field of CMS page.
To do this go: CMS -> pages from your magento backend. Then click on on that page where you want to show the static block.
Then click on Design tab from left panel like:

Now Past the above code in Layout Update XML  field.
here i wrote <reference name=”content/left/right”> in code. You must use only one like- content / left or right as your reference name.