PHPackages                             stubbles/reflect - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. stubbles/reflect

ActiveLibrary

stubbles/reflect
================

Reflection helper functions and annotations.

v11.0.0(3mo ago)212.0k3BSD-3-ClausePHPPHP ^8.3CI passing

Since Jan 11Pushed 1mo ago2 watchersCompare

[ Source](https://github.com/stubbles/stubbles-reflect)[ Packagist](https://packagist.org/packages/stubbles/reflect)[ RSS](/packages/stubbles-reflect/feed)WikiDiscussions main Synced today

READMEChangelog (10)Dependencies (5)Versions (11)Used By (3)

stubbles/reflect
================

[](#stubblesreflect)

Reflection helper functions and annotations.

Build status
------------

[](#build-status)

[![Tests](https://github.com/stubbles/stubbles-reflect/workflows/Tests/badge.svg)](https://github.com/stubbles/stubbles-reflect/workflows/Tests/badge.svg)

[![Latest Stable Version](https://camo.githubusercontent.com/ff77e2723633c5b77733590efb076d30c245a3b5fc4d722987309ad4a46bf7ef/68747470733a2f2f706f7365722e707567782e6f72672f73747562626c65732f7265666c6563742f76657273696f6e2e706e67)](https://packagist.org/packages/stubbles/reflect) [![Latest Unstable Version](https://camo.githubusercontent.com/f6afd736749d7a02eb3bfb1557cb7bb881871a18ab518e814cdbc3de36b2e87f/68747470733a2f2f706f7365722e707567782e6f72672f73747562626c65732f7265666c6563742f762f756e737461626c652e706e67)](//packagist.org/packages/stubbles/reflect)

Installation
------------

[](#installation)

*stubbles/reflect* is distributed as [Composer](https://getcomposer.org/)package. To install it as a dependency of your package use the following command:

```
composer require "stubbles/reflect": "^11.0"

```

Requirements
------------

[](#requirements)

*stubbles/reflect* requires at least PHP 8.3.

Additionally it uses *[stubbles/sequence](https://github.com/stubbles/stubbles-sequence)*to return sequences from some of the functions, and *[stubbles/values](https://github.com/stubbles/stubbles-values)* to parse values from annotations.

Reflection helper functions
---------------------------

[](#reflection-helper-functions)

All functions are in namespace `stubbles\reflect`.

### `reflect()`

[](#reflect)

*Available since release 3.1.0*

To provide more convenience a function `stubbles\reflect\reflect()` is provided. It allows to reflect classes, objects and methods:

```
$refClass  = reflect('some\interesting\UserDefinedClass'); // creates instance of \ReflectionClass
$refObject = reflect($someObjectInstance); // creates instance of \ReflectionObject
$refMethod = reflect('some\interesting\UserDefinedClass', 'aMethod'); // creates instance of \ReflectionMethod
$refMethod = reflect($someObjectInstance, 'aMethod'); // same as line before
```

Since release 4.0.0, it also allows to reflect functions:

```
$refFunction = reflect('someFunction'); // creates instance of \ReflectionFunction
```

### `reflectConstructor(): \ReflectionMethod`

[](#reflectconstructor-reflectionmethod)

Shortcut for `reflect($someObject, '__construct')`

```
$refMethod =  reflectConstructor('some\interesting\UserDefinedClass'); // same as reflect('some\interesting\UserDefinedClass', '__construct');
$refMethod =  reflectConstructor($someObjectInstance); // same as reflect('some\interesting\UserDefinedClass', '__construct');
```

### `methodsOf($class, $filter = null): \stubbles\sequence\Sequence`

[](#methodsofclass-filter--null-stubblessequencesequence)

Returns a sequence of all methods of given class.

```
```

### `propertiesOf($class, $filter = null): \stubbles\sequence\Sequence`

[](#propertiesofclass-filter--null-stubblessequencesequence)

Returns a sequence of all properties of given class.

```
```

### `parametersOf($classOrFunction, $methodName = null): \stubbles\sequence\Sequence`

[](#parametersofclassorfunction-methodname--null-stubblessequencesequence)

Returns a sequence of all properties of given class.

```
```

### `parametersOfConstructor($class): \stubbles\sequence\Sequence`

[](#parametersofconstructorclass-stubblessequencesequence)

Shortcut for `parametersOf($classOrFunction, '__construct')`.

### `parameter($name, $classOrFunction, $methodName = null): \ReflectionParameter`

[](#parametername-classorfunction-methodname--null-reflectionparameter)

Returns parameter with given name from referenced function or method.

```
```

### `constructorParameter($name, $class): \ReflectionParameter`

[](#constructorparametername-class-reflectionparameter)

Shortcut for `parameter($name, $class, '__construct')`.

### `attributesOf($reflected, $methodName = null): Attributes`

[](#attributesofreflected-methodname--null-attributes)

*Available since release 11.1.0*

To get a list of all attributes of an attributable element call the `stubbles\reflect\attributesOf()` function. It returns an instance of `stubbles\reflect\Attributes` and supports the following invocations:

```
attributesOf('my\ExampleClass', 'aMethod'); // returns annotations of this method
attributesOf($exampleInstance, 'aMethod'); // returns annotations of this method
attributesOf('my\ExampleClass'); // returns annotations of this class
attributesOf($exampleInstance); // returns annotations of this class
attributesOf('my\examplefunction'); // returns annotations of this function
attributesOf($reflectionParameter); // returns annotations of this parameter
attributesOf($reflectionProperty); // returns annotations of this class property
```

The return value is an instance of `stubbles\reflect\Attributes`, which provides access to the attributes on the reflectable:

#### `contains(string $type): bool`

[](#containsstring-type-bool)

Returns true when the reflected has an attribute of the given type, and false when not.

#### `firstNamed(string $type): object`

[](#firstnamedstring-type-object)

Returns the first attribute instance of the given type on the reflected.

#### `named(string $type): object[]`

[](#namedstring-type-object)

Returns a list containing all attributes of the given type on the reflected.

#### `isEmpty(): bool`

[](#isempty-bool)

Returns true when the reflected doesn't have any attributes at all, false otherwise.

Annotations
-----------

[](#annotations)

*Deprecated since 11.1.0, will be removed with 12.0.0, use attributes instead.*

For details about the concept behind annotations see [annotations](http://en.wikipedia.org/wiki/Annotations) which contains a general introduction into the topic. For more details how to use this in a programming language see [Java annotations](http://en.wikipedia.org/wiki/Java_annotation).

### How to define an annotation

[](#how-to-define-an-annotation)

Annotations can be defined on every element that can get a docblock comment: functions, methods, classes and properties. Additionally it is possible to define annotations for parameters in the docblock comment of the function or method where the parameter is part of.

```
namespace my;
/**
 * Class to demonstrate how to define annotations
 *
 * @MyAnnotation
 */
class ExampleClass
{
    /**
     * an example property
     *
     * @var  string
     * @AnnotationWithValues(bar='dummy', baz=42, required=true)
     */
    protected $bar;

    /**
     * another example property
     *
     * @var  string
     * @AnnotationWithOneValue("anotherDummy")
     */
    protected $baz;

    /**
     * an example method
     *
     * @param  int  $param  a parameter
     * @CastedAnnotation[MyAnnotation]
     * @ParamAnnotation{param}(key='value')
     */
    public function aMethod($param)
    {
        // some code here
    }
}
```

In the above example you can see five different ways of defining an annotation. However, you can combine these ways as you like. You may have a casted annotation with no, one or more values. But lets go through all defined annotations.

- ***@MyAnnotation***This is an annotation without any value.
- ***@AnnotationWithValues(bar='dummy', baz=42, required=true)***This annotation has two values with the parameters bar, baz and required. One is a string, the other is an integer, and the last a boolean.
- ***@AnnotationWithOneValue("anotherDummy")***This annotation has only a single string value.
- ***@CastedAnnotation\[MyAnnotation\]***A casted annotation can be used distinguish between a marker and a hint which concrete actions the annotation consuming class should do. The first name is the marker, and the name part in square brackets denotes the action to follow.
- ***@ParamAnnotation{param}(key='value')***This annotation is a parameter annotation defined for the parameter `$param`of the method `aMethod()`. The name in the curly braces denotes the name of the parameter this annotation is for. Please be aware that this annotation is not available when retrieving it via `annotationsOf('Foo', 'aMethod')`, this will result in a `ReflectionException`.

In contrast to other implementations it is not required to create a separate class for the annotation.

### Read annotations

[](#read-annotations)

To get a list of all annotations of an annotatable element call the `stubbles\reflect\annotationsOf()` function. It returns an instance of `stubbles\reflect\annotation\Annotations` and supports the following invocations:

```
annotationsOf('my\ExampleClass', 'aMethod'); // returns annotations of this method
annotationsOf($exampleInstance, 'aMethod'); // returns annotations of this method
annotationsOf('my\ExampleClass'); // returns annotations of this class
annotationsOf($exampleInstance); // returns annotations of this class
annotationsOf('my\examplefunction'); // returns annotations of this function
annotationsOf($reflectionParameter); // returns annotations of this parameter
annotationsOf($reflectionProperty); // returns annotations of this class property
```

As convienience function to retrieve annotations of a class' constructor the function `stubbles\reflect\annotationsOfConstructorParameter()` can be used:

```
annotationsOfConstructorParameter('my\ExampleClass');
annotationsOfConstructorParameter($exampleInstance);
```

As convienience function to retrieve annotations of a function or method parameter the function 'stubbles\\reflect\\annotationsOfParameter()` can be used:

```
annotationsOfParameter('param', 'my\ExampleClass', 'aMethod');
annotationsOfParameter('param', $exampleInstance, 'aMethod');
annotationsOfParameter('param', 'someFunction');
```

### Read values from annotations

[](#read-values-from-annotations)

As seen above annotations can have values. If we take the `@AnnotationWithValues`from the class above this is how you can access them:

```
$annotation = annotationsOf(/** reflectable annotation source */);
echo $annotation->getBar(); // prints "dummy"
echo $annotation->bar; // prints "dummy"
echo $annotation->getValueByName('bar'); // prints "dummy"
if ($annotation->isRequired()) {
    echo 'Required!';
}
```

These are the possibilities:

- Boolean values can be retrieved using the method `is` followed by their name.
- Any other value types can be retrieved using the method `get` followed by their name, as property of the annotation class, or using the `getValueByName()`method. *Please note that boolean values can also be retrieved using the `get`method syntax, but most times it just doesn't look that good: `getRequired()`has a different connotation than `isRequired()` from the point of view of the reader of your code.*

In case the annotation has an unnamed value only it can be retrieved using `$annotation->value` or `$annotation->getValue()`.

Using the method syntax with `get` has the advantage that a default value can be supplied which will be returned in case a value with this name is not set:

```
echo $annotation->getAwesomeness('Roland TB-303'); // prints "Roland TB-303"
```

The default value for the `is` method syntax is `false`.

If values are optional their existence can be checked: `$annotation->hasValueByName('bar')` returns `true` if a value with the name *bar* is set, and `false` otherwise.

When parameter values are read they are parsed using `stubbles\values\Parse`from *[stubbles/values](https://github.com/stubbles/stubbles-values)*. See documentation of this package how values are parsed.

### Annotation cache

[](#annotation-cache)

As parsing annotations is quite expensive Stubbles will cache annotations once they are read. However, the cache by default works only on a per request base and is not persistent. In order to make the annotation cache persistent between different requests the application needs to provide an annotation cache persistence.

The simplest way to do so is to call `stubbles\reflect\annotation\persistAnnotationsInFile('/path/to/some/cachefile.cache')`which will then use the file named in the argument to persist the annotation cache inbetween requests.

If a cache file doesn't suit your needs you can also provide a different persistence. To do so, you need to call `stubbles\reflect\annotation\persistAnnotations()` and provide two functions, one which is able to read the data and return it, and another one which can receive data and store it. For a file cache implementation, this would look like this:

```
persistAnnotations(
        function() use($cacheFile)
        {
            if (file_exists($cacheFile)) {
                return unserialize(file_get_contents($cacheFile));
            }

            return [];
        },
        function(array $annotationData) use($cacheFile)
        {
            file_put_contents($cacheFile, serialize($annotationData));
        }
);
```

The first function must return the stored annotation data. If no such data is present it must return an empty array.

The second function must store passed annotation data.

**Please note that if you use a persistent annotation cache that you need to be able to clear this cache, as changes in your code on annotations will not lead to an update of the cached data. This might lead to confusion on why a changed annotation will not be respected when the code is executed.**

###  Health Score

56

—

FairBetter than 98% of packages

Maintenance86

Actively maintained with recent releases

Popularity25

Limited adoption so far

Community14

Small or concentrated contributor base

Maturity84

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 53.1% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~401 days

Recently: every ~550 days

Total

10

Last Release

112d ago

Major Versions

v7.0.0 → v8.0.02016-07-17

v8.0.2 → v9.0.02019-10-29

v9.2.0 → v10.0.02023-12-31

v10.0.0 → v11.0.02025-11-29

PHP version history (5 changes)v7.0.0PHP &gt;=5.6.0

v8.0.0PHP ^7.0

v9.0.0PHP ^7.3

v10.0.0PHP ^8.2

v11.0.0PHP ^8.3

### Community

Maintainers

![](https://www.gravatar.com/avatar/cde3f4e0a0e4454942288eb300c91644bd359cc3572d65b473e3484701fa4931?d=identicon)[mikey179](/maintainers/mikey179)

---

Top Contributors

[![mikey179](https://avatars.githubusercontent.com/u/190475?v=4)](https://github.com/mikey179 "mikey179 (43 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (38 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/stubbles-reflect/health.svg)

```
[![Health](https://phpackages.com/badges/stubbles-reflect/health.svg)](https://phpackages.com/packages/stubbles-reflect)
```

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
