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

Accessible Laravel Package

antares/accessible

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require antares/accessible
    

    Register the Doctrine annotation loader (once in your project):

    $loader = require __DIR__ . '/vendor/autoload.php';
    Doctrine\Common\Annotations\AnnotationRegistry::registerLoader([$loader, 'loadClass']);
    
  2. Basic Usage: Add AutomatedBehaviorTrait to your model and annotate properties:

    use Accessible\AutomatedBehaviorTrait;
    
    class User {
        use AutomatedBehaviorTrait;
    
        /**
         * @Access({Access::GET, Access::SET})
         * @Assert\NotBlank
         */
        private $name;
    }
    

    Now getName()/setName() work automatically with validation.

  3. First Use Case: Replace repetitive getter/setter boilerplate for a single property:

    $user = new User();
    $user->setName('John'); // Validates via @Assert\NotBlank
    echo $user->getName();  // "John"
    

Implementation Patterns

Core Workflows

  1. Property Automation:

    • Replace manual getters/setters with @Access annotations.
    • Example: Convert 10+ properties to auto-generated methods in minutes.
  2. Validation Integration:

    • Use Symfony’s Assert annotations (e.g., @Assert\Email) directly in docblocks.
    • Example:
      /**
       * @Access({Access::SET})
       * @Assert\Email
       */
      private $email;
      
  3. Collections:

    • Annotate properties with @ListBehavior, @SetBehavior, or @MapBehavior.
    • Example:
      /**
       * @Access({Access::GET})
       * @ListBehavior
       * @Initialize({})
       */
      private $orders;
      
    • Automatically gains addOrder()/removeOrder() methods.
  4. Associations:

    • Bidirectional relationships via @Referenced/@InCollection.
    • Example (One-to-Many):
      class Author {
          /**
           * @Access({Access::GET, Access::SET})
           * @ListBehavior
           * @Referenced(className=Book::class, propertyName="author")
           */
          private $books;
      }
      
  5. Constructor Automation:

    • Use @Construct to auto-map constructor args to properties.
    • Example:
      /**
       * @Construct({"name", "email"})
       */
      class User { ... }
      $user = new User('Alice', 'alice@example.com');
      

Laravel-Specific Patterns

  1. Eloquent Models:

    • Extend AutomatedBehaviorTrait alongside Model:
      use Illuminate\Database\Eloquent\Model;
      use Accessible\AutomatedBehaviorTrait;
      
      class Post extends Model {
          use AutomatedBehaviorTrait;
          // Annotations here...
      }
      
    • Caution: Avoid conflicts with Laravel’s magic methods (e.g., setAttribute).
  2. Form Requests:

    • Validate incoming data via docblock annotations:
      class StorePostRequest extends FormRequest {
          /**
           * @Assert\NotBlank
           * @Assert\MaxLength(255)
           */
          public $title;
      }
      
  3. API Resources:

    • Use @Access({Access::GET}) to control serialization:
      class PostResource extends JsonResource {
          /**
           * @Access({Access::GET})
           */
          public $customField;
      }
      
  4. Service Layer:

    • Annotate DTOs or service classes to enforce contracts:
      class CreateUserCommand {
          /**
           * @Assert\Email
           */
          public $email;
      }
      

Gotchas and Tips

Pitfalls

  1. Annotation Loading:

    • Issue: Forgetting to register the Doctrine annotation loader causes silent failures.
    • Fix: Add this once in a bootstrapped file (e.g., bootstrap/app.php):
      $loader = require __DIR__.'/vendor/autoload.php';
      Doctrine\Common\Annotations\AnnotationRegistry::registerLoader([$loader, 'loadClass']);
      
  2. Method Conflicts:

    • Issue: Laravel’s magic methods (e.g., setAttribute) override auto-generated setters.
    • Fix: Explicitly define @Access({Access::GET, Access::SET}) and avoid naming collisions.
  3. Validation Timing:

    • Issue: @Assert annotations run only during setX() or constructor initialization.
    • Fix: Manually trigger validation with $object->validateProperty('propertyName').
  4. Circular References:

    • Issue: Bidirectional associations (@Referenced/@InCollection) can cause infinite loops.
    • Fix: Use updatePropertyAssociation() with caution or disable auto-updates:
      $this->updatePropertyAssociation('property', ['newValue' => $value], false);
      
  5. PHP 7+ Compatibility:

    • Issue: Older PHP versions may throw Undefined class constant errors for Access::GET.
    • Fix: Use fully qualified names:
      @Access({\Accessible\Annotation\Access::GET, \Accessible\Annotation\Access::SET})
      

Debugging Tips

  1. Enable Debug Mode:

    • Set Accessible\AutomatedBehaviorTrait::$debug = true to log generated methods.
  2. Inspect Generated Code:

    • Use get_class_methods($object) to verify auto-generated methods.
  3. Validation Errors:

    • Check Symfony’s ConstraintViolationList for detailed validation failures:
      try {
          $user->setEmail('invalid');
      } catch (\InvalidArgumentException $e) {
          $violations = $e->getConstraintViolations();
      }
      

Extension Points

  1. Custom Annotations:

    • Extend Accessible\Annotation\Annotation to create domain-specific rules.
  2. Override Default Behavior:

    • Subclass Accessible\AutomatedBehaviorTrait to modify method generation:
      class CustomBehaviorTrait extends AutomatedBehaviorTrait {
          protected function generateGetter($property) {
              // Custom logic
          }
      }
      
  3. Integration with Laravel Events:

    • Hook into setX() to trigger events:
      $user->setName('Bob');
      event(new UserNameUpdated($user));
      
  4. Dynamic Property Handling:

    • Use @Dynamic to generate methods for properties not defined in the class (advanced).

Performance Considerations

  1. Annotation Parsing:

    • Cache parsed annotations in Laravel’s cache (e.g., config/cache.php):
      'stores' => [
          'file' => [
              'path' => storage_path('framework/cache'),
              'tag' => 'accessible_annotations',
          ],
      ],
      
  2. Avoid Over-Annotation:

    • Limit @Access to only necessary properties to reduce reflection overhead.
  3. Disable for Non-CRUD Classes:

    • Skip AutomatedBehaviorTrait in read-only DTOs or value objects.

Laravel-Specific Quirks

  1. Model Events:

    • Auto-generated setters do not trigger Laravel’s saving/updated events.
    • Workaround: Use observing or accessors:
      public function setNameAttribute($value) {
          $this->attributes['name'] = $value;
          // Trigger custom logic
      }
      
  2. API Resources:

    • Auto-generated getters do not respect Laravel’s resource visibility rules.
    • Fix: Use explicit @Access annotations to control serialization.
  3. Database Hydration:

    • Auto-generated setters skip Laravel’s mass assignment protection.
    • Fix: Combine with $fillable or $guarded:
      protected $fillable = ['name']; // Only allow mass assignment for annotated properties
      
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours