PHPackages                             ytake/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. ytake/laravel-aspect

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

ytake/laravel-aspect
====================

Aspect Oriented Programming library for laravel framework, and lumen

11.0.0(8mo ago)138132.2k—3.4%20[8 issues](https://github.com/ytake/Laravel-Aspect/issues)1MITPHPPHP ^8.2CI passing

Since Aug 25Pushed 8mo ago12 watchersCompare

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

READMEChangelog (10)Dependencies (26)Versions (59)Used By (1)

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 Ytake\LaravelAspect\Annotation\Transactional;

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

#### Multiple Transaction

[](#multiple-transaction)

```
use Ytake\LaravelAspect\Annotation\Transactional;

/**
 * @Transactional({"master", "second_master"})
 */
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 Ytake\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 Ytake\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 Ytake\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: Level::Info-&gt;value). Supports integer constants, Monolog Level enum values, or string level names ("debug", "info", etc.)skipResultmethod result output to lognamelog name prefix(default: Loggable)driverlogger driver or channel name [docs](https://laravel.com/docs/5.6/logging#configuration)```
use Ytake\LaravelAspect\Annotation\Loggable;

class AspectLoggable
{
    /**
     * @Loggable(driver="stack")
     * @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 Ytake\LaravelAspect\Annotation\LogExceptions;

class AspectLoggable
{
    /**
     * @LogExceptions(driver="custom")
     * @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 Ytake\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(driver="custom")
     */
    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"} ...

```

### @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 Ytake\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)\\Ytake\\LaravelAspect\\Annotation\\LazyQueue or \\Ytake\\LaravelAspect\\Annotation\\EagerQueue (default: EagerQueue)onQueue (string)To specify the queue. (default: null) )mappedName (string)queue connection. (default: null/ default queue driver)```
use Ytake\LaravelAspect\Annotation\EagerQueue;
use Ytake\LaravelAspect\Annotation\LazyQueue;
use Ytake\LaravelAspect\Annotation\Loggable;
use Ytake\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 *Ytake\\LaravelAspect\\Queue\\LazyMessage*

#### EagerQueue

[](#eagerqueue)

Handle Class *Ytake\\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

60

—

FairBetter than 99% of packages

Maintenance60

Regular maintenance activity

Popularity48

Moderate usage in the ecosystem

Community25

Small or concentrated contributor base

Maturity89

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 92.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 ~74 days

Recently: every ~432 days

Total

50

Last Release

247d ago

Major Versions

6.0.1 → 7.0.02020-12-18

7.0.0 → 8.0.02023-01-15

8.0.0 → 9.0.02024-03-15

9.0.0 → 10.0.02025-02-10

10.0.0 → 11.0.02025-09-13

PHP version history (10 changes)0.1PHP &gt;=5.5.9

1.5.2PHP ^5.5 || ^7.0

1.6.0PHP ^5.5|^7.0

2.0.0PHP ^7.0

2.1.0PHP ^7.1

6.0.0PHP ^7.2.5

7.0.0PHP ^7.3|^8.0

8.0.0PHP ^8.0

9.0.0PHP ^8.1

10.0.0PHP ^8.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/47817f3dd2890864096bd77ee772ec46061432f128988ca23939b0ca486d7bc3?d=identicon)[ytake](/maintainers/ytake)

---

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)")[![kubotak-is](https://avatars.githubusercontent.com/u/13742370?v=4)](https://github.com/kubotak-is "kubotak-is (1 commits)")[![r-eiyama](https://avatars.githubusercontent.com/u/122075793?v=4)](https://github.com/r-eiyama "r-eiyama (1 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)")

---

Tags

annotationsaoplaravellaravel-aspectlumenlaravelcacheaspectloggertransaction

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

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

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

###  Alternatives

[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

245.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)[spatie/laravel-health

Monitor the health of a Laravel application

86910.0M83](/packages/spatie-laravel-health)

PHPackages © 2026

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