Advanced Container Package for Laravel

Laravel Enhanced Container

This package provides syntax sugar for the Laravel container calls and bindings, automatic resolution of bound implementation, method forwarding, and an enhanced version of the Laravel method binding feature.

The package requires PHP 8.0 and Laravel 8.x. Support for future versions of PHP & Laravel will be provided.

Installation

You can install the package via composer:

composer require michael-rubel/laravel-enhanced-container

Usage

Basic binding with new syntax

bind(ServiceInterface::class)->to(Service::class);

As singleton:

bind(ServiceInterface::class)->singleton(Service::class);

As scoped instance:

bind(ServiceInterface::class)->scoped(Service::class);

Contextual binding with new syntax

bind(ServiceInterface::class)
   ->contextual(Service::class)
   ->for(ClassWithTypeHintedInterface::class);

As variadic dependency:

bind(ServiceInterface::class)
   ->contextual(
       fn ($app) => [
           $app->make(Service::class, ['param' => true]),
           $app->make(AnotherServiceSharingTheSameInterface::class),
       ]
   )
   ->for(ClassWithTypeHintedInterface::class);

As primitive:

bind('$param')
   ->contextual(true)
   ->for(ClassWithTypeHintedPrimitive::class);

Contextual method binding with input parameter interception

Assuming that is your function in the service class:

class Service
{
    public function yourMethod(int $count): int
    {
        return $count;
    }
}

Perform the call to your service through container:

call(Service::class)->yourMethod(100)

You can pass it as $this or basic class object too:

call(new Service())->yourMethod(100)

Then override the method behavior in any place of your app:

bind(Service::class)->method()->yourMethod(function ($service, $app, $params) {
    return $service->yourMethod($params['count']) + 1;
});

Alternative syntax:

bind(Service::class)->method('yourMethod', function ($service, $app, $params) {
    return $service->yourMethod($params['count']) + 1;
});

The result next call: 101

You can easily mock the methods in your tests as well, and it counts as code coverage. đŸ˜‰

For example:

bind(ServiceInterface::class)->to(Service::class);
bind(ServiceInterface::class)->method(
    'externalApiRequestReturnsFalse',
    fn () => false
);

$service = call(ServiceInterface::class);

$call = $service->externalApiRequestReturnsFalse();

$this->assertFalse($call);

Remember that you need to use call() to method binding to work. It returns the instance of CallProxy. If you rely on interfaces, the proxy will automatically resolve bound implementation for you, no need to do it manually.

Optionally, if you want to easily wrap all your class constructor's dependencies to CallProxy, you can use BootsCallProxies trait and then call $this->bootCallProxies() in your constructor. It will bootstrap the proxy class property that utilizes Laravel's native Fluent object. What it would look like:

use MichaelRubel\EnhancedContainer\Traits\BootsCallProxies;

class AnyYourClass
{
    use BootsCallProxies;

    /**
     * @param ServiceInterface $service
     */
    public function __construct(
        private ServiceInterface $service
    ) {
        $this->bootCallProxies();
    }

    /**
     * @return object
     */
    public function getProxiedClass(): object
    {
        return $this->proxy->service; // your proxied service
    }

    /**
     * @return object
     */
    public function getOriginal(): object
    {
        return $this->service; // your original is still available
    }
}

Method forwarding

This feature automatically forwards the method when it doesn't exist in your base class to another class, if the namespace/classname structure is met.

Usual use case: if you have some kind of Service or Domain, which contains business or application logic, then some kind of Repository or Builder, which contains your database queries, but you don't want your controllers (or View/Livewire components) to be dependent on the repositories directly, and don't want to write the "proxy" methods in the Service that references the Repository when it comes to just fetch the data without any additional operations.

To enable this feature, publish the config:

php artisan vendor:publish --tag="enhanced-container-config"

Then turn forwarding_enabled option on and set the class names that met your application structure.

Assuming your structure is:

Logic:
- App/Services/Users/UserService
Queries: 
- App/Repositories/Users/UserRepository

Then your classes:

class UserService
{
    public function someMethod(): bool
    {
        return true;
    }
}

class UserRepository
{
    public function yourUser(): bool
    {
        return true;
    }
}

Then call the method to fetch the user:

call(UserService::class)->yourUser()

The result will be true despite the method is missing in UserService. If you put the same method in the UserService, it will fetch the result from the service itself.

  • Note: if you use PHPStan/Larastan you'll need to add the @method docblock to the service to make it static-analyzable, otherwise it will return an error that the method doesn't exist in the class.

Testing

composer test

ToDo:

  • optional feature to be able to run previous bound method in the chain.

Download Details:
Author: michael-rubel
Download Link: Download The Source Code
Official Website: https://github.com/michael-rubel/laravel-enhanced-container 
License: MIT
 

#laravel #php #webdev

What is GEEK

Buddha Community

Advanced Container Package for Laravel
Seamus  Quitzon

Seamus Quitzon

1595201363

Php how to delete multiple rows through checkbox using ajax in laravel

First thing, we will need a table and i am creating products table for this example. So run the following query to create table.

