Installation:
composer require ac/model-traits:^0.2.0
Add the trait to your model:
use AC\ModelTraits\AutoGetterSetterTrait;
class User extends Model
{
use AutoGetterSetterTrait;
}
First Use Case: Define properties in your model (public/protected/private) and immediately use dynamic getters/setters:
$user = new User();
$user->setName('Alice'); // No explicit setter needed
echo $user->getName(); // "Alice"
Where to Look First:
AutoGetterSetterTrait for automatic getter/setter generation.AnnotatedGetterSetterTrait if you need fine-grained control over property access.Dynamic Property Access:
Use getX()/setX() for any property without manual definition:
$model->setDynamicProperty('value');
$value = $model->getDynamicProperty();
Partial Overrides: Override specific getters/setters while keeping others dynamic:
class User extends Model
{
use AutoGetterSetterTrait;
protected $email;
public function setEmail($email)
{
$this->email = Str::lower($email); // Custom logic
}
}
Annotated Traits:
Use @Getter/@Setter annotations to explicitly define accessors:
/**
* @Getter @Setter
*/
protected $annotatedProperty;
Mass Assignment: Leverage dynamic setters for bulk updates:
$model->setAttributes([
'name' => 'Bob',
'age' => 30,
]);
toArray().$request->validate(['name' => 'required']);
$model->setName($request->name);
$model->setTestProperty('value');
$this->assertEquals('value', $model->getTestProperty());
Private Property Limitation:
Private properties are only gettable (not settable) by default. Avoid relying on setX() for private fields.
Naming Conflicts:
Dynamic getters/setters may clash with existing methods. Prefix custom methods (e.g., customSetName()).
Reflection Overhead: Heavy use of reflection can impact performance in tight loops. Cache reflection results if needed.
Annotation Parsing:
AnnotatedGetterSetterTrait requires PHPDoc annotations. Misspellings or syntax errors will break accessors.
Missing Getters/Setters:
Verify property visibility (public/protected/private) matches expectations.
php artisan tinker
>>> $model->getProperties(); // Check available properties (if trait exposes this)
Annotation Errors:
Use phpdoc to validate annotations:
composer require --dev phpdocumentor/phpdocumentor
vendor/bin/phpdoc -d app/Models -t tmp/doc
config/model-traits.php exists. Customize via model-specific logic.Custom Accessors:
Extend traits to add logic (e.g., AutoGetterSetterTrait + SoftDeletes):
use AC\ModelTraits\{AutoGetterSetterTrait, SoftDeletesTrait};
class Model extends \Illuminate\Database\Eloquent\Model
{
use AutoGetterSetterTrait, SoftDeletesTrait;
}
Property Filtering:
Override getDynamicProperties() to exclude sensitive fields:
protected function getDynamicProperties()
{
return array_diff($this->getProperties(), ['password']);
}
Event Hooks: Trigger events on dynamic setter calls:
public function setName($name)
{
$this->fireModelEvent('settingName', $name);
$this->name = $name;
}
How can I help you explore Laravel packages today?