tebru/dynamo

从基于 doctrine 注释的接口生成 PHP 类

v0.3.3 2016-03-22 19:58 UTC

This package is auto-updated.

Last update: 2024-09-24 12:12:00 UTC


README

Build Status Coverage Status

Dynamo

这个库允许您从一个带有 Doctrine 注释的接口生成一个类。它处理所有解析,并提供事件以便根据注释创建方法体。

安装

composer require tebru/dynamo

用法

使用构建器创建一个新的生成器对象

$generator = \Tebru\Dynamo\Generator::builder()
    ->namespacePrefix('My\Custom\Library')
    ->setCacheDir('path/to/cache/vendor-name')
    ->build();

构建器有很多不同的选项可以使用,但是,对于大多数情况,除了命名空间前缀和缓存目录之外,默认设置应该就足够了。

命名空间前缀是必需的,以便解决类名冲突。生成器使用完整的接口名称加上前缀作为生成的类名。默认前缀是 Dynamo

缓存目录的默认值为 /system/dir/dynamo

拥有生成器后,您可以将其接口名称传递给它,它将在您的缓存目录中创建一个文件

$generator->createAndWrite(MyInterface::class);

事件

订阅至少 MethodEvent 是必要的,因为它允许您向方法添加方法体。在事件中可访问 MethodModelAnnotationCollection

其他两个事件是 StartEventEndEvent,它们都提供对 ClassModel 的访问。

$eventDispatcher = new \Symfony\Component\EventDispatcher\EventDispatcher();
$eventDispatcher->addListener(new MethodListener());
    
$generator = \Tebru\Dynamo\Generator::builder()
    ->namespacePrefix('My\Custom\Library')
    ->setCacheDir('path/to/cache/vendor-name')
    ->setEventDispatcher($eventDispatcher)
    ->build();

示例监听器

以下是方法监听器的骨架

<?php
    
namespace Foo;

use Tebru\Dynamo\Event\MethodEvent;

class MethodListener
{
    public function __invoke(MethodEvent $event)
    {
        $methodModel = $event->getMethodModel();
        $annotationCollection = $event->getAnnotationCollection();
        
        $body = [];
        if ($annotation->collection->exists(MyAnnotation::class)) {
            $body[] = '$var = "annotation exists";';
        } else {
            $body[] = '$var = "annotation not exists";';
        }
        
        $methodModel->setBody(implode($body));
    }
}