PHP code example of pollora / attributes

1. Go to this page and download the library: Download pollora/attributes 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/ */

    

pollora / attributes example snippets


use Pollora\Attributes\Action;
use Pollora\Attributes\PostType;
use Pollora\Attributes\PostType\AdminCol;
use Pollora\Attributes\PostType\HasArchive;
use Pollora\Attributes\PostType\ShowInRest;
use Pollora\Attributes\PostType\Supports;

#[PostType('book')]
#[HasArchive('library')]
#[ShowInRest]
#[Supports(['title', 'editor', 'thumbnail'])]
final class Book
{
    #[AdminCol('isbn', 'ISBN', sortable: true)]
    public function isbnColumn(int $postId): string
    {
        return (string) get_post_meta($postId, 'isbn', true);
    }

    #[Action('save_post_book')]
    public function onSave(int $postId): void {}
}

use Pollora\Attributes\Contracts\ConfiguresArguments;
use Pollora\Attributes\Contracts\ConfiguresArgumentsWithMethod;
use Pollora\Attributes\PostType;

$class = new ReflectionClass(Book::class);
$postType = $class->getAttributes(PostType::class)[0]->newInstance();
$arguments = [];

foreach ($class->getAttributes() as $attribute) {
    $instance = $attribute->newInstance();

    if ($instance instanceof ConfiguresArguments) {
        $arguments = $instance->configureArguments($arguments);
    }
}

foreach ($class->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
    foreach ($method->getAttributes() as $attribute) {
        $instance = $attribute->newInstance();

        if ($instance instanceof ConfiguresArgumentsWithMethod) {
            $arguments = $instance->configureArguments($arguments, [new Book, $method->getName()]);
        }
    }
}

register_post_type($postType->resolveSlug(Book::class), $arguments);
// ['has_archive' => 'library', 'show_in_rest' => true, 'supports' => [...], 'admin_cols' => ['isbn' => [...]]]