imanghafoori/laravel-decorator

A package to easily decorate your function calls.

v1.1.0 2024-05-06 16:47 UTC

This package is auto-updated.

Last update: 2024-12-06 18:23:24 UTC


README

Decorator pattern in Laravel apps

Quality Score StyleCI Software License Check Imports Latest Stable Version Code Coverage Total Downloads

Made with ❤️ for smart clean coders

A try to port "decorator" feature from python language to laravel framework.

python-and-prey

🚚 Installation:

composer require imanghafoori/laravel-decorator

What is a "Decorator"

A decorator is callable which wraps around the original decorated callable, in order to form a new callable composed of the previous two.

Like a python snake swallowing a deer whole and wraps around its body !

After that the snake becomes capable to eat and digest grasses 🌿 because it has a deer inside it.

Technically, A "Decorator":

1- Is a "callable"

2- which takes another "callable" (as it's only argument, like a snake swallows another snake)

3- and returns a new "callable" (which internally calls the original callable, putting some code before and after it.)

What?!??! ???! (0_o)

What can be considered as a "callable" within laravel ?!

Long story short, anything that can be called (invoked) with App::call(); or call_user_func() like: 'MyClass@myMethod' or a closure, [UserRepo::class, 'find']

Cache Like a Pro:

Caching DB queries is always a need, but it is always annoying to add more code to the existing code. It will become more messy, we may break the current code, after all it adds a layer of fog. Yeah?

Imagine that you have a UserControllerwhich calls a UserRepo@find to get a $user .

Then after a while you decide to put a cache layer between those two classes for obvious reasons.

According to SOLID principles, you shouldn't put the caching code logic neither in your controller nor your UserRepo. But somewhere in between.

In other words, you want to add a new feature (caching in this case) without modifying the existing code.

It smells like Open-closed Principle Yeah?! 👃

You want to keep the responsibilities separate. In this case caching should not be in a repository or controller but in its own class.

It smells like Single Responsibility Principle yeah?! 👃

class UserRepository
{
    function find($uid)
    {
        return User::find($uid);
    }
}

class MadUsersController extends Controller
{
    function show ($madUserId)
    {
        $madUser = app()->call('UserRepository@find', ['id' => $madUserId]);
    }
}

ok now there is no cache, going on. it is a direct call.

With the help of laravel-decorator built-in cache decorator, you can go to AppServiceProvider.php (or any other service provider):

<?php

use Imanghafoori\Decorator\Decorators\DecoratorFactory;

class AppServiceProvider extends ServiceProvider
{

    public function boot()
    {
        $keyMaker = function ($madId) {
            return 'mad_user_key_' . $madId;
        };
        $time = 10;
        $decorator = DecoratorFactory::cache($keyMaker, $time);
        
        \Decorator::decorate('UserRepository@find', $decorator);
    }
}

You will get cached results from your calls, in your UserController without touching it! but remember to change:

 app()->call('UserRepository@find', ...
 // to :
  app('decorator')->call('UserRepository@find', ...

Define Your Own Decorators:

public function boot ()
{
    \Decorator::define('myDecoratorName1', 'SomeClass@someMethod');
    
    // or

    \Decorator::define('myDecoratorName2', function ($callable) {
        return function (...) use ($callable){ ... } 
    });
}

Then you can use this name (myDecoratorName) to decorate methods.

How to decorate a method?

// You may set multiple decorators on a single method... 
\Decorator::decorate('class@method, 'someClass@someOtherDecorator'); // (first)

// or reference the decorator by its name :
\Decorator::decorate('class@method, 'myDecoratorName'); // (second)

How to call a method with its decorators?

image

Decorate Facades:

Decorating Facade Methods

First you should extend the Imanghafoori\Decorator\DecoratableFacade class (instead of the laravel base Facade).

image

Now You Can Apply Decorators in your ServiceProvider's boot method:

image

Then if you call your facade as normal you get decorated results.

image

⚠️ Warning:

With great power, comes great responsibilities.

Remember not to violate the Liskoves Substitution Principle when you decorate something.

For example a method call which returns int|null should not unexpectedly return a string after being decorated.

$result = app('decorate')->call(...

Since the users of the method should be ready for type of value they get back.

But if you return only int and your decorator causes the null value to be filtered out. that's ok.

⭐ Your Stars Make Us Do More ⭐

As always if you found this package useful, and you want to encourage us to maintain and work on it, Please press the star button to declare your willingness.

More packages from the author:

💎 A minimal yet powerful package to give you opportunity to refactor your controllers.

💎 A minimal yet powerful package to give a better structure and caching opportunity for your laravel apps.

💎 It allows you log in with any password in local environment only.

💎 Authorization and ACL is now very easy with hey-man package!