AOP

Thanks to the author of Hyperf for the submission.

Installation

  • Install aop-integration
composer require "hyperf/aop-integration: ^1.1"

Add AOP Configuration

We need to add the config.php configuration file under the config directory.

<?php

use Hyperf\Di\Annotation\AspectCollector;

return [
    'annotations' => [
        'scan' => [
            'paths' => [
                BASE_PATH . '/app',
            ],
            'ignore_annotations' => [
                'mixin',
            ],
            'class_map' => [
            ],
            'collectors' => [
                AspectCollector::class
            ],
        ],
    ],
    'aspects' => [
        // Add corresponding Aspects here
        app\aspect\DebugAspect::class,
    ]
];

Configure the Entry File start.php

We will place the initialization method below timezone, and omit other code below.

use Hyperf\AopIntegration\ClassLoader;

if ($timezone = config('app.default_timezone')) {
    date_default_timezone_set($timezone);
}

// Initialization
ClassLoader::init();

Testing

First, let's write the class to be intercepted.

<?php
namespace app\service;

class UserService
{
    public function first(): array
    {
        return ['id' => 1];
    }
}

Next, add the corresponding DebugAspect.

<?php
namespace app\aspect;

use app\service\UserService;
use Hyperf\Di\Aop\AbstractAspect;
use Hyperf\Di\Aop\ProceedingJoinPoint;

class DebugAspect extends AbstractAspect
{
    public $classes = [
        UserService::class . '::first',
    ];

    public function process(ProceedingJoinPoint $proceedingJoinPoint)
    {
        var_dump(11);
        return $proceedingJoinPoint->process();
    }
}

Then, edit the controller app/controller/IndexController.php.

<?php
namespace app\controller;

use app\service\UserService;
use support\Request;

class IndexController
{
    public function json(Request $request)
    {
        return json(['code' => 0, 'msg' => 'ok', 'data' => (new UserService())->first()]);
    }
}

Finally, configure the route.

<?php
use Webman\Route;

Route::any('/json', [app\controller\IndexController::class, 'json']);

Finally, start the server and test.

php start.php start
curl  http://127.0.0.1:8787/json