承接 ray/aop 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

ray/aop

Composer 安装命令:

composer require ray/aop

包简介

An aspect oriented framework

关键字:

README 文档

README

Aspect Oriented Framework

Scrutinizer Code Quality codecov Type Coverage Continuous Integration Total Downloads

ray-di logo

[Japanese]

Ray.Aop package provides method interception. This feature enables you to write code that is executed each time a matching method is invoked. It's suited for cross cutting concerns ("aspects"), such as transactions, security and logging. Because interceptors divide a problem into aspects rather than objects, their use is called Aspect Oriented Programming (AOP).

A Matcher is a simple interface that either accepts or rejects a value. For Ray.AOP, you need two matchers: one that defines which classes participate, and another for the methods of those classes. To make this easy, there's factory class to satisfy the common scenarios.

MethodInterceptors are executed whenever a matching method is invoked. They have the opportunity to inspect the call: the method, its arguments, and the receiving instance. They can perform their cross-cutting logic and then delegate to the underlying method. Finally, they may inspect the return value or exception and return. Since interceptors may be applied to many methods and will receive many calls, their implementation should be efficient and unintrusive.

Example: Forbidding method calls on weekends

To illustrate how method interceptors work with Ray.Aop, we'll forbid calls to our pizza billing system on weekends. The delivery guys only work Monday thru Friday so we'll prevent pizza from being ordered when it can't be delivered! This example is structurally similar to use of AOP for authorization.

To mark select methods as weekdays-only, we define an attribute.

<?php
#[Attribute(Attribute::TARGET_METHOD)]
final class NotOnWeekends
{
}

...and apply it to the methods that need to be intercepted:

<?php
class RealBillingService
{
    #[NotOnWeekends] 
    public function chargeOrder(PizzaOrder $order, CreditCard $creditCard)
    {

Next, we define the interceptor by implementing the org.aopalliance.intercept.MethodInterceptor interface. When we need to call through to the underlying method, we do so by calling $invocation->proceed():

<?php
class WeekendBlocker implements MethodInterceptor
{
    public function invoke(MethodInvocation $invocation)
    {
        $today = getdate();
        if ($today['weekday'][0] === 'S') {
            throw new \RuntimeException(
                $invocation->getMethod()->getName() . " not allowed on weekends!"
            );
        }
        return $invocation->proceed();
    }
}

Finally, we configure everything using the Aspect class:

use Ray\Aop\Aspect;
use Ray\Aop\Matcher;

$aspect = new Aspect();
$aspect->bind(
    (new Matcher())->any(),
    (new Matcher())->annotatedWith(NotOnWeekends::class),
    [new WeekendBlocker()]
);

$billing = $aspect->newInstance(RealBillingService::class);
try {
    echo $billing->chargeOrder(); // Interceptors applied
} catch (\RuntimeException $e) {
    echo $e->getMessage() . "\n";
    exit(1);
}

Putting it all together, (and waiting until Saturday), we see the method is intercepted and our order is rejected:

chargeOrder not allowed on weekends!

Configuration Options

When creating an Aspect instance, you can optionally specify a temporary directory:

$aspect = new Aspect('/path/to/tmp/dir');

If not specified, the system's default temporary directory will be used.

Own matcher

You can have your own matcher. To create contains matcher, You need to provide a class which have two method. One is matchesClass for class match. The other one is matchesMethod method match. Both return the boolean result of matched.

use Ray\Aop\AbstractMatcher;
use Ray\Aop\Matcher;

class IsContainsMatcher extends AbstractMatcher
{
    /**
     * {@inheritdoc}
     */
    public function matchesClass(\ReflectionClass $class, array $arguments) : bool
    {
        [$contains] = $arguments;

        return (strpos($class->name, $contains) !== false);
    }

    /**
     * {@inheritdoc}
     */
    public function matchesMethod(\ReflectionMethod $method, array $arguments) : bool
    {
        [$contains] = $arguments;

        return (strpos($method->name, $contains) !== false);
    }
}

Interceptor Details

In an interceptor, a MethodInvocation object is passed to the invoke method:

class MyInterceptor implements MethodInterceptor
{
    public function invoke(MethodInvocation $invocation)
    {
        // Before method invocation
        $result = $invocation->proceed();
        // After method invocation
        return $result;
    }
}

$invocation->proceed() invokes the next interceptor in the chain. If no more interceptors are present, it calls the target method. This chaining allows multiple interceptors for a single method, executing in the order bound.

Example execution flow for interceptors A, B, and C:

  1. Interceptor A (before)
  2. Interceptor B (before)
  3. Interceptor C (before)
  4. Target method
  5. Interceptor C (after)
  6. Interceptor B (after)
  7. Interceptor A (after)

This chaining mechanism allows you to combine multiple cross-cutting concerns (like logging, security, and performance monitoring) for a single method.

With the MethodInvocation object, you can:

/** @var $method \Ray\Aop\ReflectionMethod */
$method = $invocation->getMethod();
/** @var $class \Ray\Aop\ReflectionClass */
$class = $invocation->getMethod()->getDeclaringClass();
  • $method->getAnnotations() - Get method attributes/annotations
  • $method->getAnnotation($name) - Get method attribute/annotation
  • $class->->getAnnotations() - Get class attributes/annotations
  • $class->->getAnnotation($name) - Get class attributes/annotation

Attributes

Ray.Aop uses PHP 8 Attributes for defining aspects. Doctrine annotations are no longer supported as of v2.15.

AOP Alliance

The method interceptor API implemented by Ray.Aop is a part of a public specification called AOP Alliance.

Requirements

  • PHP 8.2 or higher

Installation

The recommended way to install Ray.Aop is through Composer.

# Install Ray.Aop
$ composer require ray/aop ^2.0

Integrated DI framework

  • See also the DI framework Ray.Di which integrates DI and AOP.

Stability

Ray.Aop follows semantic versioning and ensures backward compatibility. Released in 2015, version 2.0 and its successors have maintained compatibility while evolving with PHP, and we remain committed to this stability.

  • Note: This documentation of the part is taken from Guice/AOP.

ray/aop 适用场景与选型建议

ray/aop 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 2.57M 次下载、GitHub Stars 达 104, 最近一次更新时间为 2012 年 03 月 06 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「aop」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 ray/aop 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 ray/aop 我们能提供哪些服务?
定制开发 / 二次开发

基于 ray/aop 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 2.57M
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 109
  • 点击次数: 31
  • 依赖项目数: 38
  • 推荐数: 0

GitHub 信息

  • Stars: 104
  • Watchers: 11
  • Forks: 30
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2012-03-06