adiletmaks/annotations
Composer 安装命令:
composer require adiletmaks/annotations
包简介
The KISS PHP annotations library
README 文档
README
Minime\Annotations is the first KISS PHP annotations library.
Composer Installation
{
"require": {
"minime/annotations": "~3.0"
}
}
Through terminal: composer require minime/annotations:~3.0 🎱
Setup
First grab an instance of the Minime\Annotations\Reader the lazy way:
$reader = \Minime\Annotations\Reader::createFromDefaults();
Or instantiate the annotations reader yourself with:
use Minime\Annotations\Reader; use Minime\Annotations\Parser; use Minime\Annotations\Cache\ArrayCache; $reader = new Reader(new Parser, new ArrayCache);
Notice that Reader::createFromDefaults() creates a reader instance with array cache enabled.
On production you might want to use a persistent cache handler like FileCache instead:
use Minime\Annotations\Cache\FileCache; $reader->setCache(new FileCache('app/storage/path'));
Reading Annotations
Consider the following class with some docblock annotations:
<?php /** * @name Foo * @accept ["json", "xml", "csv"] * @delta .60 * @cache-duration 60 */ class FooController { /** * @manages Models\Baz */ protected $repository; /** * @get @post * @redirect Controllers\BarController@index */ public function index(){} }
Let's use the Minime\Annotations\Reader instance to read annotations from classes,
properties and methods. Like so:
$annotations = $reader->getClassAnnotations('FooController'); $annotations->get('name') // > string(3) "Foo" $annotations->get('accept') // > array(3){ [0] => "json" [1] => "xml" [2] => "csv" } $annotations->get('delta') // > double(0.60) $annotations->get('cache-duration') // > int(60) $annotations->get('undefined') // > null
The same applies to class properties...
$annotations = $reader->getPropertyAnnotations('FooController', 'repository'); $annotations->get('manages') // > string(10) "Models\Baz"
methods...
$annotations = $reader->getMethodAnnotations('FooController', 'index'); $annotations->get('get') // > bool(true) $annotations->get('post') // > bool(true) $annotations->get('auto-redirect') // > string(19) "BarController@index"
and functions || closures:
/** @name Foo */ function foo(){} $annotations = $reader->getFunctionAnnotations('foo'); $annotations->get('name') // > string(3) "Foo"
Managing Annotations
The annotations reader Reader::get(*)Annotations always returns AnnotationsBag
instances so you can easily manage annotations:
/** * @response.xml * @response.xls * @response.json * @response.csv * @method.get * @method.post */ class Foo {} $annotations = $reader->getClassAnnotations('Foo'); // object<AnnotationsBag>
Namespacing
It's a good idea to namespace custom annotations that belong to a package.
Later you can retrieve all those namespaced annotations using the AnnotationsBag api:
$AnnotationsBag->useNamespace('response')->toArray(); // > array(3){ // > ["xml"] => (bool) TRUE, // > ["xls"] => (bool) TRUE, // > ["json"] => (bool) TRUE, // > ["csv"] => (bool) TRUE // > }
Piping Filters
You can also easily "pipe" filters. This time let's "grep" all annotations beginning with "x" and within "response" namespace:
$AnnotationsBag->useNamespace('response')->grep('/^x/')->toArray(); // > array(3){ // > ["xml"] => (bool) TRUE, // > ["xls"] => (bool) TRUE // > }
Traversing results
As you might expect, AnnotationsBag is traversable too:
foreach($annotations->useNamespace('method') as $annotation => $value) { // some behavior }
Union
You can also perform union operations between two annotations sets:
$annotations->union($defaultAnnotations);
Please refer to annotations bag public API for more operations.
The Default Syntax
Which basically means that:
@line must start with a docblock annotation tag- must have an annotation identifier
- annotation identifier can have namespace with segments delimited by
.or\
- annotation identifier can have namespace with segments delimited by
- whitespace
- can have an annotation value
- value can have an optional type [
json,string,integer,float,->]- if absent, type is assumed from value
- whitespace
- optional value
- if absent,
trueis assumed
- if absent,
- value can have an optional type [
Some valid examples below:
/** * Basic docblock showing syntax recognized by the default Minime\Annotations\Parser * * @implicit-boolean * @explicit-boolean true * @explicit-boolean false * * @implicit-string-annotation hello world! * @explicit-string-annotation "hello world!" * @string-strong-typed-annotation string 123456 * * @integer-annotation 15 * @integer-strong-typed-annotation integer 15 * * @float-annotation 0.15 * @float-strong-typed float 15 * * @json-annotation { "foo" : ["bar", "baz"] } * @strong-typed-json-annotation json ["I", "must", "be", "valid", "json"] * * @namespaced.annotation hello! * * @multiline-json-annotation { * "foo" : [ * "bar", "baz" * ] * } * * @multiline-indented-string-annotation * ------ * < moo > * ------ * \ ^__^ * \ (oo)\_______ * (__)\ )\/\ * ||----w | * || || * * @Concrete\Class\Based\Annotation -> { "foo" : ["bar"] } */
Concrete Annotations
Sometimes you need your annotations to encapsulate logic and you can only do it by mapping
instructions to formal PHP classes. These kind of "concrete" typed annotations can be declared with
the -> (arrow symbol):
/** * @Model\Field\Validation -> { * "rules" : { * "required" : true, * "max-length" : 100 * } * } */
In the example above: when prompted, the annotation parser will instantiate a
new \Model\Field\Validation() following the declared JSON prototype { "rules" : {...} }.
Voilà! Instantly classy annotations.
Caching
This package comes with two basic cache handlers. ArrayCache (for testing) and a very simple FileCache
handler for persistence. Cache handlers can be set during Minime\Annotations\Reader instantiation:
use Minime\Annotations\Reader; use Minime\Annotations\Parser; use Minime\Annotations\Cache\FileCache; $cacheHandler = new FileCache('storage/path'); $reader = new Reader(new Parser, $cacheHandler);
Or later with Reader::setCache():
$reader->setCache(new FileCache);
Public API
Minime\Annotations\Reader
::getClassAnnotations($subject)
Get all annotations from a given class:
$reader->getClassAnnotations('Full\Qualified\Class');
::getPropertyAnnotations($subject, $propertyName)
Get all annotations from a given class property:
$reader->getPropertyAnnotations('Full\Qualified\Class', 'propertyName');
::getMethodAnnotations($subject, $methodName)
Get all annotations from a given class method:
$reader->getMethodAnnotations('Full\Qualified\Class', 'methodName');
::getFunctionAnnotations($fn)
Get all annotations from a given full qualified function name or closure:
$reader->getFunctionAnnotations('utils\foo');
::getCache()
::setCache(CacheInterface $cache)
::getParser()
::setParser(ParserInterface $cache)
Minime\Annotations\AnnotationsBag
::grep($pattern)
Filters annotations using a valid regular expression and returns a new AnnotationBag
with the matching results.
::useNamespace($pattern)
Isolates a given namespace of annotations. Basically this method filters annotations by a namespace
and returns a new AnnotationBag with simplified annotations identifiers.
::union(AnnotationsBag $bag)
Performs union operation with a subject AnnotationBag:
$annotations->union($defaultAnnotations);
::toArray()
::get($key, $default = null)
::getAsArray($key)
::has($key)
::set($key, $value)
::count
Minime\Annotations\Cache\FileCache
::__construct($storagePath = null)
See example in context with Minime\Annotations\Reader:
use Minime\Annotations\Cache\FileCache; $reader->setCache(new FileCache('app/tmp/storage/path'));
If no path is given OS tmp dir is assumed as cache storage path.
::clear()
Clears entire cache. See example in context with Minime\Annotations\Reader:
$reader->getCache()->clear();
Minime\Annotations\Cache\ArrayCache
::clear()
Clears entire cache. See example in context with Minime\Annotations\Reader:
$reader->getCache()->clear();
Contributions
Found a bug? Have an improvement? Take a look at the issues.
Guide
- Fork minime\annotations
- Clone forked repository
- Install composer dependencies
$ composer install - Run unit tests
$ phpunit - Modify code: correct bug, implement features
- Back to step 4
Copyright
Copyright (c) 2013-2014 Márcio Almada. Distributed under the terms of an MIT-style license. See LICENSE for details.
adiletmaks/annotations 适用场景与选型建议
adiletmaks/annotations 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 31 次下载、GitHub Stars 达 0, 最近一次更新时间为 2021 年 07 月 20 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「annotations」 「php」 「metadata」 「reflection」 「docblock」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 adiletmaks/annotations 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 adiletmaks/annotations 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 adiletmaks/annotations 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
A collection of helpers for PHPUnit to ease testing Tarantool libraries.
The last validation library you will ever need!
Yii2 Component to manage SEO data and metadata
Extremely simple meta tag generator.
Customizations for routing
This library parses phpdoc annotations and generates md document that can be parsed by slate
统计信息
- 总下载量: 31
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 6
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2021-07-20