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

Laravel Dao Laravel Package

edstevo/laravel-dao

Laravel DAO layer for models, inspired by repository pattern. Adds caching, broadcast events, validation, and model/DAO generators to centralize data access and keep controllers flexible across Laravel apps.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require edstevo/laravel-dao
    

    Publish the config file:

    php artisan vendor:publish --provider="Edstevo\LaravelDao\LaravelDaoServiceProvider"
    
  2. Configure: Edit config/laravel-dao.php to set default cache driver (e.g., file, redis) and event broadcasting preferences.

  3. First Use Case: Generate a DAO for an existing model (e.g., User):

    php artisan dao:generate User
    

    This creates a UserDao class in app/Dao/UserDao.php with default methods (find(), all(), etc.) and a corresponding UserDaoServiceProvider.


Key Files to Review

  • Config: config/laravel-dao.php (cache, events, validation rules).
  • Generated DAOs: app/Dao/ (customize these for your logic).
  • Service Provider: app/Providers/DaoServiceProvider.php (register DAOs globally).

Implementation Patterns

Core Workflow

  1. DAO Generation: Use php artisan dao:generate ModelName to scaffold a DAO with:

    • Basic CRUD methods (find(), create(), update(), delete()).
    • Cache layer (e.g., find() checks cache before querying DB).
    • Event broadcasting (e.g., created, updated events).
  2. Customizing DAOs: Extend the generated DAO to add business logic:

    // app/Dao/UserDao.php
    class UserDao extends \Edstevo\LaravelDao\Dao
    {
        public function findActiveUsers()
        {
            return $this->model->where('active', 1)->get();
        }
    }
    
  3. Cache Integration: Leverage the built-in cache layer for read-heavy operations:

    // Automatically cached for 10 minutes
    $user = $this->userDao->find($id, 10);
    
  4. Validation: Define rules in the DAO’s rules() method:

    protected function rules()
    {
        return [
            'email' => 'required|email|unique:users',
            'password' => 'required|min:8',
        ];
    }
    
  5. Event Broadcasting: Events are auto-broadcasted for create, update, and delete operations. Listen via:

    // In an EventServiceProvider
    protected $listen = [
        'user.created' => [
            'App\Listeners\SendWelcomeEmail',
        ],
    ];
    

Integration Tips

  • Dependency Injection: Bind DAOs in app/Providers/DaoServiceProvider.php:

    $this->app->bind('App\Dao\UserDao', function ($app) {
        return new \App\Dao\UserDao(new \App\User);
    });
    

    Inject DAOs into controllers/services:

    public function __construct(UserDao $userDao) {
        $this->userDao = $userDao;
    }
    
  • Model Generators: Use php artisan dao:generate ModelName to auto-create DAOs for new models. Customize the stubs in vendor/edstevo/laravel-dao/src/stubs/.

  • Testing: Mock DAOs in tests to isolate logic:

    $this->mock(UserDao::class)->shouldReceive('find')->andReturn($user);
    

Gotchas and Tips

Pitfalls

  1. Outdated Package:

    • Last release in 2018 may cause compatibility issues with newer Laravel versions (e.g., 8/9/10).
    • Workaround: Fork the repo and update dependencies manually (e.g., laravel/framework, illuminate/cache).
  2. Cache Key Conflicts:

    • Default cache keys use model_name:id. Override in DAO:
      protected function getCacheKey($id)
      {
          return "custom_prefix:{$id}";
      }
      
  3. Event Broadcasting:

    • Requires Laravel’s queue system. Ensure QUEUE_CONNECTION is configured in .env.
    • Events may fire twice if not using a queue driver (e.g., sync).
  4. Validation Overrides:

    • Rules defined in rules() apply to create and update. For custom methods, manually validate:
      $validator = Validator::make($data, $this->customRules());
      
  5. Model Binding:

    • DAOs assume the model is bound to the DAO class name (e.g., UserDaoUser). Override getModel() if using a different naming convention:
      protected function getModel()
      {
          return new \App\Models\CustomUser();
      }
      

Debugging Tips

  1. Cache Issues:

    • Clear cache manually:
      php artisan cache:clear
      
    • Check cache keys in storage/framework/cache.
  2. Event Debugging:

    • Listen for events in Tinker:
      php artisan tinker
      Event::listen('user.created', function ($user) {
          echo "User created: {$user->id}\n";
      });
      
  3. DAO Method Overrides:

    • If a custom method isn’t working, ensure it’s not being overridden by a parent method. Use protected or public explicitly.

Extension Points

  1. Custom Cache Drivers: Extend the cache layer by overriding getCache() in your DAO:

    protected function getCache()
    {
        return Cache::store('redis')->rememberForever(...);
    }
    
  2. Dynamic Rules: Load validation rules from a separate file:

    protected function rules()
    {
        return require __DIR__ . '/validation_rules.php';
    }
    
  3. Observer Integration: Use DAO events to trigger observers:

    // In UserObserver
    public function created(User $user)
    {
        event(new UserCreated($user));
    }
    
  4. API Responses: Wrap DAO responses in API resources:

    public function find($id)
    {
        $user = parent::find($id);
        return new UserResource($user);
    }
    
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.
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
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle