ytake/laravel-aspect

为laravel框架和lumen设计的面向切面编程库

资助包维护!
ytake


README

laravel框架的面向切面编程包

Build Status StyleCI

License Latest Version Total Downloads

此库深受jcabi/jcabi-aspects的启发。

使用方法

Laravel版本兼容性

安装

$ composer require ytake/laravel-aspect

支持的自动发现(^Laravel5.5)

for Laravel9

Laravel-Aspect 支持 Laravel5.6

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

添加serviceProvider

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

for Lumen

将 App\Providers\LumenAspectServiceProvider 添加到您的 bootstrap/app.php 文件中。

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

发布 aspect 模块类

$ php artisan ytake:aspect-module-publish

更多命令选项 [--help]

发布配置

  • 基本
$ php artisan vendor:publish
  • 使用标签选项
$ php artisan vendor:publish --tag=aspect
  • 使用提供者
$ php artisan vendor:publish --provider="Ytake\LaravelAspect\AspectServiceProvider"

注册 aspect 模块

config/ytake-laravel-aop.php

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

使用类属性

namespace App\Modules;

use Ytake\LaravelAspect\Modules\CacheableModule as PackageCacheableModule;

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

示例

namespace YourApplication\Services;

use Ytake\LaravelAspect\Annotation\Cacheable;

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

注意

  • 必须使用服务容器
  • 类必须是非最终的
  • 方法必须是公共的

for Lumen

覆盖 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);
}

缓存清除命令

$ php artisan ytake:aspect-clear-cache

预编译命令

$ php artisan ytake:aspect-compile

注解

@Transactional

用于数据库事务(illuminate/database)

您必须使用 TransactionalModule 选项

  • 选项
use Ytake\LaravelAspect\Annotation\Transactional;

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

多个事务

use Ytake\LaravelAspect\Annotation\Transactional;

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

@Cacheable

用于缓存(illuminate/cache)

您必须使用 CacheableModule

  • 选项
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

用于缓存(illuminate/cache) / 移除缓存

您必须使用 CacheEvictModule

  • 选项
use Ytake\LaravelAspect\Annotation\CacheEvict;

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

@CachePut

用于缓存(illuminate/cache) / 缓存设置

您必须使用 CachePutModule

  • 选项
use Ytake\LaravelAspect\Annotation\CachePut;

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

@Loggable / @LogExceptions

用于日志(illuminate/log, monolog)

您必须使用 LoggableModule / LogExceptionsModule

  • 选项
use Ytake\LaravelAspect\Annotation\Loggable;

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

示例)

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

关于 @LogExceptions

此外,还可以查看 @Loggable。此注解执行相同的操作,但还可以记录非异常情况。

use Ytake\LaravelAspect\Annotation\LogExceptions;

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

关于 @QueryLog

用于数据库查询日志(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

在发生异常时重试方法。

您必须使用 RetryOnFailureModule。

  • 选项
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

用于消息队列(illuminate/queue, illuminate/bus)的注解。

您必须使用 MessageDrivenModule。

  • 选项
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

处理类 Ytake\LaravelAspect\Queue\LazyMessage

EagerQueue

处理类 Ytake\LaravelAspect\Queue\EagerMessage

忽略注解

使用 config/ytake-laravel-aspect.php 文件

默认: LaravelCollective/annotations

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

附加自定义注解

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

用于测试

使用无驱动程序

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