PHPackages                             jonaskahn/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. [Utility &amp; Helpers](/categories/utility)
4. /
5. jonaskahn/laravel-aspect

AbandonedArchivedLibrary[Utility &amp; Helpers](/categories/utility)

jonaskahn/laravel-aspect
========================

Aspect Oriented Programming library for laravel framework, and lumen

00PHP

Since Aug 30Pushed 1y agoCompare

[ Source](https://github.com/jonaskahn/Enhanced-Laravel-Aspect)[ Packagist](https://packagist.org/packages/jonaskahn/laravel-aspect)[ RSS](/packages/jonaskahn-laravel-aspect/feed)WikiDiscussions main Synced yesterday

READMEChangelogDependenciesVersions (1)Used By (0)

What's news
===========

[](#whats-news)

- Fixed some bugs
- Extended ability for function
- Transaction logic now should be worked in natural like Spring Framework

Why I don't create a pull request
---------------------------------

[](#why-i-dont-create-a-pull-request)

- My code will break current implementation. For example, when I come across source codes, I realized the transaction quite "weired" ( compared with Spring Framework), then I decided to fork and change the source for my own purpose.

Notice
------

[](#notice)

- Do not use my work if you are using original implementation.
- My work was implemented since 2021, now I open this source code.

---

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

[](#laravel-aspect)

aspect-oriented programming Package for laravel framework

[![Build Status](https://github.com/ytake/Laravel-Aspect/workflows/Tests/badge.svg?branch=master)](https://github.com/ytake/Laravel-Aspect/workflows/Tests/badge.svg?branch=master)[![StyleCI](https://camo.githubusercontent.com/809e89b7db3d8170ca27b097263330cd840b39399eee04fc95c2ba380f1e3ac4/68747470733a2f2f7374796c6563692e696f2f7265706f732f34303930303730392f736869656c64)](https://styleci.io/repos/40900709)

[![License](https://camo.githubusercontent.com/7f67a2c8d08e97bb316c77a7851c6f774df60146b76f2344c43c2becd9c1fd3c/687474703a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f7974616b652f6c61726176656c2d6173706563742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/ytake/laravel-aspect)[![Latest Version](https://camo.githubusercontent.com/a2606c8a35f4a7c6436edef02eaf9ec916c80f2c97ad69351aa640c26c59078a/687474703a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7974616b652f6c61726176656c2d6173706563742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/ytake/laravel-aspect)[![Total Downloads](https://camo.githubusercontent.com/d01e6a13ea155f734537a054dbc0cc216df7a099a8e2674329ba8188e7bb113a/687474703a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7974616b652f6c61726176656c2d6173706563742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/ytake/laravel-aspect)

This library is heavily inspired by the [jcabi/jcabi-aspects](https://github.com/jcabi/jcabi-aspects).

usage
-----

[](#usage)

### Laravel version Compatibility

[](#laravel-version-compatibility)

LaravelPackage5.0.x1.x5.1.x1.x5.2.x1.x5.3.x1.x5.4.x1.x5.5.x2.0.\*5.6.x2.1.\*5.7.x3.0.\*6.0.x4.07.x6.08.x7.09.x8.010.x9.0### install

[](#install)

```
$ composer require ytake/laravel-aspect
```

*Supported Auto-Discovery(^Laravel5.5)*

#### for Laravel9

[](#for-laravel9)

[Laravel-Aspect Supported Laravel5.6](https://github.com/ytake/Laravel-Aspect/blob/master-laravel5.6)

```
  "require": {
   "php": ">=7.1.3",
   "laravel/framework": "^5.7",
   "ytake/laravel-aspect": "^8.0.0"
 },
```

### added serviceProvider

[](#added-serviceprovider)

```
'providers' => [
    // added AspectServiceProvider
    \Ytake\LaravelAspect\AspectServiceProvider::class,
    // added Artisan Command
    \Ytake\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(\Ytake\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="Ytake\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 Ytake\LaravelAspect\Modules\CacheableModule as PackageCacheableModule;

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

example

```
namespace YourApplication\Services;

use Ytake\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 `Ytake\LaravelAspect\AspectServiceProvider`

```
use Ytake\LaravelAspect\AspectManager;
use Ytake\LaravelAspect\AnnotationManager;
use Ytake\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(Ytake\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

14

—

LowBetter than 1% of packages

Maintenance27

Infrequent updates — may be unmaintained

Popularity0

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity18

Early-stage or recently created project

 Bus Factor1

Top contributor holds 91.8% 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.

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/84830899?v=4)[tuyendev](/maintainers/tuyendev)[@tuyendev](https://github.com/tuyendev)

---

Top Contributors

[![ytake](https://avatars.githubusercontent.com/u/4454078?v=4)](https://github.com/ytake "ytake (169 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)")[![jonaskahn](https://avatars.githubusercontent.com/u/4338500?v=4)](https://github.com/jonaskahn "jonaskahn (3 commits)")[![scrutinizer-auto-fixer](https://avatars.githubusercontent.com/u/6253494?v=4)](https://github.com/scrutinizer-auto-fixer "scrutinizer-auto-fixer (1 commits)")[![yamotuki](https://avatars.githubusercontent.com/u/7507294?v=4)](https://github.com/yamotuki "yamotuki (1 commits)")[![hohoangtung](https://avatars.githubusercontent.com/u/13851541?v=4)](https://github.com/hohoangtung "hohoangtung (1 commits)")

### Embed Badge

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

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

PHPackages © 2026

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