如何使用phpDocumentor为Laravel包的Model编写规范文档注释
Laravel Eloquent 模型 phpDocumentor 文档块编写规范
核心思路和你当前处理访问器、内置属性的逻辑一致:隐藏Laravel框架层的实现细节,仅在类级别声明使用者可见的属性、方法,底层实现统一加@ignore标记。
关联关系(Relations)写法
关联支持两种调用方式,按如下规则处理:
- 类级别用
@property/@property-read声明属性调用的返回类型:一对一/ morphTo 等对一关联标注对应模型实例,一对多/多对多等对多关联标注Illuminate\Database\Eloquent\Collection实例 - 底层的关联方法可以保留返回类型声明,加
@ignore标记避免在文档的方法列表重复展示
示例代码:
/** * @property-read \App\Models\Profile $profile 用户关联的个人资料 * @property-read \Illuminate\Database\Eloquent\Collection<int, \App\Models\Post> $posts 用户发布的所有文章 */ class User extends Model { /** @ignore */ protected $fillable = ['name', 'email']; /** * @ignore * @return \Illuminate\Database\Eloquent\Relations\HasOne<\App\Models\Profile> */ public function profile() { return $this->hasOne(Profile::class); } /** * @ignore * @return \Illuminate\Database\Eloquent\Relations\HasMany<\App\Models\Post> */ public function posts() { return $this->hasMany(Post::class); } }
查询作用域(Scopes)写法
Scope调用时会自动去掉scope前缀、首字母小写,且第一个$query参数由框架自动注入,按如下规则处理:
- 类级别用
@method标签声明实际可调用的方法签名,标注入参和返回值类型 - 底层的
scopeXxx方法加@ignore标记,避免暴露不符合调用逻辑的方法签名
示例代码:
/** * @method static \Illuminate\Database\Eloquent\Builder<static> valid(bool $flag = true) 筛选状态有效的记录 * @method static \Illuminate\Database\Eloquent\Builder<static> categoryId(int $id) 筛选指定分类ID的记录 */ class Post extends Model { /** @ignore */ protected $casts = ['is_valid' => 'bool']; /** * @ignore * @param \Illuminate\Database\Eloquent\Builder<static> $query * @param bool $flag * @return \Illuminate\Database\Eloquent\Builder<static> */ public function scopeValid($query, $flag = true) { return $query->where('is_valid', $flag); } /** * @ignore * @param \Illuminate\Database\Eloquent\Builder<static> $query * @param int $id * @return \Illuminate\Database\Eloquent\Builder<static> */ public function scopeCategoryId($query, $id) { return $query->where('category_id', $id); } }
内容的提问来源于stack exchange,提问作者fudo
相关产品推荐
相关产品推荐