CREATE TABLE `products` (
 `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
 `description` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
 `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
 `updated_at` datetime DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

Next, we will need to insert some dummy records in this table that will be deleted.

INSERT INTO `products` (`name`, `description`) VALUES

('Test product 1', 'Product description example1'),

('Test product 2', 'Product description example2'),

('Test product 3', 'Product description example3'),

('Test product 4', 'Product description example4'),

('Test product 5', 'Product description example5');

Now we are redy to create a model corresponding to this products table. Here we will create Product model. So let’s create a model file Product.php file under app directory and put the code below.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $fillable = [
        'name','description'
    ];
}

Step 2: Create Route

Now, in this second step we will create some routes to handle the request for this example. So opeen routes/web.php file and copy the routes as given below.

routes/web.php

Route::get('product', 'ProductController@index');
Route::delete('product/{id}', ['as'=>'product.destroy','uses'=>'ProductController@destroy']);
Route::delete('delete-multiple-product', ['as'=>'product.multiple-delete','uses'=>'ProductController@deleteMultiple']);

#laravel #delete multiple rows in laravel using ajax #laravel ajax delete #laravel ajax multiple checkbox delete #laravel delete multiple rows #laravel delete records using ajax #laravel multiple checkbox delete rows #laravel multiple delete

Gordon  Taylor

Gordon Taylor

1614840465

How to Create User Authentication in Laravel 8 Using UI Auth Package

Laravel provides user authentication package to manage complete authentication like User Register, Login, Forgot Password, Email Verification. UI Auth…

You can create and manage authentication in Laravel 8 easily using inbuilt packages. User authentication is always the most important concern of any web application. If you want to handle the application functionalities and roles then it always requires a user module. On the basis of the user, you can manage the rights of access in the application. I already shared a post on one of the latest features of Laravel 8 for managing authentication using Jetstream and Livewire. In this post, I will show you how you can create authentication without using Jetstream. I will be going to use the Laravel UI package. Here, I will be starting with a new project in Laravel 8. So, let’s start.

#laravel 8 #auth package in laravel #laravel auth #ui auth in laravel #ui vue auth in laravel #user authentication in laravel

sophia tondon

sophia tondon

1618970788

Top Laravel Development Company India | Laravel Development Services

Laravel is a popular framework for website development, acquiring 25.85% of the PHP framework market share. As a most admired framework among PHP frameworks, it is being utilized for e-commerce, enterprise, social media, and various different types of websites.

There are more than 1 million websites worldwide available over the web that are created using Laravel. Laravel framework is the first preference of PHP developers as it allows them to develop highly scalable, flexible, and faster web applications.

Surely, you, too, would want to deliver a splendid and unhindered user experience to your target audience over the web. Laravel framework can help you achieve this pursuit at ease; all you need to do is hire Laravel developers from reliable & coveted hosts. But! There is no shortage of Laravel development companies that promise to deliver an excellent solution, but only some are able to deliver top-notch quality.

Therefore, I have decided to enlist top Laravel development companies to help you find a reliable and expert host for web development. So, stay hooked with me till the end of this article and explore the best Laravel developers in 2021.

While creating this list, I have kept the following pointers in reflection:

Years of excellence (average 8 years)
Workfolio
Rewards & Recognition
Client rating & feedback
Hourly/Monthly Price
Number of happy clients
Number of successfully launched projects
Minimum man-years experience
So, let’s not waste a minute and glance at top Laravel development companies to hire for creating excellent web solutions.

Read More - https://www.valuecoders.com/blog/technology-and-apps/top-laravel-development-companies-to-hire-experts/

#hire a laravel developer #hire laravel developer #hire laravel developers #laravel developer for hire #laravel developers #laravel developers for hire

sophia tondon

sophia tondon

1620977020

Hire Laravel Developers | Laravel Development Company, Services India

Looking for a team of experienced offshore Laravel developers? Hire a top dedicated team of Laravel developers from India online with 6+ years of average experience on an hourly or dedicated (monthly) basis from ValueCoders and enjoy easy hiring, quality work, and on-demand scalability at up to 60% less cost.

Our offshore Laravel development experts are fully competent to build scalable, secure, and robust custom web apps suiting your business requirements.

First Time Right Process
Complete Control Over The Team
Certified Laravel Coders
Agile & DevOps Enablement
Non-Disclosure Agreement
No Contract Lock-Ins

Visit Us- https://www.valuecoders.com/hire-developers/hire-laravel-developers

#hire a laravel developer #hire laravel developer #laravel development #hire laravel experts #find laravel developers #laravel development services india

Seamus  Quitzon

Seamus Quitzon

1595205213

How to perform migration rollback in laravel

As we know that laravel migration provides very simple way to create database table structure. We need to create migration file and write table structure then migrate that migration. Sometimes we need to rollback that migration. So here we will discuss about the migration rollback in laravel.

We can run the rollback artisan command to rollback on a particular step. We can execute the following artisan command.

php artisan migrate:rollback --step=1

Every time when we will rollback, we will get the last batch of migration.

**Note: **This rollback command will work on laravel 5.3 or above version. For the version below 5.3, there is no command available for migration rollback in laravel.

We can also use the following command to rollback and re migrate.

php artisan migrate:refresh --step=2

It will rollback and remigrate last two migration.

You can also checkout the article for executing single migration by clicking on the link below.

How to migrate single migration in laravel

#laravel #how to perform rollback migration in laravel #laravel migration rollback #migration refresh in laravel #migration rollback batch in laravel #migration rollback for one specific migration #migration rollback in laravel