1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

LaravelでカスタムAnnotationを定義

Last updated at Posted at 2021-11-19

今回、LaravelにてCSVの1行分を表すクラス(DTO的な)を定義する必要があって、CSVの1行を出力するために、列の出力順をプロパティごとに設定したなぁとおもったので、そのやり方をメモ。

Reference URL:
https://www.doctrine-project.org/projects/doctrine-annotations/en/1.13/index.html

Define Annotation class.

namespace App\Annotations;

/**
 * @Annotation
 */
class Order
{
    public int $value;
    public function __construct(array $values)
    {
        $this->value = $values['value'];
    }
}

Put annotation on the properties.

namespace App\Services\CsvRows;

use App\Annotations\Order;

class MemberPersonalInfoRow 
{
  /** @Order(1) */
  public string $id;

  /** @Order(2) */
  public string $name;

  /** @Order(3) */
  public string $phone_number;

  /** @Order(4) */
  public string $address;
}

Retrieve the annotation by property.

$reflectionClass  = new \ReflectionClass(MemberPersonalInfoRow::class);
$annotationReader = app(AnnotationReader::class);
foreach ($reflectionClass->getProperties() as $property) {
    $order = $annotationReader->getPropertyAnnotation($property, Order::class);
    if (is_null($order)) {
        continue;
    }
    /** @var $order Order */
    var_dump(
        $property->getName(),
        $order->value
    );
}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?