我一直试图使用GoAOP库一段时间,并且从未成功地让它工作。我已多次浏览documentation并复制了一些示例,但甚至无法让它们工作。我现在想要实现的只是一个简单的方面。
我有几个文件如下:
应用程序/ 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";
}
}
应用程序/使用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
中定义切入点错误(我尝试了几种变体),或者我是否对这段代码的工作方式有一个基本的误解。
非常感谢任何指导我正确方向的帮助。
答案 0 :(得分:0)
GoAOP框架旨在与自动加载器配合使用,这意味着它只能处理通过composer autoloader间接加载的类。
当您通过require_once './app/Example.php';
手动包含类时,PHP会立即加载类,并且无法通过AOP进行转换,因此没有任何反应,因为类已存在于PHP的内存中。
为了使AOP正常工作,您应该将类加载委托给Composer
并为您的类使用PSR-0 / PSR-4标准。在这种情况下,AOP将挂钩自动加载过程,并在需要时执行转换。
有关框架内部的其他详细信息,请参阅我对how AOP works in plain PHP that doesn't require any PECL-extentions的回答。这些信息对您有用。