tebru / dynamo
从基于 doctrine 注释的接口生成 PHP 类
v0.3.3
2016-03-22 19:58 UTC
Requires
- php: >= 5.4
- doctrine/annotations: ~1.0
- doctrine/collections: ^1.3
- nikic/php-parser: ~1.3
- symfony/event-dispatcher: ^2.3|~3.0
- symfony/filesystem: ~2.3|~3.0
- tebru/assert: ^0.2
Requires (Dev)
- php: >= 5.5
- mockery/mockery: ^0.9.4
- phpunit/phpunit: ^4.7
- satooshi/php-coveralls: ^0.6.1
README
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
是必要的,因为它允许您向方法添加方法体。在事件中可访问 MethodModel
和 AnnotationCollection
。
其他两个事件是 StartEvent
和 EndEvent
,它们都提供对 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)); } }