• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
Tutsplanet

Tutsplanet

Free Technical and Blogging Resources

  • Home
  • Web Hosting
  • Programming
  • Plugins
  • Twitter Trends
  • Tools
  • About Us

Programming TagsLaravel

Bind vs Singleton in Laravel. Which one to use, and when?

Nov 14, 2021 Editorial Staff Leave a Comment

Share
Tweet
Share
5 Shares

In today’s tutorial, we are discussing bind() and singleton() methods in Laravel. In general, you might have encountered this a lot while you programming in Laravel based apps.

We use bind in the event of reusable classes or objects ( the object is created each time when it is called). So each instance of the class will be different from the previous one.

Imagine you need to display product details in your application, every product detail will be different, so as the every product object. You cannot use one instance for different products. So you will have to create a new instance for every new product.

We use singleton for a class or object when we need to access the same instance throughout the application( the object is constructed only once and keeps the state throughout the execution).

So when you need a single, shared instance of class you can use singleton.

For example, in a cache class, or in a log class, you don’t need to create different objects for this type of job. Instead of that, you use the same instance throughout the application.

We will examine this with the help of an example.

Create a class in the following path app\Support\TestClass.php

<?php
namespace App\Support;

class TestClass {

    protected $counter = 0;
    /**
     * Method increments the counter 
     */
    public function increment() {
        $this->counter++;
        return $this->counter;
    }
}

Open the AppServiceProvider.php file and add the below code to register() function.

App\Providers\AppServiceProvider.php

.......
public function register() {
    $this->app->singleton(
        'test1',
        \App\Support\TestClass::class
    );

    $this->app->bind(
        'test2',
        \App\Support\TestClass::class,
    );
}
......

Go to your console and type php artisan tinker. What is a tinker?. Laravel includes a powerful REPL, called Tinker, powered by the PsySH console by Justin Hileman under the hood. The tinker console allows you to interact with your Laravel application from the command line in an interactive shell.

And try to execute the classes in there

>>> app('test1')->increment()
=> 1
>>> app('test1')->increment()
=> 2
>>> app('test1')->increment()
=> 3
>>> app('test2')->increment()
=> 1
>>> app('test2')->increment()
=> 1
>>> app('test2')->increment()
=> 1
>>>

You can see test1 class is increments the counter, and what it means is it’s not creating a new instance every time, but it uses the same instance instead.  On the other hand, the test2 class creates a new object each time, so it prints the 1 always.

In addition, you can use the bind() as a singleton() if we set the third parameter is true, which is surprising in the first place, but it’s not. You will understand this better in a minute.

Consider this example with the third parameter as true

$this->app->bind(
    'test2',
    \App\Support\TestClass::class,
    true
);

We will execute the tinker again

Check the output below
>>> app('test2')->increment()
=> 1
>>> app('test2')->increment()
=> 2
>>> app('test2')->increment()
=> 3
>>> app('test2')->increment()
=> 4
>>>

Now it’s the same as the singleton() method. Basically, Laravel actually just proxies to call a bind(). For this reason, you are receiving the same results as a singleton().

To understand more, you can examine the below code from the core Laravel file.

\Illuminate\Container\Container in vendor/laravel/framework/src/Illuminate/Container/Container.php

public function singleton($abstract, $concrete = null)
{
    $this->bind($abstract, $concrete, true);
}

You can see that singleton() calls bind() but $shared= true

Tested in version – 8.7

Thanks to this article


Editorial Staff

Editorial Staff at Tutsplanet is a dedicated team to write various tutorials about subjects like Programming, Technology and Operating Systems.

View all posts by Editorial Staff

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Quick Links

  • Top 21 Website Ideas To Make Money Online in 2021
  • A Simple YouTube Video Downloader Script in PHP
  • The 50 Most Useful jQuery Plugins for Frontend Development
  • Replace “\n” with new line characters, using Notepad++
  • Using Third-Party Libraries in Codeigniter
  • Upload Multiple Images and Store in Database using PHP and MySQL.
  • Hierarchical Tree view Category Example in Laravel
  • Laravel Image Intervention Tutorial With Example
  • How to import sql file in MySQL database using PHP?
  • Free VAT Calculator Online

Subscribe

* indicates required



Search Here

Share

   



Hot topics

  • Replace “\n” with new line characters, using Notepad++ 14 views
  • Solution: windows photo viewer opens each time save a pic file 12 views
  • Simple PHP Shopping Cart 10 views
  • A Simple YouTube Video Downloader Script in PHP 10 views
  • How to Create PDF File From HTML Form Using Fpdf? 9 views
  • All Countries SQL file with Country Codes to Download 8 views
  • How to create and download a Zip file with PHP 8 views
  • How to set up GitHub SSH in Ubuntu with example 7 views
  • How to enter new line in Microsoft Teams? 7 views
  • Laravel Eloquent Select Column as Alias 7 views

Categories

  • Design & Development
  • Drupal
  • Facebook
  • General
  • How To
  • ios
  • Javascript
  • Linux
  • Magento
  • Marketing
  • News
  • PHP
  • Plugins
  • Programming
  • Snippets List
  • Social Media
  • Softwares
  • Themes
  • Tips
  • Wordpress
  • YouTube























Copyright © 2023 · Planet on Genesis Framework · Powered By BunnyCDN . Network wallpapernoon.com