Skip to content

feat: Add #[Computed] attribute for virtual model properties#245

Merged
techmahedy merged 2 commits intodoppar:3.xfrom
techmahedy:techmahedy-3.x
Apr 16, 2026
Merged

feat: Add #[Computed] attribute for virtual model properties#245
techmahedy merged 2 commits intodoppar:3.xfrom
techmahedy:techmahedy-3.x

Conversation

@techmahedy
Copy link
Copy Markdown
Member

What

Introduces #[Computed] — a method-level attribute that marks a model method as a virtual property. Computed properties are derived values that are never persisted to the database but are automatically included in toArray() and json_encode() output.

Why

Previously, virtual properties had to be appended manually or handled outside the model. There was no first-class way to declare derived attributes that serialize cleanly alongside real database columns.

How it works

class User extends Model
{
    #[Computed]
    public function fullName(): string
    {
        return $this->name . ' ' . $this->email;
    }
}

// Both access styles work
$user->full_name   // "John Doe"  ← snake_case
$user->fullName    // "John Doe"  ← camelCase works too

// toArray() / json_encode() always uses snake_case
$user->toArray();
// ['name' => '...', 'email' => '...', 'full_name' => 'John Doe']

// makeHidden respects both names
$user->makeHidden(['full_name'])->toArray();
$user->makeHidden(['fullName'])->toArray();  // either works

Behaviour

  • Method name is automatically converted to snake_case as the serialization key
  • Accessible via both $model->full_name and $model->fullName
  • Included in toArray() and json_encode() automatically
  • Never written to the database — invisible to dirty checking and save()
  • Supports makeHidden() by either the snake_case key or the method name
  • Reflection runs once per class and is statically cached

Files

  • Database/Entity/Attributes/Computed.php — new attribute
  • Database/Entity/Computed/InteractsWithComputedProperties.php — new trait
  • Database/Entity/Model.php — added trait, updated __get() and makeVisible()

@techmahedy techmahedy added the feat new feature label Apr 16, 2026
@techmahedy techmahedy merged commit 34dac0a into doppar:3.x Apr 16, 2026
25 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

feat new feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant