Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Model Traits Laravel Package

ac/model-traits

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. 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;
    }
    
  2. 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"
    
  3. Where to Look First:

    • Review AutoGetterSetterTrait for automatic getter/setter generation.
    • Check AnnotatedGetterSetterTrait if you need fine-grained control over property access.

Implementation Patterns

Usage Patterns

  1. Dynamic Property Access: Use getX()/setX() for any property without manual definition:

    $model->setDynamicProperty('value');
    $value = $model->getDynamicProperty();
    
  2. 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
        }
    }
    
  3. Annotated Traits: Use @Getter/@Setter annotations to explicitly define accessors:

    /**
     * @Getter @Setter
     */
    protected $annotatedProperty;
    
  4. Mass Assignment: Leverage dynamic setters for bulk updates:

    $model->setAttributes([
        'name' => 'Bob',
        'age'  => 30,
    ]);
    

Workflows

  • API Resources: Use dynamic getters to auto-generate JSON responses without manual toArray().
  • Forms: Bind form inputs directly to model properties via dynamic setters.
  • Serialization: Simplify JSON/XML serialization with auto-generated accessors.

Integration Tips

  • Laravel Eloquent: Works seamlessly with Eloquent models (no extra config needed).
  • Validation: Use dynamic setters in form requests:
    $request->validate(['name' => 'required']);
    $model->setName($request->name);
    
  • Testing: Mock dynamic getters/setters in unit tests:
    $model->setTestProperty('value');
    $this->assertEquals('value', $model->getTestProperty());
    

Gotchas and Tips

Pitfalls

  1. Private Property Limitation: Private properties are only gettable (not settable) by default. Avoid relying on setX() for private fields.

  2. Naming Conflicts: Dynamic getters/setters may clash with existing methods. Prefix custom methods (e.g., customSetName()).

  3. Reflection Overhead: Heavy use of reflection can impact performance in tight loops. Cache reflection results if needed.

  4. Annotation Parsing: AnnotatedGetterSetterTrait requires PHPDoc annotations. Misspellings or syntax errors will break accessors.

Debugging

  • 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 Quirks

  • No Global Config: Traits are self-contained; no config/model-traits.php exists. Customize via model-specific logic.

Extension Points

  1. 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;
    }
    
  2. Property Filtering: Override getDynamicProperties() to exclude sensitive fields:

    protected function getDynamicProperties()
    {
        return array_diff($this->getProperties(), ['password']);
    }
    
  3. Event Hooks: Trigger events on dynamic setter calls:

    public function setName($name)
    {
        $this->fireModelEvent('settingName', $name);
        $this->name = $name;
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware