• Stars
    star
    130
  • Rank 277,575 (Top 6 %)
  • Language
    PHP
  • License
    MIT License
  • Created over 9 years ago
  • Updated 8 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

aspect oriented programming Package for laravel framework

Laravel-Aspect

aspect-oriented programming Package for laravel framework

Build Status StyleCI

License Latest Version Total Downloads

This library is heavily inspired by the jcabi/jcabi-aspects.

usage

Laravel version Compatibility

Laravel Package
5.0.x 1.x
5.1.x 1.x
5.2.x 1.x
5.3.x 1.x
5.4.x 1.x
5.5.x 2.0.*
5.6.x 2.1.*
5.7.x 3.0.*
6.0.x 4.0
7.x 6.0
8.x 7.0
9.x 8.0

install

$ composer require ytake/laravel-aspect

Supported Auto-Discovery(^Laravel5.5)

for Laravel9

Laravel-Aspect Supported Laravel5.6

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

added serviceProvider

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

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

$ php artisan ytake:aspect-module-publish

more command options [--help]

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

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

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

$ php artisan ytake:aspect-clear-cache

PreCompile Command

$ php artisan ytake:aspect-compile

Annotations

@Transactional

for database transaction(illuminate/database)

you must use the TransactionalModule

  • option
params description
value (or array) database connection
expect expect exception
use Ytake\LaravelAspect\Annotation\Transactional;

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

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

for cache(illuminate/cache)

you must use the CacheableModule

  • option
params description
key cache key
cacheName cache name(merge cache key)
driver Accessing Cache Driver(store)
lifetime cache lifetime (default: 120min)
tags Storing Tagged Cache Items
negative(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

for cache(illuminate/cache) / remove cache

you must use the CacheEvictModule

  • option
params description
key cache key
cacheName cache name(merge cache key)
driver Accessing Cache Driver(store)
tags Storing Tagged Cache Items
allEntries flush(default:false)
use Ytake\LaravelAspect\Annotation\CacheEvict;

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

@CachePut

for cache(illuminate/cache) / cache put

you must use the CachePutModule

  • option
params description
key cache key
cacheName cache name(merge cache key)
driver Accessing Cache Driver(store)
lifetime cache lifetime (default: 120min)
tags Storing Tagged Cache Items
use Ytake\LaravelAspect\Annotation\CachePut;

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

@Loggable / @LogExceptions

for logger(illuminate/log, monolog)

you must use the LoggableModule / LogExceptionsModule

  • option
params description
value log level (default: \Monolog\Logger::INFO) should Monolog Constants
skipResult method result output to log
name log name prefix(default: Loggable)
driver logger driver or channel name docs
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

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

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

Retry the method in case of exception.

you must use the RetryOnFailureModule.

  • option
params description
attempts (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: <\Exception::class> )
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

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

you must use the MessageDrivenModule.

  • option
params description
value (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

Handle Class Ytake\LaravelAspect\Queue\LazyMessage

EagerQueue

Handle Class Ytake\LaravelAspect\Queue\EagerMessage

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

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

for testing

use none driver

<env name="ASPECT_DRIVER" value="none"/>

More Repositories

1

Laravel.Smarty

smarty template engine for laravel
PHP
83
star
2

Laravel-FluentLogger

fluent logger for laravel (with Monolog handler for Fluentd)
PHP
63
star
3

valueobjects

A PHP library/collection of classes / immutable objects!
PHP
60
star
4

Laravel-Couchbase

Couchbase providers for Laravel
PHP
30
star
5

gardening

Vagrant Box(centos7) for PHP web developers.
Shell
26
star
6

laravel-websocket

Laravel (websocket, socket.io) sample / websocket, socket.io サーバサンプル
PHP
23
star
7

Laravel5.BasicArchitecture

Larave5 基本的な実装サンプル集/Laravel5 basic architecture Sample
PHP
21
star
8

php-ksql

Apache Kafka / Confluent KSQL REST Client for PHP
PHP
18
star
9

php-presto-client

prestdb client for php
PHP
17
star
10

Tutorial.Laravel4

Laravel4 tutorial application
PHP
15
star
11

phluxor

A toolkit for flexible actor models in PHP, empowering the PHP ecosystem
PHP
13
star
12

cqrs-app-sample

PHP(Laravel) / ES+CQRS Sample Application
PHP
12
star
13

Laravel.JpRecipe

laravel jp recipe site
PHP
12
star
14

LaravelWorkShop

Laravelワークショップなどで利用した資料です。
PHP
9
star
15

lumen-adr-example

Implementing ADR in Lumen
PHP
8
star
16

example-laravel-aspect-ddd

example. laravel aspect oriented programming with ddd style
PHP
7
star
17

microCMS.Project

micro cms / blog engine by Lumen
PHP
7
star
18

laravel-presto-kafka-demo

(example) laravel with prestodb
PHP
6
star
19

ytake-laravel

PHP
6
star
20

nazg-skeleton

Begin developing HHVM/Hack Http Microframework Skeleton. Nazg is Action-Domain-Responder (ADR) Micro framework for HHVM/Hack
Hack
5
star
21

protoactor-go-cqrs-example

no tactical DDD pattern, implemented CQRS pattern using actor model(golang)
Go
5
star
22

gulp-sample

phpの為のgulp入門
PHP
4
star
23

hack-logging

Send logs to files For HHVM/Hack
Hack
4
star
24

Iono.Container

spring framework style PHP service container library(with annotations)
PHP
4
star
25

Laravel.VoltDB

VoltDB providers for Laravel
PHP
4
star
26

protoactor-go-example

A sample where the content of akka in action is changed to proto actor (go)
Go
4
star
27

zundoko-kafka-streams

sample of kafka streams
Scala
3
star
28

L5Idea

for Laravel5.1 next level architecture example
PHP
3
star
29

hack-ddd-repository-sample

for phpcon sendai 2019
Hack
3
star
30

hack-terminal-nes-emulator

wip
Hack
3
star
31

Lom

Lombok style code generator for php
PHP
3
star
32

laravel-skeleton

strict mode laravel (removed facades etc...)
PHP
3
star
33

protoactor-go-persistence-pg

Go package with persistence provider for Proto Actor (Go) based on PostgreSQL.
Go
3
star
34

VoltDB.PHPClientWrapper

voltdb-php-client wrapper / json interface support
PHP
2
star
35

hh-container

simple light weight service location container for hhvm/hack
Hack
2
star
36

aspect-app-sample-kansai

PHP
2
star
37

spec-unit-testing

for phpstudy
PHP
2
star
38

kafka-console

php kafka console application
PHP
1
star
39

.github

1
star
40

psr-http-factory-hhi

Typechecker definitions for PSR-17
1
star
41

hhypermedia

Hypertext Application Language for HHVM/Hack
Hack
1
star
42

hack-cookie

HHVM and Hack Cookies for facebook/hack-http-request-response-interfaces
Hack
1
star
43

terraform-aws-boilerplate

for me
HCL
1
star
44

unko

1
star
45

hack-pds-skeleton

Hack Development Standards
Hack
1
star
46

hackdotenv

Loads environment vars from .env to getenv().
Hack
1
star
47

consoler

php console application
PHP
1
star
48

kfchc

health check for kafka connect
Go
1
star
49

training-scala-es-spark-als

Scala
1
star
50

zend-expressive-reference

PHP
1
star
51

gardening-builder

for gardening.box
Shell
1
star
52

gardening-hhvm

PHP
1
star
53

go-actor-metrics-sample

Go
1
star
54

student-actors

Go
1
star
55

Hackavel

hhvm/hack project
Hack
1
star