PHP code example of twithers / laravel-php-attributes
1. Go to this page and download the library: Download twithers/laravel-php-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/ */
twithers / laravel-php-attributes example snippets
return [
/**
* Caching will make use of Laravel's built-in file caching. Using caching will be a massive performance benefit
* as no directories and files need to be scanned for attributes and attribute usages
*/
'use_cache' => true,
/**
* By default this will scan your listed directories below for all attributes and then search for them.
*
* If you want to avoid the initial search, you can list your attribute classes below:
* 'App\Attributes\Foo',
* App\Attributes\Bar::class,
*
*/
'attributes' => [
],
/**
* By default this will scan all files inside your app folder for attributes.
*
* If you want to limit the folders, you can adjust the namespace and the files:
* 'App\Http\Controllers' => app_path('Http/Controllers')
*/
'directories' => [
'App' => app_path(),
],
];
#[Attribute]
class SampleAttribute
{
public string $name;
public string $label;
public function __construct(
string $name,
string $label
){
$this->name = name;
$this->label = label;
}
}
#[SampleAttribute(name: 'SampleClass', label: 'My Sample Class Label')]
class SampleClass
{
#[SampleMethod(name: 'sampleMethod', label: 'My Sample Method Label')]
public function sampleMethod(): bool
{
return true;
}
}
$reflectionClass = new ReflectionClass(SampleClass::class);
$attributes = $reflectionClass->getAttributes(SampleMethod::class);
if (count($attributes)){
$attribute = $attributes[0]->newInstance();
dump($attribute->name); // "SampleClass"
dump($attribute->label); // "My Sample Class Label"
}
$reflectionClass = new ReflectionClass(SampleClass::class);
$reflectionMethod = $reflectionClass->getMethod('sampleMethod');
$attributes = $reflectionMethod->getAttributes(SampleMethod::class);
if (count($attributes)){
$attribute = $attributes[0]->newInstance();
dump($attribute->name); // "Sample Method"
dump($attribute->label); // "My Sample Method"
}