我尝试使用GoAOP库已经有一段时间了,但从来没有成功地让它工作。我已经检查了documentation几次,并复制了一些示例,但都无法让它们正常工作。我现在想要实现的只有一个简单的方面。
我有几个文件,如下:
app/ApplicationAspectKernel.php
<?php
require './aspect/MonitorAspect.php';
use Go\Core\AspectKernel;
use Go\Core\AspectContainer;
/**
* Application Aspect Kernel
*/
class ApplicationAspectKernel extends AspectKernel
{
/**
* Configure an AspectContainer with advisors, aspects and pointcuts
*
* @param AspectContainer $container
*
* @return void
*/
protected function configureAop(AspectContainer $container)
{
$container->registerAspect(new Aspect\MonitorAspect());
}
}init.php
<?php
require './vendor/autoload.php';
require_once './ApplicationAspectKernel.php';
// Initialize an application aspect container
$applicationAspectKernel = ApplicationAspectKernel::getInstance();
$applicationAspectKernel->init(array(
'debug' => true, // Use 'false' for production mode
// Cache directory
'cacheDir' => __DIR__ . '/cache/', // Adjust this path if needed
// Include paths restricts the directories where aspects should be applied, or empty for all source files
'includePaths' => array(__DIR__ . '/app/')
));
require_once './app/Example.php';
$e = new Example();
$e->test1();
$e->test2('parameter');方面/MonitorAspect.php
<?php
namespace Aspect;
use Go\Aop\Aspect;
use Go\Aop\Intercept\FieldAccess;
use Go\Aop\Intercept\MethodInvocation;
use Go\Lang\Annotation\After;
use Go\Lang\Annotation\Before;
use Go\Lang\Annotation\Around;
use Go\Lang\Annotation\Pointcut;
/**
* Monitor aspect
*/
class MonitorAspect implements Aspect
{
/**
* Method that will be called before real method
*
* @param MethodInvocation $invocation Invocation
* @Before("execution(public Example->*(*))")
*/
public function beforeMethodExecution(MethodInvocation $invocation)
{
$obj = $invocation->getThis();
echo 'Calling Before Interceptor for method: ',
is_object($obj) ? get_class($obj) : $obj,
$invocation->getMethod()->isStatic() ? '::' : '->',
$invocation->getMethod()->getName(),
'()',
' with arguments: ',
json_encode($invocation->getArguments()),
"<br>\n";
}
}app/Example.php
<?php
class Example {
public function test1() {
print 'test1' . PHP_EOL;
}
public function test2($param) {
print $param . PHP_EOL;
}
}当我运行php init.php时,它确实会运行,但只打印,而不打印MonitorAspect的输出。我不知道我是否在@Before中定义了错误的切入点(我尝试了几种变体),或者我只是对这段代码应该如何工作有一个根本的误解。
如果你能帮我指明正确的方向,我将不胜感激。
发布于 2018-01-25 17:54:44
GoAOP框架被设计为使用自动加载器,这意味着它只能处理通过composer自动加载器间接加载的类。
当您通过require_once './app/Example.php';手动包含您的类时,PHP会立即加载类,因此不会发生任何事情,因为类已经存在于PHP的内存中。
为了让AOP正常工作,你应该将类加载委托给Composer,并对你的类使用PSR0/PSR4标准。在这种情况下,AOP将挂钩自动加载过程,并在需要时执行转换。
有关框架内部的更多详细信息,请参阅我对how AOP works in plain PHP that doesn't require any PECL-extentions的回答。这些信息对您应该很有用。
https://stackoverflow.com/questions/48437205
复制相似问题