PHPackages                             bssd-ltd/laravel-aspect - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Logging &amp; Monitoring](/categories/logging)
4. /
5. bssd-ltd/laravel-aspect

ActiveLibrary[Logging &amp; Monitoring](/categories/logging)

bssd-ltd/laravel-aspect
=======================

Aspect Oriented Programming library for laravel framework, and lumen

0.0.2(4y ago)1709[1 issues](https://github.com/bssd-ltd/Laravel-Aspect/issues)MITPHPPHP ^7.3|^8.0

Since Jul 22Pushed 1y agoCompare

[ Source](https://github.com/bssd-ltd/Laravel-Aspect)[ Packagist](https://packagist.org/packages/bssd-ltd/laravel-aspect)[ RSS](/packages/bssd-ltd-laravel-aspect/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)Dependencies (28)Versions (5)Used By (0)

Laravel-Aspect
==============

[](#laravel-aspect)

Origin source can be found [here](https://github.com/ytake/Laravel-Aspect)

### added serviceProvider

[](#added-serviceprovider)

```
'providers' => [
    // added AspectServiceProvider
    \Bssd\LaravelAspect\AspectServiceProvider::class,
    // added Artisan Command
    \Bssd\LaravelAspect\ConsoleServiceProvider::class,
]
```

### for Lumen

[](#for-lumen)

Add App\\Providers\\LumenAspectServiceProvider to your bootstrap/app.php file.

```
$app->register(\App\Providers\LumenAspectServiceProvider::class);
$app->register(\Bssd\LaravelAspect\ConsoleServiceProvider::class);
```

### publish aspect module class

[](#publish-aspect-module-class)

```
$ php artisan ytake:aspect-module-publish
```

more command options \[--help\]

### publish configure

[](#publish-configure)

- basic

```
$ php artisan vendor:publish
```

- use tag option

```
$ php artisan vendor:publish --tag=aspect
```

- use provider

```
$ php artisan vendor:publish --provider="Bssd\LaravelAspect\AspectServiceProvider"
```

### register aspect module

[](#register-aspect-module)

config/ytake-laravel-aop.php

```
        'modules' => [
            // append modules
            // \App\Modules\CacheableModule::class,
        ],
```

use classes property

```
namespace App\Modules;

use Bssd\LaravelAspect\Modules\CacheableModule as PackageCacheableModule;

/**
 * Class CacheableModule
 */
class CacheableModule extends PackageCacheableModule
{
    /** @var array */
    protected $classes = [
        \YourApplication\Services\SampleService::class
    ];
}
```

example

```
namespace YourApplication\Services;

use Bssd\LaravelAspect\Annotation\Cacheable;

class SampleService
{
    /**
     * @Cacheable(cacheName="testing1",key={"#id"})
     */
    public function action($id)
    {
        return $this;
    }
}
```

*notice*

- Must use a service container
- Classes must be non-final
- Methods must be public

### for Lumen

[](#for-lumen-1)

override `Bssd\LaravelAspect\AspectServiceProvider`

```
use Bssd\LaravelAspect\AspectManager;
use Bssd\LaravelAspect\AnnotationManager;
use Bssd\LaravelAspect\AspectServiceProvider as AspectProvider;

/**
 * Class AspectServiceProvider
 */
final class AspectServiceProvider extends AspectProvider
{
    /**
     * {@inheritdoc}
     */
    public function register()
    {
        $this->app->configure('ytake-laravel-aop');
        $this->app->singleton('aspect.manager', function ($app) {
            $annotationConfiguration = new AnnotationConfiguration(
                $app['config']->get('ytake-laravel-aop.annotation')
            );
            $annotationConfiguration->ignoredAnnotations();
            // register annotation
            return new AspectManager($app);
        });
    }
}
```

bootstrap/app.php

```
$app->register(App\Providers\AspectServiceProvider::class);

if ($app->runningInConsole()) {
    $app->register(Bssd\LaravelAspect\ConsoleServiceProvider::class);
}
```

Cache Clear Command
-------------------

[](#cache-clear-command)

```
$ php artisan ytake:aspect-clear-cache
```

PreCompile Command
------------------

[](#precompile-command)

```
$ php artisan ytake:aspect-compile
```

Annotations
-----------

[](#annotations)

### @Transactional

[](#transactional)

for database transaction(illuminate/database)

you must use the TransactionalModule

- option

paramsdescriptionvalue (or array)database connectionexpectexpect exception```
use Bssd\LaravelAspect\Annotation\Transactional;

/**
 * @Transactional("master")
 */
public function save(array $params)
{
    return $this->eloquent->save($params);
}
```

#### Multiple Transaction

[](#multiple-transaction)

```
use Bssd\LaravelAspect\Annotation\Transactional;

/**
 * @Transactional({"master", "second_master"})
 */
public function save(array $params)
{
    $this->eloquent->save($params);
    $this->query->save($params);
}
```

#### Exception Rollback

[](#exception-rollback)

```
use Bssd\LaravelAspect\Annotation\Transactional;

/**
 * @Transactional(expect="\QueryException")
 */
public function save(array $params)
{
    $this->eloquent->save($params);
    $this->query->save($params);
}
```

#### Multiple Exception Rollback

[](#multiple-exception-rollback)

```
use Bssd\LaravelAspect\Annotation\Transactional;

/**
 * @Transactional(expect={"\QueryException", "\RuntimeException"})
 */
public function save(array $params)
{
    $this->eloquent->save($params);
    $this->query->save($params);
}
```

### @Cacheable

[](#cacheable)

for cache(illuminate/cache)

you must use the CacheableModule

- option

paramsdescriptionkeycache keycacheNamecache name(merge cache key)driverAccessing Cache Driver(store)lifetimecache lifetime (default: 120min)tagsStoring Tagged Cache Itemsnegative(bool)for null value (default: false)```
use Bssd\LaravelAspect\Annotation\Cacheable;

/**
 * @Cacheable(cacheName="testing1",key={"#id","#value"})
 * @param $id
 * @param $value
 * @return mixed
 */
public function namedMultipleKey($id, $value)
{
    return $id;
}
```

### @CacheEvict

[](#cacheevict)

for cache(illuminate/cache) / remove cache

you must use the CacheEvictModule

- option

paramsdescriptionkeycache keycacheNamecache name(merge cache key)driverAccessing Cache Driver(store)tagsStoring Tagged Cache ItemsallEntriesflush(default:false)```
use Bssd\LaravelAspect\Annotation\CacheEvict;

/**
 * @CacheEvict(cacheName="testing",tags={"testing1"},allEntries=true)
 * @return null
 */
public function removeCache()
{
    return null;
}
```

### @CachePut

[](#cacheput)

for cache(illuminate/cache) / cache put

you must use the CachePutModule

- option

paramsdescriptionkeycache keycacheNamecache name(merge cache key)driverAccessing Cache Driver(store)lifetimecache lifetime (default: 120min)tagsStoring Tagged Cache Items```
use Bssd\LaravelAspect\Annotation\CachePut;

/**
 * @CachePut(cacheName={"testing1"},tags="testing1")
 */
public function throwExceptionCache()
{
    return 'testing';
}
```

### @Loggable / @LogExceptions

[](#loggable--logexceptions)

for logger(illuminate/log, monolog)

you must use the LoggableModule / LogExceptionsModule

- option

paramsdescriptionvaluelog level (default: \\Monolog\\Logger::INFO) should Monolog ConstantsskipResultmethod result output to lognamelog name prefix(default: Loggable)driverlogger driver or channel name - default using **LOG\_CHANNEL** (.env settings)```
use Bssd\LaravelAspect\Annotation\Loggable;

class AspectLoggable
{
    /**
     * @Loggable
     * @param null $id
     * @return null
     */
    public function normalLog($id = null)
    {
        return $id;
    }
}
```

sample)

```
[2015-12-23 08:15:30] testing.INFO: Loggable:__Test\AspectLoggable.normalLog {"args":{"id":1},"result":1,"time":0.000259876251221}

```

#### About @LogExceptions

[](#about-logexceptions)

**Also, take a look at @Loggable. This annotation does the same, but also logs non-exceptional situations.**

```
use Bssd\LaravelAspect\Annotation\LogExceptions;

class AspectLoggable
{
    /**
     * @LogExceptions
     * @param null $id
     * @return null
     */
    public function dispatchLogExceptions()
    {
        return $this->__toString();
    }
}
```

#### About @QueryLog

[](#about-querylog)

for database query logger(illuminate/log, monolog, illuminate/database)

```
use Bssd\LaravelAspect\Annotation\QueryLog;
use Illuminate\Database\ConnectionResolverInterface;

/**
 * Class AspectQueryLog
 */
class AspectQueryLog
{
    /** @var ConnectionResolverInterface */
    protected $db;

    /**
     * @param ConnectionResolverInterface $db
     */
    public function __construct(ConnectionResolverInterface $db)
    {
        $this->db = $db;
    }

    /**
     * @QueryLog
     */
    public function multipleDatabaseAppendRecord()
    {
        $this->db->connection()->statement('CREATE TABLE tests (test varchar(255) NOT NULL)');
        $this->db->connection('testing_second')->statement('CREATE TABLE tests (test varchar(255) NOT NULL)');
        $this->db->connection()->table("tests")->insert(['test' => 'testing']);
        $this->db->connection('testing_second')->table("tests")->insert(['test' => 'testing second']);
    }
}
```

```
testing.INFO: QueryLog:AspectQueryLog.multipleDatabaseAppendRecord {"queries":[{"query":"CREATE TABLE tests (test varchar(255) NOT NULL)","bindings":[],"time":0.58,"connectionName":"testing"},{"query":"CREATE TABLE tests (test varchar(255) NOT NULL)","bindings":[],"time":0.31,"connectionName":"testing_second"} ...

```

### @PostConstruct

[](#postconstruct)

The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization.

you must use the PostConstructModule

```
use Bssd\LaravelAspect\Annotation\PostConstruct;

class Something
{
    protected $abstract;

    protected $counter = 0;

    public function __construct(ExampleInterface $abstract)
    {
        $this->abstract = $abstract;
    }

    /**
     * @PostConstruct
     */
    public function init()
    {
        $this->counter += 1;
    }

    /**
     * @return int
     */
    public function returning()
    {
        return $this->counter;
    }
}
```

**The method MUST NOT have any parameters**

### @RetryOnFailure

[](#retryonfailure)

Retry the method in case of exception.

you must use the RetryOnFailureModule.

- option

paramsdescriptionattempts (int)How many times to retry. (default: 0)delay (int)Delay between attempts. (default: 0 / sleep(0) )types (array)When to retry (in case of what exception types). (default: &lt;\\Exception::class&gt; )ignore (string)Exception types to ignore. (default: \\Exception )```
use Bssd\LaravelAspect\Annotation\RetryOnFailure;

class ExampleRetryOnFailure
{
    /** @var int */
    public $counter = 0;

    /**
     * @RetryOnFailure(
     *     types={
     *         LogicException::class,
     *     },
     *     attempts=3,
     *     ignore=Exception::class
     * )
     */
    public function ignoreException()
    {
        $this->counter += 1;
        throw new \Exception;
    }
}
```

### @MessageDriven

[](#messagedriven)

Annotation for a Message Queue(illuminate/queue. illuminate/bus).

you must use the MessageDrivenModule.

- option

paramsdescriptionvalue (Delayed)\\Bssd\\LaravelAspect\\Annotation\\LazyQueue or \\Bssd\\LaravelAspect\\Annotation\\EagerQueue (default: EagerQueue)onQueue (string)To specify the queue. (default: null) )mappedName (string)queue connection. (default: null/ default queue driver)```
use Bssd\LaravelAspect\Annotation\EagerQueue;
use Bssd\LaravelAspect\Annotation\LazyQueue;
use Bssd\LaravelAspect\Annotation\Loggable;
use Bssd\LaravelAspect\Annotation\MessageDriven;

/**
 * Class AspectMessageDriven
 */
class AspectMessageDriven
{
    /**
     * @Loggable
     * @MessageDriven(
     *     @LazyQueue(3),
     *     onQueue="message"
     * )
     * @return void
     */
    public function exec($param)
    {
        echo $param;
    }

    /**
     * @MessageDriven(
     *     @EagerQueue
     * )
     * @param string $message
     */
    public function eagerExec($message)
    {
        $this->logWith($message);
    }

    /**
     * @Loggable(name="Queued")
     * @param string $message
     *
     * @return string
     */
    public function logWith($message)
    {
        return "Hello $message";
    }
}
```

#### LazyQueue

[](#lazyqueue)

Handle Class *Bssd\\LaravelAspect\\Queue\\LazyMessage*

#### EagerQueue

[](#eagerqueue)

Handle Class *Bssd\\LaravelAspect\\Queue\\EagerMessage*

### Ignore Annotations

[](#ignore-annotations)

use config/ytake-laravel-aspect.php file

default: LaravelCollective/annotations

```
    'annotation' => [
        'ignores' => [
            // global Ignored Annotations
            'Hears',
            'Get',
            'Post',
            'Put',
            'Patch',
            'Options',
            'Delete',
            'Any',
            'Middleware',
            'Resource',
            'Controller'
        ],
    ],
```

### Append Custom Annotations

[](#append-custom-annotations)

```
    'annotation' => [
        'ignores' => [
            // global Ignored Annotations
            'Hears',
            'Get',
            'Post',
            'Put',
            'Patch',
            'Options',
            'Delete',
            'Any',
            'Middleware',
            'Resource',
            'Controller'
        ],
        'custom' => [
            \Acme\Annotations\Transactional::class
            // etc...
        ]
    ],
```

for testing
-----------

[](#for-testing)

use none driver

```

```

###  Health Score

23

—

LowBetter than 27% of packages

Maintenance8

Infrequent updates — may be unmaintained

Popularity15

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity49

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 87.3% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~10 days

Total

2

Last Release

1744d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/77174fe616ad468cc08f36ac4e9be8264fab5256aebd9be6d028154bf18466f3?d=identicon)[bssd-co-ltd](/maintainers/bssd-co-ltd)

---

Top Contributors

[![ytake](https://avatars.githubusercontent.com/u/4454078?v=4)](https://github.com/ytake "ytake (165 commits)")[![tuyendev](https://avatars.githubusercontent.com/u/84830899?v=4)](https://github.com/tuyendev "tuyendev (9 commits)")[![4n70w4](https://avatars.githubusercontent.com/u/38257723?v=4)](https://github.com/4n70w4 "4n70w4 (5 commits)")[![izayoi256](https://avatars.githubusercontent.com/u/1329505?v=4)](https://github.com/izayoi256 "izayoi256 (4 commits)")[![bsd-company-bot](https://avatars.githubusercontent.com/u/80682860?v=4)](https://github.com/bsd-company-bot "bsd-company-bot (3 commits)")[![jonaskahn](https://avatars.githubusercontent.com/u/4338500?v=4)](https://github.com/jonaskahn "jonaskahn (2 commits)")[![scrutinizer-auto-fixer](https://avatars.githubusercontent.com/u/6253494?v=4)](https://github.com/scrutinizer-auto-fixer "scrutinizer-auto-fixer (1 commits)")

---

Tags

laravelcacheaspectloggertransaction

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

![Health badge](/badges/bssd-ltd-laravel-aspect/health.svg)

```
[![Health](https://phpackages.com/badges/bssd-ltd-laravel-aspect/health.svg)](https://phpackages.com/packages/bssd-ltd-laravel-aspect)
```

###  Alternatives

[ytake/laravel-aspect

Aspect Oriented Programming library for laravel framework, and lumen

138132.2k1](/packages/ytake-laravel-aspect)[roots/acorn

Framework for Roots WordPress projects built with Laravel components.

9682.1M97](/packages/roots-acorn)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

255.2k](/packages/aedart-athenaeum)[laravel/pulse

Laravel Pulse is a real-time application performance monitoring tool and dashboard for your Laravel application.

1.7k12.1M99](/packages/laravel-pulse)[laravel-zero/framework

The Laravel Zero Framework.

3371.4M369](/packages/laravel-zero-framework)[flarum/core

Delightfully simple forum software.

211.3M1.9k](/packages/flarum-core)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
