PHP code example of zenstruck / class-metadata

1. Go to this page and download the library: Download zenstruck/class-metadata library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

zenstruck / class-metadata example snippets


namespace App\Entity;

use Zenstruck\Alias;
use Zenstruck\Metadata;

#[Alias('user')]
#[Metadata('track', true)]
#[Metadata('identifier', 'getId')]
class User
{
    // ...
}

use Zenstruck\Alias;

// alias for class lookup:
Alias::for(User::class); // "user" (string|null - the alias for User or null if none)
Alias::for(new User()); // "user" (alternatively, you can pass the object directly)

// class for alias lookup:
Alias::classFor('user'); // "App\Entity\User" (class-string|null - the FQCN whose alias is "user")

use Zenstruck\Metadata;

// metadata for a class
Metadata::for(User::class); // ['track' => true, 'identifier' => 'getId'] (array<string,scalar> - metadata array for User or empty array if none)
Metadata::for(new User()); // ['track' => true, 'identifier' => 'getId'] (alternatively, you can pass the object directly)
Metadata::for('user'); // ['track' => true, 'identifier' => 'getId'] (alternatively, fetch metadata by a class' alias)

// metadata value for key
Metadata::get(User::class, 'track'); // true (scalar|null - the metadata value for "key" or null if none)
Metadata::get(new User(), 'track'); // true (alternatively, you can pass the object directly)
Metadata::get('user', 'track'); // true (alternatively, fetch metadata by a class' alias)

// "first" metadata value for list of keys
Metadata::first(User::class, 'audit_id', 'identifier', 'id'); // "getId" (scalar|null - first metadata value found for" keys" (left to right) or null if none)
Metadata::first(new User(), 'audit_id', 'identifier', 'id'); // "getId" (alternatively, you can pass the object directly)
Metadata::first('user', 'audit_id', 'identifier', 'id'); // "getId" (alternatively, fetch metadata by a class' alias)

// all classes with metadata key
Metadata::classesWith('identifier'); // ["App\Entity\User"] (class-string[] - FQCN's that have metadata with key "identifier")

use Zenstruck\Metadata\Bridge\Doctrine\AliasManagerRegistry;

/** @var \Doctrine\Persistence\ManagerRegistry $inner */

$registry = new AliasManagerRegistry($inner);

$registry->getRepository('user'); // converts "user" alias to FQCN
$registry->getRepository(User::class); // can still use FQCN

$registry->getManagerForClass('user'); // converts "user" alias to FQCN
$registry->getManagerForClass(User::class); // can still use FQCN